Fix Word VBA Object Variable Not Set Error in Document Events
🔍 WiseChecker

Fix Word VBA Object Variable Not Set Error in Document Events

When you run VBA code in Word that responds to document events like Open, Close, or BeforeSave, you may see error 91: Object variable or With block variable not set. This error stops your macro and can be confusing because the code looks correct. The cause is almost always that an object reference, such as a Document, Range, or Application object, has not been assigned before the code tries to use it. This article explains the specific reasons this error occurs in event-driven VBA and provides clear steps to fix each scenario.

Key Takeaways: Fixing Error 91 in Word VBA Document Events

  • Set obj = Nothing before assigning a new object reference: Prevents the error when reusing a module-level variable across multiple event procedures.
  • Use the correct document object reference via Application.Documents(1) or ThisDocument: Ensures the object exists before any method or property is called on it.
  • Check for Nothing before using an object variable in an If statement: Avoids the error when the object might not have been created due to a conditional code path.

ADVERTISEMENT

Why Word VBA Throws Error 91 in Document Events

Error 91 occurs when your VBA code tries to use an object variable that has no assigned reference. In the context of document events, this typically happens because the object variable was declared but never set to a valid object. Common scenarios include:

  • Using a module-level variable that holds a reference to a Document object, but the document was closed before the event code runs.
  • Calling a method on a Range or Selection object that is no longer valid because the document content changed.
  • Writing code in the ThisDocument module that assumes the ActiveDocument is the same as the document where the event is firing.
  • Forgetting to use the Set keyword when assigning an object to a variable.

The root cause is that VBA cannot access a null object. When an event procedure runs, the document may not be fully initialized or may have been destroyed. Understanding these triggers helps you write defensive code that checks object validity before use.

How Document Events Trigger the Error

Word fires document events from the ThisDocument code module. For example, the Document_Open event runs when a document opens. If you declare a variable at the module level like Dim doc As Document and then try to use doc inside Document_Open without first assigning it, VBA throws error 91. Similarly, if you set doc = ActiveDocument but the active document is not the one that opened, the reference may be invalid.

Another common trigger is the Document_BeforeClose event. If your code tries to access the document’s content after the close has started, the document object may already be set to Nothing. This is why checking for Nothing is essential in every event procedure that uses object variables.

Steps to Fix the Object Variable Not Set Error

The following methods address the most common causes of error 91 in document events. Apply them in the order shown. If the error persists after one method, move to the next.

Method 1: Explicitly Set Object Variables Inside Each Event Procedure

  1. Open the VBA editor
    Press Alt+F11 in Word to open the Visual Basic for Applications editor. In the Project Explorer, double-click ThisDocument to open its code window.
  2. Locate the event procedure that triggers the error
    For example, if the error occurs when you open the document, find the Document_Open() procedure. If it does not exist, create it by selecting Document from the Object drop-down and Open from the Procedure drop-down.
  3. Declare and set the object variable inside the event procedure
    Instead of using a module-level variable, declare a local variable and assign it with Set. For example:
    Private Sub Document_Open()
    Dim doc As Document
    Set doc = ThisDocument
    MsgBox doc.Name
    End Sub

    Using ThisDocument ensures you reference the document that contains the code, not an arbitrary active document.
  4. Test the code
    Close and reopen the document to trigger the event. If the error disappears, the fix is complete. If not, proceed to Method 2.

Method 2: Check for Nothing Before Using an Object Variable

  1. Identify the line that throws error 91
    When the error occurs, click Debug in the error dialog. The VBA editor highlights the offending line. Note the object variable being used.
  2. Add a conditional check before the line
    Insert an If statement that verifies the object is not Nothing. For example, if the variable is rng, add:
    If Not rng Is Nothing Then
    rng.Text = "Hello"
    End If

    If the object might be Nothing, your code skips the operation instead of crashing.
  3. Apply the check to every object variable in the event procedure
    Review the entire procedure and wrap each object usage in a similar check. For module-level variables that persist across events, also check them at the start of each event.
  4. Test the document
    Trigger the event again. The error should not appear. If it still occurs, proceed to Method 3.

Method 3: Use Application.Documents Collection Instead of ActiveDocument

  1. Replace ActiveDocument references
    In your event procedure, change every occurrence of ActiveDocument to ThisDocument or to a specific document from the Application.Documents collection. For example:
    Set doc = Application.Documents(1)
    This is reliable when you know the document index.
  2. Loop through all open documents if needed
    If you must find a document by name, use a For Each loop:
    Dim doc As Document
    For Each doc In Application.Documents
    If doc.Name = "Report.docx" Then
    ' perform actions
    End If
    Next doc

    This avoids the error when the target document is not active.
  3. Test the fix
    Save the document, close it, and reopen it. The event should run without error.

ADVERTISEMENT

If Word VBA Still Throws Error 91 After the Main Fix

Error Occurs Only in Document_BeforeClose

The Document_BeforeClose event fires while the document is closing. At that point, some object references may already be invalid. To fix this, always use ThisDocument instead of a variable that might have been set earlier. Also, avoid referencing other open documents inside BeforeClose unless you first verify they exist.

Error Occurs When Running Code from a Template

If your event code is in a global template (Normal.dotm or an add-in), the ThisDocument object refers to the template, not the document. Use ActiveDocument when the code must act on the document that is currently open. However, check that ActiveDocument is not Nothing before using it. Add this line at the top of your event procedure:
If ActiveDocument Is Nothing Then Exit Sub

Error Occurs Intermittently in Long-Running Macros

When a macro runs for a long time, the user may close the document while the macro is still executing. This causes object references to become invalid. To prevent this, use error handling that traps error 91 and exits gracefully. Add this structure around your event code:
On Error Resume Next
Set doc = ThisDocument
If doc Is Nothing Then Exit Sub
On Error GoTo 0

VBA Error 91 Causes in Document Events vs Module-Level Code

Item Document Event Code Standard Module Code
Object reference source ThisDocument, ActiveDocument, or Application.Documents Any object created or passed as parameter
Common cause of error 91 Event fires before document is fully initialized or after it is destroyed Variable declared but never assigned with Set
Best practice to avoid error Always use ThisDocument inside the event procedure and check for Nothing Set the variable immediately after declaration and validate before use
Scope of variable Often module-level, causing stale references across events Usually local, reducing stale reference risk
Debugging difficulty Higher because events fire automatically and may not be repeatable Lower because you control when the code runs

By understanding these differences, you can write event code that is robust against object reference errors. The key is to always assign object variables inside the event procedure, never rely on a module-level variable that may have been cleared, and always check for Nothing before using any object.

ADVERTISEMENT