Word VBA – Macro to Open Word Document
Open Word Document
This Word VBA Macro will open a word document from the specified directory:
Sub OpenDoc() Dim strFile As String strFile = "c:\Users\Nenad\Desktop\Test PM.docm" 'change to path of your file If Dir(strFile) <> "" Then 'First we check if document exists at all at given location Documents.Open strFile End If End Sub
Now you can interact with the newly opened document with the ActiveDocument Object. This code will add some text to the document.
ActiveDocument.Range(0, 0).Text = "Add Some Text"
Open Document to Variable
You can also open a Word document, immediately assigning it to a variable:
Sub OpenDoc() Dim strFile As String Dim oDoc as Document strFile = "c:\Users\Nenad\Desktop\Test PM.docm" 'change to path of your file If Dir(strFile) <> "" Then 'First we check if document exists at all at given location Set oDoc = Documents.Open strFile End If End Sub
Allowing you to interact with the document via the variable oDoc.:
oDoc.Range(0, 0).Text = "Add Some Text"
Generally it’s best practice to open to a variable, giving you the ability to easily reference the document at any point.
Open Word Document From Excel
This VBA procedure will open a Word Document from another MS Office program (ex. Excel):
Sub OpenDocFromExcel() Dim wordapp Dim strFile As String strFile = "c:\Users\Nenad\Desktop\Test PM.docm" Set wordapp = CreateObject("word.Application") wordapp.Documents.Open strFile wordapp.Visible = True End Sub