VBA,避免在IF语句中重复AND

时间:2018-12-22 19:04:35

标签: vba if-statement

在编辑VBA代码时,我需要一些帮助。我想做的是避免在IF语句中重复AND。

到目前为止,我已经拥有了它,并且它就像一种魅力。

If Range("B1") <> "MatDescr" And Range("B2") <> "MatDescr" And Range("B3") <> "MatDescr" Then
MsgBox "Column 'B' does not contain MatDescr"
...rest of the code...

因此,如上所述,我想避免在代码内使用太多AND,因为我也必须在其他一些代码中编写它。 我现在想到的是通过编写以下代码来缩短代码:

Dim s As Integer 
For s = 1 To 3
If Cells(s, 2) <> "MatDescr" Then
next s 
rest of the code

这看起来好多了,但是通过这种方式,VBA在我尝试使用OR而不是AND时看到了该语句。这不是我的目标。

4 个答案:

答案 0 :(得分:2)

在这种情况下,您真正​​想知道您的值"MatDescr"是否出现在B1:B3范围内,您可以使用以下代码进行测试。

If ActiveSheet.Range("B1:B3").Find("MatDescr") Is Nothing Then
    MsgBox "Column 'B' does not contain MatDescr"
End If

我冒昧地将隐式调用插入ActiveSheet,在这里您使用的是不合格的Range调用。 Range.Find方法搜索包含目标值的第一个单元格,如果找不到结果,则返回Nothing

答案 1 :(得分:1)

它可以是evaluated这样的Excel数组公式:

If [AND(B1:B3 <> "MatDescr")] Then

答案 2 :(得分:1)

If Application.CountIf([B1:B3], "MatDescr") = 0 Then

答案 3 :(得分:0)

您也可以使用Match

If IsError(Application.Match("MatDescr", ActiveSheet.Range("B1:B3"),0)) Then MsgBox "Column 'B' does not contain MatDescr"
相关问题