Run time 91 vba ошибка

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.

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's user avatar

David Zemens

53k11 gold badges81 silver badges130 bronze badges

asked Nov 21, 2016 at 16:23

Slab's user avatar

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:

  1. 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 no ActiveSheet.
  2. 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.
  3. You’ve shadowed the built-in ActiveSheet with Dim Activesheet As
    Worksheet
    and neglected to assign a worksheet object to that variable, so it’s Nothing by default.

Resolutions:

  1. Add logic to check for presence of Workbook object, etc.
  2. Declare a Worksheet object variable and assign to it.
  3. Prefer to avoid shadowing existing built-in names, ensure assignment to the object variable

answered Nov 21, 2016 at 16:40

David Zemens's user avatar

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

  • What do you call this old-time style of door knob/lock? How can I replace it?

  • Transitioning between scenes in a novel

  • Flutter Xcode 15 Error (Xcode): DT_TOOLCHAIN_DIR cannot be used to evaluate LIBRARY_SEARCH_PATHS

  • MPQ4470-AEC1 Layout guideline clarification

  • Why study finite topological spaces?

  • Is it true that common law courts will not resolve a question without a controversy?

  • The usage of «can not» vs. «cannot» in mathematics

  • How can I best set expectations for and run a campaign in a darker setting?

  • Deutschlandticket to Dutch border stations — how to pass the ticket gates?

  • How would mathematical demonstratives be used in a court?

  • How does the Way of Mercy monk’s ability Physician’s Touch work exactly?

  • Has there ever been an attempt to charge Israel, or its officials, with a war crime for changing the demography of the occupied Palestinian West Bank?

  • What is an ideal layout for a normally-open solder jumper?

  • Do subducted continents rise up again through ridges?

  • Filter a list of strings to create a separate list of those that match a given prefix

  • What is a good way to phrase «in my experience» in a journal paper?

  • Significance of trail of pebbles vs breadcrumbs?

  • Is this revision of the level 2 Transmutation Wizard feature balanced?

  • Book about a giant spaceship that passes through the solar system

  • Add grid points to a torus

  • How can I find out what % of the health insurance premium my employer pays?

  • Will a Humans Tolerance Keep Going Until Full Immunity?

  • Is there a possibility when calling .ToUpper() that the new string requires more memory?

  • Banking System console app in C++

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.

Overview

VBA run-time error 91 is a common trappable error seen in VBA development. This error is triggered when you try to use an object variable (i.e. a variable which is of the “Object” type) that has no object (properly) assigned to it.

This error is a very common technical error which can often be encountered by beginners and even experienced programmers. Therefore, it is useful that you understand it, learn about how it is triggered, and how to work around it. This knowledge will help you in your development as a programmer in Microsoft Office.

run-time error 91 object variable or with block variable not set

Key Concept Before We Start — Value Assignment to Variables in VBA

Before we look into the topic of Error 91, let’s go through a very important coding concept in VBA about value assignment to variables. There are two main types of value assignment, which you can think of as (1) “object” and (2) “non-object”. You can see in the table below that for all variables which are non-objects, we simply use “=” to assign values to them. However, for object variables, we must always begin the assignment with “Set“.

Variable Type Scope VBA syntax / treatment
Normal (Non-Objects) Any variable type that is not an object, e.g. integer, long, string, variate, etc. Syntax: Set MyVariable = YourValue  
Example: Dim x As Integer x = 123
Objects All variables which are objects. e.g. range, application, collection, etc. Syntax: Set MyObject = YourObject
' Assign object reference  
Set MyObject = Nothing
' Discontinue association  

Example 1:
Dim x as Range Set x = ThisWorkbook.Worksheets(1)  
Example 2:
Dim dict As Scripting.Dictionary Set dict = New Scripting.Dictionary

You can now see why Error 91 is called “Object variable not Set”.  It is because you should assign an object to an object variable with the SET statement.

So How is Error 91 Triggered?

There are four main reasons you might encounter this error:

  1. “Set” is omitted in the assignment of an object variable
  2. Using GoTo to jump into a “With” block
  3. Attempting to use an object variable that has been set to Nothing.
  4. Attempting to use an object which is not yet being created

Scenario 1: “Set” is Omitted in the Reference to an Object Variable

The macro “example1” below shows the most straightforward scenario when Error 91 can be triggered. The variable “MyObject” is an object variable. In line 4, “MyObject = ActiveSheet” attempts to assign a worksheet object (the ActiveSheet) to MyObject. Because the SET statement was omitted, this line of code causes Error 91 during run time.

