如何在VBA中的if语句中使用OR

Jag*_*esh 0 excel vba excel-vba

我在下面的代码中是否正确使用了"OR".有人可以帮帮我吗?

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

Yow*_*E3K 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
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

与实际问题无关,但在回答评论中的进一步问题时:

如果数据中包含错误值,则无法将它们与字符串进行比较,因此您需要先测试错误.

例如:

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

    '...
Run Code Online (Sandbox Code Playgroud)

要么

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
Run Code Online (Sandbox Code Playgroud)