2017-07-14 699 views
0

我在下面的代碼中是否正確使用「OR」。請有人幫助我嗎?如何在VBA中使用OR in if語句

If Cells(i, 3).Value = "BRITISH TELECOM" Or "CHRISTIES INTERNATIO" Or "DTAG" Or "IMAGINE COMMUNICATIONS CORP" Then 

回答

8

不,你沒有:

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 
+1

現在我想,如果我應該張貼我的選擇案例的答案???不,我會讓你把它關掉;) –

+1

@ShaiRado Happy? – YowE3K

+0

謝謝,我越來越類型不匹配錯誤(運行時錯誤'13':) – Jagadeesh