[英]How to use OR in if statement in VBA
我在下面的代碼中正確使用了“ OR”嗎? 有人可以幫我嗎?
If Cells(i, 3).Value = "BRITISH TELECOM" Or "CHRISTIES INTERNATIO" Or "DTAG" Or "IMAGINE COMMUNICATIONS CORP" Then
不,您沒有:
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
一種替代方法是使用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
該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
與實際問題無關,但針對評論中的其他問題:
如果您的數據中有錯誤值,則無法將它們與字符串進行比較,因此您需要首先測試錯誤。
例如:
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
'...
要么
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.