Sub example1()
Dim MyObject As Object   'Create object variable
Dim x As String
MyObject = ActiveSheet   'Create object reference [Err 91 here]
x = MyObject.Name        'Assign Count value to x
MsgBox "Sheet name is: " &amp;amp;amp;amp; x
End Sub

Solution:

To avoid making this mistake, you must always remember to use a Set statement to assign an object to an object variable.

See the correct way of object variable assignment with a Set statement in line 4 below:

Sub example1_fixed()
Dim MyObject As Object    	'Create object variable
Dim x  As String
Set MyObject = ActiveSheet	'Create object reference the correct way
x = MyObject.Name        	'Assign Count value to x
MsgBox "Sheet name is: " &amp;amp;amp;amp; x
End Sub

Scenario 2: Using GoTo to Jump into a “With” Block

If a GoTo statement jumps into a With block, it may cause Error 91. See the example below:

Sub BadJumper()
    Dim x As Integer    'counter for use with for loop
    Dim result As String
    x = WorksheetFunction.RandBetween(1, 10) 'Draw integer between 1&amp;amp;amp;amp;10
    If x &amp;amp;amp;gt; 5 Then
        GoTo jumper1   'Jump if x &amp;amp;amp;gt;5
    Else
        End			'Terminate macro if x&amp;amp;amp;lt;=5
    End If
    With Range("A1")
jumper1:
        .Value = x 	'place rolling total [Err 91 here]
    End With
End Sub

In line 6, the GoTo statement jumps to “jumper1” when x>5. The With statement in line 10 is bypassed and the process jumps straight to line 12 which is supposed to put the value of x into cell A1. Error 91 will be trigger right there.

Having the With statement (line 10) bypassed, Excel has no idea what object the “Value” property (line 12) refers to, and therefore has no idea where to place the value of x.

Solution:

To avoid this mistake, make sure your GoTo statements never jump directly inside a WITH block.

Scenario 3: Attempting to Use an Object Variable that Has Been Set to Nothing.

Error 91 can also be triggered when the code attempts to use an object variable that has been set to “Nothing”. (i.e. the object variable has been reset/erased.)

In line 5 of the macro below, the object variable “MyObject” has been reset by the statement “Set MyObject = Nothing“. Error 91 will happen in line 6 (when the code tries to display the name of MyObject in a Msgbox). This is equivalent to having an blank object variable which has nothing assigned to it.

Sub example3()
Dim MyObject As Object      'Create object variable.
Set MyObject = ActiveSheet  'Create valid object reference.
MsgBox "Sheet name is: " &amp;amp;amp;amp; MyObject.Name
Set MyObject = Nothing
MsgBox "Sheet name is: " &amp;amp;amp;amp; MyObject.Name	'[Err 91 here]
End Sub

Solution:

After resetting an object variable by setting it to nothing, make sure you re-assign an object to it (with a Set statement) before calling it.

Scenario 4: Attempting to Use an Object which Is Not Yet Created During Run-Time

The previous examples showed Error 91 scenarios in which objects have not been properly assigned to object variables. There are situations where Error 91 is triggered because the object has not been created.

This scenario normally applies to objects which are not under any of the Microsoft Office Application objects. For instance, (1) generic Visual Basic objects (such as Collection, Dictionary) or (2) Objects in libraries added through “Add Reference”.

Example (part 1):

The two macros below “ex4_Collection” and “ex4_Dictionary” contain very typical mistakes made by VBA programmers when using Collections and Dictionaries. In line 2 of both macros, the objects were declared, and then values are being added to the Collection/Dictionary in line 3, where Error 91 occurred.

Sub ex4_Collection()
Dim MyCollection1 As Collection
MyCollection1.Add Item:=123		'[Err 91 here]
End Sub 
Sub ex4_Dictionary()
Dim dict As Scripting.Dictionary
dict.Add "key1", 123		'[Err 91 here]
End Sub

Solution:

To fix the macro, you need to learn the syntax to create a new instance of the object.  See below how the two macros are fixed by inserted a new Set statement in line 3 of both macros.

Sub ex4_Collection_fixed ()
Dim MyCollection1 As Collection
Set MyCollection1 = New Collection   'create the Collection
MyCollection1.Add Item:=123
End Sub
Sub ex4_Dictionary_fixed()
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary	'create the Dictionary
dict.Add "key1", 123
End Sub

Example (part 2):

Here is another very common case when a reference to a library is added. For example, the Office library is added through “Add Reference” from the Tools menu in VB Editor:

add office object library via references

The macro below tries to create a Mail item. But Error 91 will be triggered in line 3. The macro seems perfectly fine, where the Outlook application object and the MailItem object have been declared, and then a Set statement is used to create a Mail item. But why there is still the Error 91?

