VBA if else不返回正确的值

时间:2013-11-25 21:11:51

标签: vba if-statement

尝试根据两个输入的值返回L,M,H值。这就是我所拥有的:

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

返回的值不是我需要的。例如,(0,291)当它应该明显为M.为什么?

时返回H.

2 个答案:

答案 0 :(得分:3)

中间变量的条件(即使它们是VBA解释器可接受的)几乎肯定不会产生您期望的结果。将所有这些条件更改为等效的形式:

variable condition constant

示例:更改

80 <= x <= 120

x >= 80 and x <= 120

答案 1 :(得分:1)

试试这个:

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