VBA for Excel throws "Object variable or with block variable not set" when there is no Object

wardzin picture wardzin · Mar 29, 2014 · Viewed 89.8k times · Source

In my code, I have declared these variables:

Dim Field_Name, Datatype, row As Integer

Then, inside a For loop, I have this code:

Field_Name = Worksheets(i).UsedRange.Find("Field Name").Column
Datatype = Worksheets(i).UsedRange.Find("Datatype").Column
row = Worksheets(i).UsedRange.Find("Field Name").row + 1

However, that code throws the "Object variable or with block variable not set" run-time error. According to the API, the Range.Column and Range.row property is a read-only Long. I have tried making the datatype of my variables to Long, but with no success. It would appear that VBA expecting me to do

Set Field_Name = Worksheets(i).UsedRange.Find("Field Name").Column
Set Datatype = Worksheets(i).UsedRange.Find("Datatype").Column
Set row = Worksheets(i).UsedRange.Find("Field Name").row + 1

However, said variables are not objects, so doing that throws the "Object required" compile error.

Any help with this would be greatly appreciated. If you're not sure about how to fix it, then any workarounds or alternative ways to get the column number and row number of a cell would be greatly appreciated.

Answer

Matroid picture Matroid · May 24, 2016

Even though this is an old question, I'd like to say something too.

I had the same problem to get this error while using the .Find method. I came to this question and so others will do the same.

I found a simple solution to the problem:

When Find does not find the specified string it returns Nothing. Calling anything directly after Find will lead to this error. So, your .Column or .row will throw an error.

In my case I wanted an Offset of the found cell and solved it this way:

Set result = Worksheets(i).Range("A:A").Find(string)
    If result Is Nothing Then
        'some code here
    ElseIf IsEmpty(result.Offset(0, 2)) Then
        'some code here
    Else
        'some code here
    End If