vba 如何在具有多个条件的excel VBA中编写OR语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24029856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Write OR statement in excel VBA with multiple conditions
提问by user1986119
How to Write OR statement in excel VBA with multiple conditions. I tried it as
如何在具有多个条件的 Excel VBA 中编写 OR 语句。我试过了
For i = 1 To 30
a = Sheets("Interface").Range("A" & i).Value
If (Sheets("Interface").Range("A" & i).Value Like "Street*name") Or _
(UCase(Sheets("Interface").Range("A" & i).Value) Like "Street*address") Or _
(UCase(Sheets("Interface").Range("A" & i).Value) Like "address") Then
'If a Like "*Street*address*" Then
Sheets("Interface").Range("B" & i).Value = "STREETNAME"
End If
Next i
I tried it with simple street*address statement(comment code) but it didn't get into the true code.whats wrong with this code.
我用简单的 street*address 语句(注释代码)尝试了它,但它没有进入真正的代码。这段代码有什么问题。
回答by Tim Williams
Something like this:
像这样的东西:
For i = 1 To 30
a = UCase(Sheets("Interface").Range("A" & i).Value)
If a Like "STREET*NAME" Or a Like "STREET*ADDRESS" Or _
a Like "ADDRESS" Then
Sheets("Interface").Range("B" & i).Value = "STREETNAME"
End If
Next i
回答by LimaNightHawk
The problem with VB/VBA is that if you write compound Or statements like this, VB will evaluate every condition, even if the first condition is found to be True. It won't short-circuit.
VB/VBA 的问题在于,如果您编写这样的复合 Or 语句,VB 将评估每个条件,即使发现第一个条件为 True。它不会短路。
It's a bit unconventional, but if you want a short-circuit method, you can use a Select Case, like this:
这有点标新立异,但是如果你想要一个短路的方法,你可以使用一个 Select Case,像这样:
Select Case True
Case a Like b, _
a Like c, _
a Like d, _
Debug.Print "True"
Case Else
Debug.Print "False"
End Select