Excel Error 1004 in vba vlookup function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TonyRandom
    New Member
    • Mar 2008
    • 12

    #1

    Excel Error 1004 in vba vlookup function

    I hope I haven't posted this in the wrong section, but it is a VBA problem, so please forgive me if it should be elsewhere.
    I have two tabs in a spreadsheet, both containing lists of parts codes. I want to programatically compare the first list against the second, and where the code isn't found in the second list I want to append it to the end of the list.
    I have tried to trap the error 1004 that is raised when the part cannot be found in the list, and have created an on error goto jump to handle it, and this works on the first time it encounters the problem, but as soon as it hits it again, the error appears and the code stops.

    Here is the section of code i have written so far.

    Code:
        Sheets("Main").Select
        Range("A1").Select
        Range(Selection, Selection.End(xlDown)).Select
        Selection.Name = "AllParts"
        Sheets("ImportList").Select
        Range("A1").Select
        On Error GoTo AddPart
        FRow = Cells(Application.Rows.Count, 1).End(xlUp).Row
    AddPart:
        If Err.Number = 1004 Then
        myPartCode = ActiveCell.Value
        With Main
        With .Cells(.Rows.Count, 1).End(xlUp)(2, 1)
            .Value = myPartCode
        End With
        End With
        End If
        
        ActiveCell.Offset(1, 0).Select
        myPartCode = ""
        On Error GoTo AddPart
    
        For i = ActiveCell.Row To FRow
        myPartCode = Application.WorksheetFunction.VLookup(ActiveCell, Range("AllParts"), 1, False)
        
        Debug.Print myPartCode
        ActiveCell.Offset(1, 0).Select
        Next i
    The sheet named Main also has its codename set to Main.

    I cannot understand why the on error captures it once, then doesn't capture it the second time.
    This is completely baffling me, ane left me pulling out my hair.
  • NeoPa
    Recognized Expert Moderator MVP
    • Oct 2006
    • 32669

    #2
    Error code is supposed to reset the error. One of the Resume statements should be used. Using On Error to handle program flow is only an acceptable idea when you have a very good understanding of the Error handling facilities in VBA.

    I would recommend Error Code that does what's expected and manage the flow of the logic entirely separately.

    Comment

    Working...