I'm new to vba so am learning. I'm struggling to understand why this is failing in Excel 2016 and my research is drawing a blank. I have the following code
Option Explicit
Sub Range_End_Method()
Dim lRow As Long
Dim lCol As Long
Dim i As Integer
Dim rng As Range
Set rng = ActiveCell
lRow = Cells(Rows.Count, 1).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
Do While rng.Value <> Empty
If InStr(rng.Value, "Petrol") = 0 Then
currentRow = ActiveCell.Row
Worksheets("MySheet").Cells(currentRow, 5) = "Shopping"
Set rng = rng.Offset(1)
rng.Select
Else
currentRow = ActiveCell.Row
Worksheets("MySheet").Cells(currentRow, 9) = "Not Found"
Set rng = rng.Offset(1)
rng.Select
End If
Loop
End Sub
If I open the vba editor and type this into a "Microsoft Excel Objects" sheet I don't get an error. But if I run as a "Modules" naming my module as "m_End" I get an error thrown up saying
Compile Error
Variable not defined
The variable it highlights in vba editor is "currentRow" from the line in the first "If condition":
currentRow = ActiveCell.Row
I don't understand what the difference is and how to fix the error.
Any help would be appreciated.
Option Explicit
followed bySub yourSubName()
. That being the case, you never declarecurrentRow
as being a variable. If you don't haveOption Explicit
at the beginning, go toTools ► Options ► Editor ► Code Settings
and SelectRequire Variable Declaration
It will save you loads of time in the future. Perhaps in your sheet module you did not haveOption Explicit
– Ron Rosenfeld May 14 '17 at 11:57