VBA If Then Or Statements

我们两清 提交于 2019-12-14 03:11:50

问题


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


来源:https://stackoverflow.com/questions/15746368/vba-if-then-or-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!