Learning some VBA. So far, I’ve constructed this piece of code which should allow me (though it does not, yet) to do the following thing:
- Get the number in the
"M" & icell (in the first iteration it is M5). - Find that number in the A column.
- Once it finds it, set the value of
PutHereIfFoundthe same as the value of F6 (hence the offset). - If a number is found, then increment i in order for the loop to continue searching for M6, M7, … all up to cell M20.
It’s returning a Run-Time Error 91, which stands for Object Variable or With Variable not set. When I debug, it points to the Set PuthereIfFound line.
What is the reason for this mistake?
Sub FindThis()
Dim FindThis As Range
Dim PutHereIfFound As Range
Dim i As Integer
Dim f As Integer
i = 5
f = 5
Do
Set FindThis = ActiveSheet.Range("M" & i)
Set PutHereIfFound = ActiveSheet.Range("N" & i)
With ActiveSheet.Range("A:A")
Set PutHereIfFound = .Find(What:=FindThis, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False).Offset(0, 5)
If Not PutHereIfFound Is Nothing Then
i = i + 1
Else
i = i
End If
End With
Loop While i <= 20
End Sub
Further to my comment, your code can be optimized like this.