VBA If Then Or Statements

2019-09-06 17:19发布

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? :(

2条回答
我只想做你的唯一
2楼-- · 2019-09-06 17:55

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.

查看更多
倾城 Initia
3楼-- · 2019-09-06 17:56

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
查看更多
登录 后发表回答