vba - 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
解决方案
您需要先测试 的返回值,.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
推荐阅读
- c# - Binding a setter value inside a trigger to an element
- ssl - Squeak-5.2 can't connect to https://github.com/
- apache-spark - How to debug the apache spark when it stuck at the certain line?
- html - Empty post title Wordpress
- python - 如何在 9.414 版本中使用 executemany 忽略 postgres 中的重复项?
- javascript - $ character in ReactJs
- redundancy - 在链接失败的情况下将请求重定向到其他 IP 地址
- python - TensorFlow 在集群上运行(40k 核心,500TFLOP/s 和 40k RAM)与 NVIDIA GTX 1080
- swift - 如何动态更改 PageViewController 中的背景?
- reactjs - 会话存储无法保存在 reactjs 应用程序中