Home » excel » excel – If Not IsError(MATCH) is not bypassing the error. How to skip unfound MATCHes?

excel – If Not IsError(MATCH) is not bypassing the error. How to skip unfound MATCHes?

Posted by: admin May 14, 2020 Leave a comment

Questions:

Aim: Find column headers input into Array Headers and then copy those columns onto a new sheet.

The raw data has 200+ columns and fetching them manually is a no-go so this just searches the first row for the header in question with MATCH. If the header is not found, I am getting RTE 1004: Application-defined or object defined error on the HeaderLoc = Match line.

I have tried to change HeaderLoc to Variant to allow for it to assume an error value but this is not working.

My error trap If Not IsError line is not being reached – I have also tried to put the error trap before assigning HeaderLoc


How do I get the error to move on without using On Error? Also, this solution seems to be in align with many others accepted solutions here, so wondering why it’s not working here but does in other instances. Is it due to the way my array is assigned?


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
How to&Answers:

Either skip the error and test for 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

Or use Application.Match and a variant variable.

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