如何在VBA中的if语句中使用OR [英] How to use OR in if statement in VBA

查看:346
本文介绍了如何在VBA中的if语句中使用OR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

不,您没有:

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 语句.如果您要测试的条件很多,这些功能特别有用:


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

Select Case 语句等同于以下 If 语句:

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


与实际问题无关,但针对评论中的另一个问题:

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

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.

例如:

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

这篇关于如何在VBA中的if语句中使用OR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