Sub ex4_Outlook()
  Dim OutlookApp As Outlook.Application
  Dim OutlookMail As Outlook.MailItem
  Set OutlookMail = OutlookApp.CreateItem(olMailItem)
End Sub

The macro below shows the correct approach to create such an (early binding) instance of the Outlook application object. See how line 3 has been added?

Sub ex4_Outlook_fixed()
  Dim OutlookApp As Outlook.Application
  Dim OutlookMail As Outlook.MailItem

  Set OutlookApp = New Outlook.Application  'create Outlook App
  Set OutlookMail = OutlookApp.CreateItem(olMailItem)
End Sub

The skills to interact with object variables is crucial in VBA development and successful declaration and assignment are the first steps. Understanding the above scenarios can for sure help you program more efficiently in VBA.

Today we are with our another error solving article, & here we are going to show you & solve your VBA Runtime Error 91 Windows PC code problem from your Windows PC permanently. So, for that, all you have to do is just read and check out this below post once entirely fast so that you can surely grab some neat, natural solutions and the methods for getting rid out of this type of Error 91 Excel VBA problem.

This shows an error code message like,

Runtime Error 91

Object variable or With the block variable not set

This Error 91 object variable or with block variable set suddenly occurs when you are starting any program. This error is a significant error code problem on many of the users PC. This error is a common error problem on the Windows-based systems that usually appear randomly. This Error Code 91 may encounter with the Microsoft products. Old or corrupted registry keys may also cause this error. This error problem includes PC freezes, crashes & the possible virus infection. This issue even the result of coding errors in the app. This VBA Runtime Error 91 Windows problem appears to be due to the insufficient access rights on the PC.

Causes of VBA Runtime Error 91 Windows Code Issue:

  • When opening Excel
  • Runtime error

So, here are some quick tips and tricks for efficiently fixing and resolve this type of Error 91 Windows PC Code problem from you permanently.

How to Fix & Solve VBA Runtime Error 91 Windows Code Problem

1. Change DCOMCnfg.exe Settings –

Ensure that DCOMCnfg.exe file is set to allow “Everyone” to use it so that you can quickly fix and solve this VBA Runtime Error 91 Windows code problem from your PC.

2. By using this below Command on the RUN –

By using this below Command in the RUN

  • Go to the start menu
  • Search for RUN & open it
  • Type this below the following command in the Run window
    Regsvr32 c:\windows\system32\scrrun.dll
  • Now, then click OK there
  • After completing, just close the tab
  • That’s it, done

By using this above command in the RUN can get back you from this VBA Runtime Error 91 Windows code problem.

3. Perform a full Windows PC Scan for Viruses or Malware –

Perform a full PC scan for viruses

  • Go to the Start Menu
  • Search for ‘Microsoft Security Essentials‘ & open it
  • Click on the “Scan Now” option
  • Before clicking on the ‘Scan Now‘ button,
  • Check that ‘Full‘ Scan option is selected already while scanning
  • That’s it, Done

It will perform a full PC scan for the viruses on your computer to fix this Runtime Error 91 excel vba problems.

4. Use a Registry Cleaner to Clean all the Registry of your Windows PC –

Clean or Restore the Registry

Clean your registry by any registry cleaner software so that it can fix and solve this VBA excel Runtime Error 91 Windows problem from your PC completely.

5. Disable the Script Debugging on the Internet Explorer –

Disable the Script Debugging on the Internet Explorer

  • Go to your Internet Explorer
  • Now, go to the Tools option there
  • Click on ‘Internet Options’ there
  • Now, click on the Advanced tab there
  • Now, scroll down to the Browsing
  • &, click on Disable Script Debugging to disable it
  • After completing, close the tab
  • That’s it, done

By disabling the script debugging on the Internet Explorer browser can fix and solve this Error 91 Excel VBA code problem from your PC.

These are the quick and the best way methods to get quickly rid out of this VBA Runtime Error 91 Windows PC Code problem from you entirely. Hope these solutions will surely help you to get back from this Error 91 object variable not set issue.

If you are facing or falling in this VBA Runtime Error 91 Windows PC Code problem or any error problem, then comment down the error problem below so that we can fix and solve it too by our top best quick methods guides.

Return to VBA Code Examples

This article will explain the VBA object variable or with block variable not set error.

vba error 91

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.

vba error object variable

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:

vba error with block

When we click on debug, the code stops within the WITH….END WITH block – hence the with block variable error.

vba error with block debug

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

Понравилась статья? Поделить с друзьями:
  • Run graphics test ошибка команды нет
  • Rundll ошибка при запуске windows
  • Run dll возникла ошибка при запуске
  • Runas ошибка 193
  • Run dll устранение ошибки windows 10