jluk
jluk

Reputation: 1030

VBA if else doesn't return correct values

Trying to return a L, M, H value based on the values of two inputs. Here is what I have:

If (80 <= x <= 120 And y > 120) Or (x > 120 And y > 120) Or (x > 120 And 80 <= y <= 120) Then
    CDI = "H"

ElseIf (x < 80 And y <= 120) Or (x < 120 And y < 80) Then
    CDI = "L"

ElseIf (x < 80 And y > 120) Or (80 <= x <= 120 And 80 <= y <= 120) Or (x > 120 And y < 80) Then
    CDI = "M"

End If

The values being returned aren't what I need. For example, (0,291) returns H when it should clearly be M. Why?

Upvotes: 2

Views: 88

Answers (2)

rawdog
rawdog

Reputation: 732

Try this:

If (x >= 80 And x <= 120 And y > 120) Or (x > 120 And y > 120) Or (x > 120 And y >= 80 And y <= 120) Then
    CDI = "H"

ElseIf (x < 80 And y <= 120) Or (x < 120 And y < 80) Then
    CDI = "L"

ElseIf (x < 80 And y > 120) Or (x >= 80 And x <= 120 And y >= 80 And y <= 120) Or (x > 120 And y < 80) Then
    CDI = "M"

End If

Upvotes: 1

Robert Harvey
Robert Harvey

Reputation: 180788

The conditions with the variable in the middle (even if they are acceptable to the VBA interpreter) are almost certainly not going to produce the result you expect. Change all such conditions to the equivalent of the form:

variable condition constant

Example: Change

80 <= x <= 120

to

x >= 80 and x <= 120

Upvotes: 3

Related Questions