Schalton
Schalton

Reputation: 3104

VBA If Statements Condensed

Excel 2015, Access 2015

General State:

if s=t then
    LD = 0
    Exit Function
end if

Current State:

If s = t Then: LD = 0: Exit Function

Goal: Is there a way to condense multiple conditional statements into one line without essentially falsifying a return? I'm looking for a more elegant solution.


Inspiration: C Code from https://en.wikipedia.org/wiki/Levenshtein_distance

for (int j = 0; j < t.Length; j++)
{
    var cost = (s[i] == t[j]) ? 0 : 1;
    v1[j + 1] = Minimum(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);
}

Changed into this in VBA:

For j = 0 To Len(t) - 1
    If Mid$(s, i + 1, 1) = Mid$(t, j + 1, 1) Then cost = 0 Else cost = 1
    v1(j + 1) = VBAMin(v1(j) + 1, v0(j + 1) + 1, v0(j) + cost)
Next j

Upvotes: 0

Views: 528

Answers (2)

EEM
EEM

Reputation: 6659

Try this

 cost = IIf(Mid$(s, I + 1, 1) = Mid$(t, J + 1, 1), 0, 1)

Upvotes: 1

Demetri
Demetri

Reputation: 859

I sometimes do something like the below:

(I know most people would argue it is poor programming)

If s = t _
      Then LD = 0:Exit Function _
      Else If a=b _
                Then LD = 1 _
                Else If c=d then LD = 2 Else LD = 3:Exit Function

Upvotes: 1

Related Questions