繁体   English   中英

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

[英]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.

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