首页 > 解决方案 > If Not IsError(MATCH) 没有绕过错误。如何跳过未找到的 MATCHes?

问题描述

目标:查找输入到 Array 的列标题Headers,然后将这些列复制到新工作表上。

原始数据有 200 多列,手动获取它们是不行的,所以这只是在第一行搜索有问题的标题MATCH。如果没有找到标题,我RTE 1004: Application-defined or object defined error就上HeaderLoc = Match线了。

我试图将 HeaderLoc 更改为 Variant 以允许它假设一个错误值,但这不起作用。

未达到我的错误陷阱If Not IsError行 - 我还尝试在分配之前放置错误陷阱HeaderLoc


如何在不使用的情况下让错误继续前进On Error此外,这个解决方案似乎与这里许多其他接受的解决方案一致,所以想知道为什么它在这里不起作用,但在其他情况下起作用。是因为我的数组的分配方式吗?


Dim HeaderLoc as Long
Dim Headers   
Headers = Array("Header1", "Header2", Etc........)

Application.ScreenUpdating = False
    For i = LBound(Headers) To UBound(Headers)
        HeaderLoc = WorksheetFunction.Match(Headers(i), Raw.Rows(1), 0)
            If Not IsError(HeaderLoc) Then
                Raw.Range(Raw.Cells(2, HeaderLoc), Raw.Cells(LR, HeaderLoc)).Copy
                Des.Cells(2, i + 13).PasteSpecial xlPasteValues
            End If
    Next i
Application.ScreenUpdating = True

标签: excelvba

解决方案


要么跳过错误并测试0

Dim HeaderLoc As Long
Dim Headers

Headers = Array("Header1", "Header2", Etc........)

Application.ScreenUpdating = False
    For i = LBound(Headers) To UBound(Headers)
        HeaderLoc = 0
        On Error Resume Next
            HeaderLoc = WorksheetFunction.Match(Headers(i), Raw.Rows(1), 0)
        On Error GoTo 0
            If HeaderLoc > 0 Then
                Raw.Range(Raw.Cells(2, HeaderLoc), Raw.Cells(LR, HeaderLoc)).Copy
                Des.Cells(2, i + 13).PasteSpecial xlPasteValues
            End If
    Next i
Application.ScreenUpdating = True

或者使用 Application.Match 和一个变体变量。

Dim HeaderLoc As Variant
Dim Headers

Headers = Array("Header1", "Header2", Etc........)

Application.ScreenUpdating = False
    For i = LBound(Headers) To UBound(Headers)
        HeaderLoc = Application.Match(Headers(i), Raw.Rows(1), 0)
            If Not IsError(HeaderLoc) Then
                Raw.Range(Raw.Cells(2, HeaderLoc), Raw.Cells(LR, HeaderLoc)).Copy
                Des.Cells(2, i + 13).PasteSpecial xlPasteValues
            End If
    Next i
Application.ScreenUpdating = True

推荐阅读