VBA If Then Or Statements

2019-09-06 17:34发布

问题:

VBA beginner here. I'm trying to do a pretty simple if/then statement in VBA 2003, but I'm running into the issue. My code reads:

Dim var as Integer
If var = 1 or 2 Then
    'Do stuff
Else
    MsgBox ("error")

I keep running into the issue with the or statement. If I change it to var = 1, the code runs without a hitch; if I rewrite it as

If var = 1 or var = 2

then it works fine. But as I would like to expand this, being able to write this in a more cohesive way would be great. What am I missing? :(

回答1:

You need to write it as:

If var = 1 or var = 2

because or connects two conditions, not two values that form part of the same condition.



回答2:

If you want cleaner code, you can use a case expression instead:

select case var 
    case 1, 2
        'Do stuff
    case else
        MsgBox ("error")
end select