Search code examples
excelvbavariablesruntime-errorrow

Defining an integer for last row in column


I'm getting Run-time error '1004': Application-defined or object-defined error on the following code (where I define lr) and cannot for the life of me work out the problem.

The aim of the code is to search for a matching Project Description in column defined as "ProjectDescriptionColumn", and to return a Project Code that lives in the cell of the same row but in column defined as "ProjectCodeColumn"

Any help greatly appreciated.

Dim ProjectDescriptionColumn As Long
Dim ProjectCodeColumn As Long

With Sheets("Completed")
If Cells(LastRowInL, "M").Value = "Engine Ancillaries" Then ProjectDescriptionColumn = 8 And ProjectCodeColumn = 9
End With

Dim lr As Integer
Dim i As Integer

lr = Sheets("VBA_Data").Cells(1, ProjectDescriptionColumn).End(xlDown).Row '<<<Run-time error here>>>

For i = 1 To lr

If UCase(Range(Sheets("Completed").Cells(LastRowInL, "B")).Value) = UCase(Sheets("VBA_Data").Cells(i, ProjectDescriptionColumn).Value) Then
Range(Sheets("Completed").Cells(LastRowInL, "N")).Value = Sheets("VBA_Data").Cells(i, ProjectCodeColumn).Value
End If
Next i

Solution

  • If the If statement isn't true, the column variables are never set. For me, that creates an index error, not a 1004. But a run-time error is surely related to the values plugged into the statement at the time. Can you step through the code to that point, and check the value of ProjectDescriptionColumn ?