简体   繁体   中英

How to use OR in if statement in VBA

Did I use "OR" correctly in my below code. Could someone help me please?

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

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 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM