Word VBA, Open Document

In this article I will explain how you can open a word document using VBA.


Contents

Opening Word Document:

If you are opening a word document from word you can use the code below:

Sub main()
Documents.Open ("D:TestFolderMain.docx")
End Sub

Where “D:TestFolderMain.docx” is the path where the word document is located.


Opening Word Document From Other Applications:

If you are opening a word document from another application, you would need to automate a word application first. This can be done using the code below:

Sub main()
Dim objWord As Object
'automate word application
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'open word document
objWord.documents.Open ("D:TestFolderMain.docx")
End Sub

For more information about automating word applications please see the article below:


Using Open File Dialogs

You could also ask the user to choose the path of the word document using an open file dialogs. I have covered this topic in detail in the article below. Although the article was written for VBA for Excel, the concept can also be used in VBA for Word:

In the sample code below the user is asked to select the location of the word file from an open file dialog. After selecting the file, it is opened:

Sub main()
Dim intChoice As Integer
Dim strPath As String
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True

Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'if the user selects a file
If intChoice <> 0 Then
    'get the path selected
    strPath = Application.FileDialog( _
        msoFileDialogOpen).SelectedItems(1)
    'opens the document
    objWord.documents.Open (strPath)
End If
End Sub

 See also:

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

 

Leave a Reply

Your email address will not be published. Required fields are marked *