首页 > 解决方案 > Excel vba 检查 Match 函数是否返回 NA - 宏崩溃:运行时错误 1004“应用程序定义或对象定义错误”

问题描述

我使用一个Match函数来查找包含数据的特定行:

Sub test

With ThisWorkbook.Worksheets("hide_rows")
 For i = 2 To 15
   MsgBox (Application.WorksheetFunction.Match(.Cells(i, 1).Value, _
                ThisWorkbook.Worksheets("Sheet1").Range("A:A"), 0)) 
 Next
End With

End Sub

从 i = 2 到 i=14 它工作正常。但是,excel中的字符串在.Cells(15, 1)给定的范围内找不到,这会导致 Runtime Error 1004 “Application-defined or Object-defined error错误。我试图通过检查它是否是#N/A第一个来修复它:

Sub test

With ThisWorkbook.Worksheets("hide_rows")
 For i = 2 To 15
   MsgBox (Application.WorksheetFunction.IsNA(Application.WorksheetFunction.Match(.Cells(i, 1).Value, _
                ThisWorkbook.Worksheets("Sheet1").Range("A:A")), 0)) 
 Next
End With

End Sub

它返回False第 2-14 行,但在第 15 行仍然崩溃。

同时,如果我只是Match在工作表中手动计算,然后检查结果是否#N/A正常:

Sub test()

With ThisWorkbook.Worksheets("hide_rows")
 For i = 2 To 15
   MsgBox (Application.WorksheetFunction.IsNA(.Cells(i, 7).Value))
 Next
End With

End Sub

标签: vbaexcel

解决方案


您需要先测试 的返回值,.Cells(i, 7).Value 然后再将其传递给WorksheetFunction.Match. 我还建议使用 VBA 函数IsError而不是WorksheetFunction.IsNA

With ThisWorkbook.Worksheets("hide_rows")
    For i = 2 To 15
        Dim result As Variant

        result = .Cells(i, 1).Value
        If IsError(result) Then
            'Do whatever
        Else
            MsgBox (Application.WorksheetFunction.Match(result, _
                    ThisWorkbook.Worksheets("Sheet1").Range("A:A"), 0))
        End If
    Next
End With

推荐阅读