Asked
Viewed
5k times
Why is this not working? Run time error 91?
Dim fornameCurr As String
Dim surnameCurr As String
Dim rowCurr As Long
rowCurr = 13
fornameCurr = Activesheet.Cells(rowCurr, 1) << ERROR HERE
surnameCurr = Activesheet.Cells(rowCurr, 2)
- vba
- excel
David Zemens
53k11 gold badges81 silver badges130 bronze badges
asked Nov 21, 2016 at 16:23
SlabSlab
3533 silver badges14 bronze badges
11
-
How is this code being called? From Excel or from another application? Is it from an Add-in? (If it’s from Excel, not from an Add-in, then this code should work)
Nov 21, 2016 at 16:30
-
I am getting no issues with the code you have given.
Nov 21, 2016 at 16:32
-
What is the value in A13? Is it an error?
Nov 21, 2016 at 16:36
-
@Vityata that would raise a 13 Type Mismatch error, though, not a 91 Object error.
Nov 21, 2016 at 16:36
-
«Curr» rings the «Currency» bell in my external reader’s head. Avoid useless abbreviations and use meaningful names. What’s wrong with
currentRow
?Nov 21, 2016 at 16:44
1 Answer
Runtime error 91 suggests that ActiveSheet Is Nothing
(because ActiveSheet
is the only presumed Object in the few lines of code you’ve provided, and certainly the only Object on the line raising the error).
Several scenarios I can think of might contribute to this:
- The code is being called from an Add-In, in Excel or another application, and no Excel workbooks are open. In this case, there is no
ActiveWorkbook
and also noActiveSheet
. - The code is being executed from another application (Outlook,
Access, Word, PowerPoint, etc.), but you’re using the Excel built-in
ActiveSheet
which doesn’t exist in the other applications. - You’ve shadowed the built-in
ActiveSheet
withDim Activesheet As
and neglected to assign a worksheet object to that variable, so it’s
WorksheetNothing
by default.
Resolutions:
- Add logic to check for presence of Workbook object, etc.
- Declare a
Worksheet
object variable and assign to it. - Prefer to avoid shadowing existing built-in names, ensure assignment to the object variable
answered Nov 21, 2016 at 16:40
David ZemensDavid Zemens
53k11 gold badges81 silver badges130 bronze badges
6
-
My guess is #2 — but we really shouldn’t have to guess. OP needs to provide more details.
Nov 21, 2016 at 16:42
-
It seems like he is trying to pass a location reference to a string, which makes me think thats the issue. fornameCurr = Activesheet.Cells(rowCurr, 1) <> Dim fornameCurr As String. Weird that he didnt get a data type mismatch error?
Nov 21, 2016 at 17:02
-
@DougCoats I don’t follow what you’re saying…
ActiveSheet.Cells(rowCurr, 1)
returns the.Value
from that cell, which is convertible to String data type unless it’s an Error (which would raise the Mismatch, instead).Nov 21, 2016 at 17:11
-
@DavidZemens, I go with option 3… note how OP’s code does not have ‘sheet’ capitalized, thus possibly he declared his own.
Nov 21, 2016 at 17:51
-
@WayneG.Dunn yes I noticed that. Could be a typo but it did make me think of that possible error in shadowing the built-in
ActiveSheet
.Nov 21, 2016 at 18:07
- The Overflow Blog
- Featured on Meta
Related
Hot Network Questions
-
Filter a list of strings to create a separate list of those that match a given prefix
-
Isn’t it convenient to pronounce «-man» in «salesman» and «-men» in «salesmen» differently as you do it in «man [mæn]» and «men [men]»?
-
Is my replacement light switch wiring correct?
-
Adding a Primary Key to a Large PostgreSQL Table with High Traffic
-
Career change: Entering Academia realistic at 36?
-
Comprised of both
-
Will a Humans Tolerance Keep Going Until Full Immunity?
-
How can we measure the amount of Dark Matter in the universe to an integer?
-
Is Computer Modern 12 pt an exact scaled version of 10 pt? If not, how to scale?
-
Transcript of discussion between Elon Musk and Israeli PM Benyamin Netanyahu on 18 Sep 2023?
-
Conjecture about partitions of the powerset without the empty set
-
Code review from domain non expert
-
Manager wants to hire an additional resource with experience in a skill that I do not have
-
How can I renew a Belarusian passport abroad?
-
Are there rules that treat Ceremorphosis as an illness or curable/resistable infliction?
-
What can be found on the «terminal» on the Jurassic World promotional website?
-
Can someone help me understand why the MAE, MSE and RMSE scores for my regression model are very low but the R2 is negative?
-
How does the Way of Mercy monk’s ability Physician’s Touch work exactly?
-
Does a slippery liquid leak through pipe fittings?
-
Find the largest sum such that no two elements are touching
-
Can aunt and her nephew’s dna trace line to see if aunt’s mother (nephew’s grandmother) is her biological mother?
-
Why would astronauts need a wristwatch and a separate timer?
-
How can different models of set theory be constructed from the same set of axioms?
-
Double sharp: how to analyse a chord in Moonlight Sonata 3rd movement?
more hot questions
Question feed
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
In VB object variables require the Set
keyword to be assigned. Object properties that are objects also need to be Set
. Runtime error 91 «object variable not set» is raised when the assignment doesn’t use that keyword.
This is inherited from legacy Let
keyword to assign values, and Set
keyword to assign references; the Let
eventually was deprecated (although still needed for defining properties) and the Set
remained, leaving the VB6/VBA value assignment syntax like [Let] variable = value
, where «Let» is optional.
In the declaration and assignment:
Dim SourceWindow As Window, QACheckWindow As Window
'this is like saying "Let SourceWindow = ActiveWindow":
SourceWindow = ActiveWindow
SourceWindow
is an object, assigned as if it were a value — this causes VBA to attempt let-coercion through a default member call. If the object wasn’t initialized, the member call fails with error 91. If the object was initialized but doesn’t have a default member, error 438 is raised.
So in this case error 91 is being raised because of an implicit member call; the .net equivalent would be a NullReferenceException
:
Dim SourceWindow As Window, Dim WindowTitle As String
'"SourceWindow" reference isn't set, the object can't be accessed yet:
WindowTitle = SourceWindow.Caption
I’m going to go a bit overboard here, but the legacy Let
statement should not be confused with the Let
clause (in VB.net) which, in the LINQ query syntax (in VB.net), computes a value and assigns it to a new, query-scoped variable (example taken from MSDN):
From p In products
Let Discount = p.UnitPrice*0.1 '"Discount" is only available within the query!
Where Discount >= 50
Select p.ProductName, p.UnitPrice, Discount
VB.net assigns both values and references, without the need to specify a Let
or a Set
, because in .net this distinction is a much thinner line, given how everything ultimately derives from System.Object
… including System.ValueType
. That’s why the Set
keyword was also deprecated in VB.net, and also why the VB.net syntax for defining properties has dropped the Let
in favor of Set
— because parameterless default members are illegal in VB.NET, so this ambiguous let-coercion doesn’t happen.
Return to VBA Code Examples
This article will explain the VBA object variable or with block variable not set error.
This relatively common error occurs for exactly the reason that the message box says – the object variable or with block variable has not been set yet!
Object Variable Not Set
Let us consider the following code:
Sub TestObject()
Dim wks as Worksheet
wks.Name = "Sheet1"
End Sub
We have declared a new object variable called “wks” as a Worksheet.
We are then attempting to name this sheet – Sheet1
However, when we run the code, we get the run-time error. When we click on the Debug button, the code stops at the line where we are trying to name the sheet.
We are trying to populate the variable “wks” – but we haven’t actually allocated the variable to a specific sheet – we have only declared it as a variable. Therefore, although the variable is declared, the object doesn’t actually exist!
Let us consider the amended code below:
Sub TestObject()
Dim wks as Worksheet
Set wks = ActiveSheet
wks.Name = "Sheet1"
End Sub
We have now created the object with this line of code:
Set wks = ActiveSheet
The code will then run without error.
With Block Variable Not Set
Let us now consider this code:
Sub TestWith()
Dim wks As Worksheet
With wks
.Name = "Sheet1"
.Activate
End With
End Sub
When we run this code, we get the same error:
When we click on debug, the code stops within the WITH….END WITH block – hence the with block variable error.
The error is actually the same and once again, by creating the object, we will solve the error.
Sub TestWith()
Dim wks As Worksheet
Set wks = ActiveSheet
With wks
.Name = "Sheet1"
.Activate
End With
End Sub
Example
Incorrect code
Sub DoSomething()
Dim foo As Collection
With foo
.Add "ABC"
.Add "XYZ"
End With
End Sub
Why doesn’t this work?
Object variables hold a reference, and references need to be set using the Set
keyword. This error occurs whenever a member call is made on an object whose reference is Nothing
. In this case foo
is a Collection
reference, but it’s not initialized, so the reference contains Nothing
— and we can’t call .Add
on Nothing
.
Correct code
Sub DoSomething()
Dim foo As Collection
Set foo = New Collection
With foo
.Add "ABC"
.Add "XYZ"
End With
End Sub
Why does this work?
By assigning the object variable a valid reference using the Set
keyword, the .Add
calls succeed.
Other notes
Often, a function or property can return an object reference — a common example is Excel’s Range.Find
method, which returns a Range
object:
Dim resultRow As Long
resultRow = SomeSheet.Cells.Find("Something").Row
However the function can very well return Nothing
(if the search term isn’t found), so it’s likely that the chained .Row
member call fails.
Before calling object members, verify that the reference is set with a If Not xxxx Is Nothing
condition:
Dim result As Range
Set result = SomeSheet.Cells.Find("Something")
Dim resultRow As Long
If Not result Is Nothing Then resultRow = result.Row
The object variable or with block variable not set error can occur if a variable is referenced before it has been assigned a value. There could be different causes according to your case.
All the causes and their solutions have been included in this article to provide a complete understanding of this error and what it takes to get it resolved. Keep reading to discover efficient ways to get rid of this error.
Contents
- What Causes the Object Variable or With Block Variable Not Set?
- – Improper Assignment of Object
- – Object Not Initialized or Set To Nothing
- – Object Reference Not Set to an Instance of an Object
- – Invalid Address Variable
- – Due To Other Exceptions
- – No Error Found
- How To Solve Object Variable or With Block Variable Not Set?
- – Check and Properly Set Object Reference
- – Initialize Object Before Use
- – Ensure That the Object Has Been Instantiated Before Use
- – Use Correct Address Variable
- – Catch Other Exception
- – No Solution Required
- FAQs
- 1. Where Object Variable or With Block Variable Not Set Occurs?
- 2. What Is Object Variable or With Block Variable Not Set’’ (Windows 10)?
- 3. What Is Run Time Error 91’: Object Variable or With Block Not Set?
- Conclusion
The object variable or with block variable not set can be caused by the improper assignment of objects, accessing an object that has not been correctly created, the object reference not set to an instance, an invalid address variable, or another exception in the code.
However, there are multiple variations of the “object variable or with block variable not set” error message depending on where it appears and in which context. A few variations of the error message are listed below.
- object variable or with block variable not set vba
- object variable or with block variable not set range
- object variable or with block variable not set word
- object variable or with block variable not set SQL
- object variable or with block variable not set vb6
– Improper Assignment of Object
You can face this error because of improper assignment of objects. This error occurs when accessing a variable or object that has not been assigned a value or reference. In other words, the object variable points to “Nothing” rather than an actual object instance.
There could be several reasons behind this cause of error, including incorrect use of variables, mistyping of variable names, or the absence of appropriate error handling in the code.
– Object Not Initialized or Set To Nothing
This error can also arise if you try to access an object that has not been correctly created. It may happen due to the absence of proper instantiation of the object in your code or because you forget to create an instance of the object.
When an object is not properly created, it is set to “Nothing,” and trying to access it leads to this error.
– Object Reference Not Set to an Instance of an Object
This error message can appear if the object reference is not set to an instance of an object. Essentially, the object variable points to a non-existing object, which can happen from not correctly assigning the object reference in your code, reassigning the reference to another object, or the object being destroyed prematurely.
When you try to use this unreferenced object, the error message “Object variable or with block variable not set” is displayed.
– Invalid Address Variable
The error can occur In the context of the Address variable. If the Address variable is not set correctly, it may result in the WebResponse being null.
A null object reference means that the object has not been assigned a value or set to Nothing, which can cause problems when you try to access the object’s properties or methods. When the WebResponse is null, attempting to access it will result in an error.
– Due To Other Exceptions
The “Object variable or with block variable not set” error can arise due to another exception in your code that was not adequately handled. This exception can result in an object being set to Nothing, causing the error when that object is accessed.
– No Error Found
When there is no issue in the code, the error message “A first chance exception of type ‘System.NullReferenceException’ occurred in Microsoft.VisualBasic.dll” may pop up. This is normal behavior and occurs when the .NET framework encounters a potential exception, but the code is designed to handle it while the exception is never thrown.
You don’t have to take any action because the Object variable or with block variable not set issue won’t happen in these situations.
How To Solve Object Variable or With Block Variable Not Set?
You can solve the object reference is not set to an instance by checking the code and adequately setting object reference, creating an instance of the object before attempting to access it, preserving the reference, adding the “http://” prefix, or including a catch block for Exception type.
– Check and Properly Set Object Reference
If an object was incorrectly assigned, you might fix the mistake by checking your code and ensuring the object variable points to an instance of an object. To accomplish this, confirm that the object was appropriately created and the reference was allocated.
The object reference could be unassigned if there are typos in the variable name or source code. For the object reference to be set correctly, you must find and address these problems.
– Initialize Object Before Use
If the error arises from an uninitialized object, you can solve it by creating an instance of the object before attempting to access it.
This can be done through the appropriate constructor or object creation method. Initializing the object will ensure the object reference is appropriately assigned to an object’s instance.
– Ensure That the Object Has Been Instantiated Before Use
If the error occurs from the object reference being destroyed or deallocated prematurely, you can fix it by preserving the reference. Ensure that the object reference is not set to Nothing and that the object is not destroyed before you try to access it.
You may also need to check that any code accessing the object is not causing it to be destroyed or deallocated.
To check if an object variable is set before using it in VBA to avoid the “object variable or with block variable not set” error, you can use the following code:
‘ Your code here
Else
‘ Handle the error
End If
If Not objVariable Is Nothing Then
‘ Your code here
Else
‘ Handle the error
End If
This code checks if the object variable objVariable has been assigned an object reference. Suppose it has, then the code inside the If the statement is executed. If not, then the code inside the Else statement is executed, which can be used to handle the error.
– Use Correct Address Variable
If you face this problem because of an invalid address variable, you can fix it by adding the “http://” prefix in front of the Address variable. This should make the Address variable a valid URL, resolving the error.
– Catch Other Exception
To rectify the mistake, you can include a catch block for the Exception type after the WebException catches block. This will display an exception message box, providing more significant insights into the issue and facilitating the identification and resolution of the underlying cause of the error.
– No Solution Required
If the source of the error is a first-chance exception, the most effective resolution is to disregard it, as it is a common occurrence and does not signify any defect in the code. Ignoring the error will not affect the operation of your program.
FAQs
1. Where Object Variable or With Block Variable Not Set Occurs?
The object variable or with block variable not set can occur in Microsoft Visual Basic for Applications programming language, which is used in Microsoft Office applications such as Excel, Word, and Access. It can also happen in languages like Visual Basic 6 (VB6) and SQL.
2. What Is Object Variable or With Block Variable Not Set’’ (Windows 10)?
The object variable or with block variable not set is a run-time error in Windows 10 that arises when an object variable is used without being correctly assigned to an object. Several programming languages, including Visual Basic for Applications and Visual Basic 6, are susceptible to this problem.
3. What Is Run Time Error 91’: Object Variable or With Block Not Set?
Run time error 91: object variable or with block variable not set is a specific error message indicating that an object variable is being used without being correctly assigned to an object. This occurs while using an unassigned object variable or set to an object.
Conclusion
In this comprehensive guide, we covered all of the causes behind the object variable or with block variable not set error and how to fix it without triggering any other exceptions in the program. Let’s conclude this article.
- The “Object variable or with block variable not set” error can be caused by improper assignment or accessing an object that has not been correctly created.
- Object reference not set to an instance, invalid address variables, and other exceptions in the code are also some major causes.
- The error can be fixed by checking and adequately setting the object reference and initializing the object before use.
- Solutions include preserving the object reference, using the correct address variable, and catching other exceptions.
- If the error is a first-chance exception, the best solution is to ignore it, as it is normal behavior and does not indicate any problem with the code.
We learned every possible way to remove this error. But if you still need clarification about this error, you can reread the article for a better understanding.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team