Get the name of open Word document in Excel - excel

I have one .xlsm workbook and one .docx document open.
The code is Excel VBA.
I want to display the name of the Word file in MsgBox.
How do I reference the Word document in Excel VBA?
I found code here https://excel-macro.tutorialhorizon.com/vba-excel-get-the-instance-of-already-opened-word-document/
After I've rewritten it, it is giving me this error:
activex component can't create object 429.
Sub Get_Opened_Doc_Instance()
'Variables declaration
'Dim WordApp As Object
Dim WordApp As Word.Application
'Dim WordDoc As Object
Dim WordDoc As Word.Document
'Dim Text As String
'this variable is here because later I'm going to search this file.
Set WordApp = GetObject(, Word.Application)
'Set WordDoc = GetObject(, Word.Document)
WordApp.Visible = True 'this line or the next one returns the error
'activex component can't create object 429
MsgBox WordApp.ActiveDocument.Name
End Sub
My Excel VBA editor tools->references screenshot.

GetObject and CreateObject both accept a String parameter representing a ProgID - that's a literal string value present in the Windows Registry, associating a class with a specific type library.
Hence, you want that argument to be enclosed in double quotes, which delimit a string literal:
Set WordApp = GetObject(, "Word.Application")
The reason you're getting an error is because there's an implicit default member call in Word.Application that's returning the value of Word.Application.Name, i.e. the string value "Microsoft Word", and "Microsoft Word" is not a valid, registered ProgID.
Having the reference to the Word object model in your project means you can do this:
Dim WordApp As Word.Application
Set WordApp = GetObject(, "Word.Application")
And then every member call made against this WordApp object variable will be compile-time validated (that's what early-bound means). It also means you can do this:
Dim WordApp As Word.Application
Set WordApp = New Word.Application
Instead of this:
Dim WordApp As Word.Application
Set WordApp = CreateObject("Word.Application")
With the reference to the Word object library, all wdXxxxx constants are defined and usable. The counterpart of that, is that your users must have the exact same version of the referenced library on their machines.
If your users are on different versions of Word / Office than you, consider late binding instead.
You'll lose the ability to use wdXxxxx constants directly (you'll need to use their underlying values, or define them as Const identifiers or Enum members yourself). You'll also lose compile-time validation, intellisense/autocompletion, the ability to New up any class from the Word library, and Option Explicit will not be able to protect you from a typo in any of the late-bound member calls you make (expect run-time error 438 if you do something wrong), but you'll also shed the dependency on a specific version of Word/Office.
To use late binding, you need to declare things As Object, like this:
Dim WordApp As Object
Set WordApp = GetObject(, "Word.Application")
Note that this cannot work, even with the double quotes:
'Set WordDoc = GetObject(, "Word.Document")
Because you can't create a Word.Document - only Word can do that, for the same reason you can't create an Excel.Worksheet, only Excel can do that. To create a Word.Document, you need to invoke a member of WordApp that will create a new document (and return a reference to it that you can capture in a local variable):
Dim WordDoc As Object 'early-bound: As Word.Document
'Set WordDoc = WordApp.ActiveDocument
Set WordDoc = WordApp.Documents.Add
MsgBox WordDoc.Name

You don't need the first two lines in your above macro - you can obtain what you're looking for with just these 3 lines:
Set objWord = GetObject(, "Word.Application")
objWord.Visible = True
MsgBox objWord.ActiveDocument.Name

Related

Setting range in Word with VBA in Excel

How do I set a range in Word while opening that file with VBA in Excel?
Dim wordApp As Word.Application
Dim wordObject As Word.Document
Dim wordRange As Word.Range
Dim filePath As String
Dim fileName As String
filePath = "C:\Users\"
fileName = "somename.docx"
Set wordApp = CreateObject("Word.Application")
With wordApp
.Visible = True
.Activate
.WindowState = wdWindowStateNormal
End With
Set wordObject = wordApp.Documents.Open(filePath & fileName)
Set wordRange = Documents(fileName).Sections(1).Range
With wordRange
'code
End With
The line causing trouble:
Set wordRange = Documents(fileName).Sections(1).Range
Regardless of the string I put in this returns
4160 runtime error "Bad File Name"
If I use ActiveDocument instead of Documents(), I get
4248 runtime error: "This command is not available because no document is open".
The error persists even after opening multiple unsaved and saved Word docs whilst running the code, only to have the same error message show up.
Set wordRange = Documents(fileName).Sections(1).Range errors because Excel doesn't know what Documents is (or it resolves it to something other than Word.Documents)
To fix that, you'd use (just as you did in the previous line)
Set wordRange = wordApp.Documents(fileName).Sections(1).Range
That said, you've already Set the Document(filepath & filename) to wordObject, so use it:
Set wordRange = wordObject.Sections(1).Range
Also, Excel doesn't know wdWindowStateNormal, so a new Variant variable is created (unless you have Option Explicit, which you should, always) and assigned the default value 0. Which just happens to be the value of Word.wdWindowStateNormal so no harm done, but the code is misleading.
To fix, use
.WindowState = 0 'wdWindowStateNormal
I'm curious about the way you've created the object. Using early binding but instead of creating New Word.Application you use CreateObject
Was this an intentional decision?
What is the benefit?

Can't get reference to the existing instance of Word object from excel; runtime error 429

