0
我在下面的代碼中是否正確使用「OR」。請有人幫助我嗎?如何在VBA中使用OR in if語句
If Cells(i, 3).Value = "BRITISH TELECOM" Or "CHRISTIES INTERNATIO" Or "DTAG" Or "IMAGINE COMMUNICATIONS CORP" Then
我在下面的代碼中是否正確使用「OR」。請有人幫助我嗎?如何在VBA中使用OR in if語句
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
現在我想,如果我應該張貼我的選擇案例的答案???不,我會讓你把它關掉;) –
@ShaiRado Happy? – YowE3K
謝謝,我越來越類型不匹配錯誤(運行時錯誤'13':) – Jagadeesh