VBA匹配函数查找不存在的值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VBA匹配函数查找不存在的值相关的知识,希望对你有一定的参考价值。

我有一些VBA代码执行与不同工作表的匹配。然后,使用从此匹配返回的行来确定If语句的结果。这是我的代码:

On Error Resume Next 'Accuracy Index Match Start
aMatchRow = Application.Match(summarySheet.Cells(accuracyRow, 3), aCommSheet.Range("C:C"), 0)
On Error GoTo 0

With summarySheet.Cells(accuracyRow, 15)
    If aMatchRow > 0 Then
        .Value = aCommSheet.Cells(aMatchRow, 15)
    Else
        .Value = "COMMENT REQUIRED"
    End If
End With

我遇到的问题是,即使没有匹配项,也会返回一个值。因此,例如,在summarySheet.Cells(accuracyRow, 3)aCommSheet.Range("C:C")中没有匹配的情况下,我仍然会返回一个行值,然后将其输入If语句,因此将错误的值返回给summarySheet.Cells(accuracyRow, 15)

如果没有匹配,则应执行“ELSE”。但无论如何,“如果”正在进行。

答案

要扩展@ GSerg的评论:

Dim m
m = Application.Match(summarySheet.Cells(accuracyRow, 3), aCommSheet.Range("C:C"), 0)


With summarySheet.Cells(accuracyRow, 15)
    If Not IsError(m) Then '<<< test for no match here
        .Value = aCommSheet.Cells(m, 15)
    Else
        .Value = "COMMENT REQUIRED"
    End If
End With

以上是关于VBA匹配函数查找不存在的值的主要内容,如果未能解决你的问题,请参考以下文章