BruceWayne
BruceWayne

Reputation: 23283

Count (and activate) opened Word Documents

This is odd - I swear I was just using this code successfully, but not it's not working:

Sub t()
Dim wdApp As Object
Set wdApp = GetObject(, "Word.Application")
Debug.Print wdApp.Documents.Count
End Sub

From Excel, it should simply realize there is a Word document open, and return 1. However, I'm getting 0 for some reason. I've also tried Set wdApp = CreateObject("Word.Application").

What might I be overlooking? There are no errors thrown, it's just not showing I have a document open.

(Note: I got the idea from this thread, as I want to copy an Excel range and paste into a Word doc.)

Upvotes: 0

Views: 1662

Answers (3)

Fahad Al-Dossary
Fahad Al-Dossary

Reputation: 51

        Sub t()
        Dim wdApp As Object
        Dim Docs
        On Error Resume Next
        Set wdApp = GetObject(, "Word.Application")
        On Error GoTo 0
        
        If Err.Number <> 424 Then
        On Error Resume Next
        
        Set Docs = wdApp.Documents
        On Error GoTo 0
        MsgBox "No Doc is open"
        Else
        MsgBox Docs.Count
        End If
        
        End Sub

Upvotes: 0

Parfait
Parfait

Reputation: 107567

Also as best practices, always free resources within error handling so such processes are always closed if macros succeeds or fails.

Sub t()
On Error Goto ErrHandle
    Dim wdApp As Object
    Set wdApp = GetObject(, "Word.Application")

    Debug.Print wdApp.Documents.Count

    Set wdApp = Nothing
    Exit Sub

ErrHandle:
    Set wdApp = Nothing
    Exit Sub
End Sub

And if running COM interfaces from other languages such as Python, PHP, R, etc. use try/catch procedures to always clear such objects regardless of fail or success. Below is the counterpart of macro in Python:

import win32com.client

try:
    wdApp = win32com.client.Dispatch("Word.Application")

    print(wdApp.Documents.Count)

except Exception as e:
    print(e)

finally:    
    wdApp = None

Upvotes: 2

Comintern
Comintern

Reputation: 22185

GetObject can only return one Word.Application object. If you have multiple instances running, the count of open documents might be off (because you're only counting from one instance). Unfortunately it isn't clear from the documentation which application you get in this instance, but I'd guess you're getting 0 from wdApp.Documents.Count because you're attaching to a zombie Word process.

Upvotes: 5

Related Questions