Home » excel » excel – Run-time Error 91 – Object Variable or with Block variable not set – VBA

excel – Run-time Error 91 – Object Variable or with Block variable not set – VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have the following snippet VBA:

DatetoRun = InputBox("How far back do you want to run the MI for?", "Date backing", Format(Now(), "dd/mm/yyyy"))

'Date validation for DatetoRun
If IsDate(DatetoRun) Then       
    DatetoRun = Format(CDate(DatetoRun), "dd/mm/yyyy")
    dateStart = DatetoRun        
Else
    MsgBox "Please enter a DATE in the correct format dd/mm/yyyy"
End If

Set found = Range("A:A").Find(what:=DatetoRun, LookIn:=xlValues, lookat:=xlWhole)

iclearrow = found.Row

When executing it I keep getting the

Object Variable or With Block variable not set

which confuses me as I am setting it:

Set found = Range("A:A").Find(what:=DatetoRun, LookIn:=xlValues, lookat:=xlWhole)

The error happens on the last row:

iclearrow = found.Row

Not sure how or why this is happening. also sometime it will randomly work once, but then error out after. Nothing is consistent!

How to&Answers:

You need to have error handling scenario if Find failed to find DatetoRun in column A.

Set found = Range("A:A").Find(what:=DatetoRun, LookIn:=xlValues, lookat:=xlWhole)
If Not found Is Nothing Then ' find was successfull
    iclearrow = found.row
Else ' Find failed >> raise an error
    MsgBox "Unable to find " & DatetoRun, vbCritical
End If

Note: when searching for dates, they are actually stored as numeric values, so try using:

Set found = Range("A:A").Find(what:=CDbl(DatetoRun), LookIn:=xlValues, lookat:=xlWhole)

Edit 1: Try the following line of Find :

Set found = Range("A:A").Find(what:=DatetoRun, LookIn:=xlFormulas, lookat:=xlPart)

Answer:

What is the DatetoRun type of variable? I guess it is Variant.

As far as Find() and Date is following its own logic, converting values to string and searching them – Range.Find not making a difference between January and November (February and December) in VBA Excel, then it is a good idea to parse DatetoRun to Date after the conditions.

Like this:
DatetoRun = CDate(DatetoRun)
Then, it will always be “found” in Range("A:A"), if it is present there. The If Not found Is Nothing Then is a good idea to be present as well.