Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 835
wardzin Avatar asked Mar 29 '14 18:03

wardzin


People also ask

How do I fix object variable not set error 91?

Error: "Runtime Error 91" is a Visual BASIC error which means "Object variable not set". This indicates that the object was never created using the "Set" command before being used. Remedy: Be sure to use the SET statement to create the new oject.

What is block variable in VBA?

Roughly, it means that the VBA code used some variable without first initializing it properly.

How do I assign a value to a variable in Excel VBA?

Setting variables In VBA, declaring variables is optional, but you can't declare AND set the variable at the same time. We've added a line that assigns the value of a variable. In VBA, just append “. Value”, an equals sign, and the value you want to assign (in quotation marks).


1 Answers

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
like image 162
Matroid Avatar answered Sep 20 '22 12:09

Matroid