vba 如何在VBA中的if语句中使用OR
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45099602/
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 use OR in if statement in VBA
提问by Jagadeesh
Did I use "OR" correctly in my below code. Could someone help me please?
我在下面的代码中是否正确使用了“OR”。有人可以帮我吗?
If Cells(i, 3).Value = "BRITISH TELECOM" Or "CHRISTIES INTERNATIO" Or "DTAG" Or "IMAGINE COMMUNICATIONS CORP" Then
回答by YowE3K
No, you didn't:
不,你没有:
If Cells(i, 3).Value = "BRITISH TELECOM" Or _
Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
Cells(i, 3).Value = "DTAG" Or _
Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then
An alternative would be to use a Select Case
statement. These are especially useful if you have many conditions to test:
另一种方法是使用Select Case
语句。如果您有许多条件要测试,这些特别有用:
Select Case Cells(i, 3).Value
Case "BRITISH TELECOM", _
"CHRISTIES INTERNATIO", _
"DTAG", _
"IMAGINE COMMUNICATIONS CORP"
'Do something
Case "Some other string", _
"and another string"
'Do something else
Case Else
'Do something if none of the other statements evaluated to True
End Select
That Select Case
statement would be equivalent to the following If
statement:
该Select Case
语句等效于以下If
语句:
If Cells(i, 3).Value = "BRITISH TELECOM" Or _
Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
Cells(i, 3).Value = "DTAG" Or _
Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then
'Do something
ElseIf Cells(i, 3).Value = "Some other string" Or _
Cells(i, 3).Value = "and another string" Then
'Do something else
Else
'Do something if none of the other statements evaluated to True
End If
Unrelated to the actual question, but in response to a further question in comments:
与实际问题无关,但在回应评论中的另一个问题时:
If you have error values in your data, they will not be able to be compared to Strings, so you will need to test for errors first.
如果您的数据中有错误值,它们将无法与字符串进行比较,因此您需要先测试错误。
For example:
例如:
If IsError(Cells(i, 3).Value) Then
'Do whatever you want to do with error values such as #N/A
ElseIf Cells(i, 3).Value = "BRITISH TELECOM" Or _
Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
Cells(i, 3).Value = "DTAG" Or _
Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then
'...
or
或者
If IsError(Cells(i, 3).Value) Then
'Do whatever you want to do with error values such as #N/A
Else
Select Case Cells(i, 3).Value
Case "BRITISH TELECOM", _
"CHRISTIES INTERNATIO", _
"DTAG", _
"IMAGINE COMMUNICATIONS CORP"
'Do something
Case "Some other string", _
"and another string"
'Do something else
Case Else
'Do something if none of the other statements evaluated to True
End Select
End If