Excel VBA Run-Time Error 1004 during For Loop: Application-defined or object-defined error

Viewed 25

I am receiving the 1004 Application-defined or object-defined error when running a Sub that contains a For Loop. When I remove the For Loop I no longer get the error so I assume this is causing it.

Note that when I run the sub, it works (it runs the loop with expected results) but it still returns the error.

Here is the full code:

Sub MondayBreakfast_Ingredients()

'Select the lookup value

    Dim Breakfast As String
    Breakfast = Worksheets(1).Range("C3").Value

'Select the Ingredients table

    Dim startrow As Long
    startrow = 12

    Dim LR As Long
    LR = Worksheets(2).Cells(startrow, 2).End(xlDown).Row
    
    Dim recipe_names As Range
    Set recipe_names = Worksheets(2).Range("B" & startrow & ":B" & LR)
    
'Number of columns to loop through

    Dim currentrow As Long
    currentrow = Application.WorksheetFunction.Match(Breakfast, recipe_names, 0) + startrow - 1
    
    Dim numbercolumns As Long
    numbercolumns = Worksheets(2).Cells(currentrow, 2).End(xlToRight).Column
    
'Create loop

    For StartNumber = 2 To numbercolumns
        
        rownumber = StartNumber + 7
    
        Worksheets(1).Cells(rownumber, "E").Value = _
        Application.WorksheetFunction.VLookup(Breakfast, recipe_names.CurrentRegion, StartNumber, False)
        
    Next StartNumber
    
End Sub

Here is the line that receives the error:

'Create loop

    For StartNumber = 2 To numbercolumns
        
        rownumber = StartNumber + 7
    
        Worksheets(1).Cells(rownumber, "E").Value = _
        Application.WorksheetFunction.VLookup(Breakfast, recipe_names.CurrentRegion, StartNumber, False)
        
    Next StartNumber
    
0 Answers
Related