I have a script in excel which opens a certain MS Word file. Both Word and Excel object libraries are included. Here is the code of initializing an instance of Word:
Sub InitializeWord()
'Path for the upper-level folder
Dim RootPath As String
'Path for the destination of my document
Dim WordDocPath As String
RootPath = Left(ActiveWorkbook.Path, InStrRev(ActiveWorkbook.Path, "\"))
WordDocPath = RootPath & "Templates\" & "ÎÌÄ.docm"
'Try to get a reference to existing Word instance
On Error Resume Next
Set WordApp = GetObject(, Word.Application)
'If WordApp still references nothing - create a new instance of WordApp and open the document.
If WordApp Is Nothing Then
Set WordApp = CreateObject("Word.Application")
'word will be closed while running
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open(WordDocPath)
'Else search open documents for the file you need and reference it, if there's none - open it.
Else
Dim OpenedDoc As Object
For Each OpenedDoc In Word.Documents
If StrComp(OpenedDoc.FullName, WordDocPath, vbTextCompare) = 0 Then
Set WordDoc = OpenedDoc
Exit For
End If
Next OpenedDoc
If WordDoc Is Nothing Then
Set WordDoc = Word.Documents.Open(WordDocPath)
End If
End If
Set Headers = WordDoc.SelectContentControlsByTitle("DocHeader")(1)
WordApp.Visible = True
End Sub
The script correctly creates the instance of word when there is none, but when there is word app already opened during the runtime, the script fails to get the Word.Application Object and tries to open the document the second time. Disabling On Error Resume Next string gets Runtime Error "ActiveX component can't create object".
GetObject() expects a string value, not a reference, so add quotes to it:
Set WordApp = GetObject(, "Word.Application")

I need to get current active word document name using late binding in vba

I am using create object but can I get active document name using create object. I am doing late bindings because incompatibility with word versions.
Here is my code:
Dim app as Object
Set app = createobject("Word.Application")
Dim wrddoc as Object
Set wrddoc = app.ActiveDocument
In this example, just because we create an instance of Word it doesn't mean there are any Word documents in our Word Application. This is something we have to explicitly do in VBA when we work with different Office Applications.
You were close, but you were missing a line of code:
'Declare your variables
Dim WrdApp as Object
Dim WrdDoc as Object
'Create an instance of Word, and make it visible.
Set WrdApp = CreateObject("Word.Application")
WrdApp.Visible
'Create a document in the word application, by default this will be the active document.
Set WrdDoc = app.Documents.Add

Add specific Document to specific Word.Application

May I assign the objDoc as a document of the ObjWord (after Set objDoc = oDoc.Object)?
My code looks like this:
'Declaration
Dim oDoc As OLEObject
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim WS as Worksheet
Dim strOdoc as String
'Initialization
Set WS = Whorksheets("Sheet1")
strOdoc = "WordDoc"
Set objWord = New Word.Application
'Set objWord = GetObject(, "Word.Application")
'I need using GetObject to be able to made the activated OLEDocument, invisible.
'And Need Set objWord = New Word.Application to be able
'to EndTask the WINWORD.EXE with objWord.Quit.
objWord.Visible = False
Set oDoc = WS.OLEObjects(strOdoc)
oDoc.Activate
Set objDoc = oDoc.Object
'I need here Add the objDoc to the objWord
I need objDoc to have been a document of the objWord object, which has been hidden with objWord.Visible = False (I can't use Dim objDoc As objWord.Document variable declaration).
I need the objWord to have been isolated because when using
objWord.Quit, it must not try to close other Word Documents. (Here I used Set objWord = New Word.Application)
I need using the GetObject statement to be able to made the activated OLEDocument invisible.
And Need Set objWord = New Word.Application to be able to EndTask the
WINWORD.EXE with objWord.Quit.
But how can integrate two above advantages: 1) Working Invisible with the OLEObjectDocument and 2) Perform EndTask the WINWORD.EXE if no other word documents are opened?
Please take a more logical, step-by-step approach. Bear in mind that you need the Microsoft Word Object Library to be referenced (VBE > Tools > References).
Now you can create an instance of the Word application. It is invisible by default. You can use it and quit it without affecting any other instances of the Word that might be running concurrently. That part of your code is logically correct but the recommended code is Set objWord = CreateObject("Word.Application"). This creates a new instance. I'm not sure if Set objWord = New Word.Application perhaps does the same thing but you shouldn't need both.
Now you can open a document. Use the Documents.Open method to do that. The document will be of Word.Document data type, not an OLEObject. This document will open in a window and it is that window which you can make invisible. Address it as objWord.Windows(1) or objWord.ActiveWindow. Perhaps there will be a flicker on the screen which you might combat with objWord.ScreenUpdating = False.
After these steps you would have a normal Word document, invisible in its own Window, open in an instance of Word which has no other document open in it. You can manipulate that document, close it and then quit objWord.

Unable to work with word applications from excel

I am trying to open word document from the excel but stuck at the first line when I am using the below code. I have added reference still get the compile error user- defined type not defined.
Dim oApp As Word.Application
Dim oSec As Word.Section
Dim oDoc As Word.Document
Set AppWord = CreateObject("Word.Application")
Set oApp = New Word.Application
Set oDoc = oApp.Documents.Add
You need to add a reference in the VBA context by opening VBA (Developer Tab, Click: Visual Basic), Select your Workbook and Click from the menu: Tools, References.
In the references list find the Word Object Library and make sure it is checked before clicking OK
Now try again, and don't forget to make oApp visible! :
Sub Test()
Dim oApp As Word.Application
Dim oSec As Word.Section
Dim oDoc As Word.Document
Set AppWord = CreateObject("Word.Application")
Set oApp = New Word.Application
Set oDoc = oApp.Documents.Add
oApp.Visible = True
End Sub

Resources