Search code examples
excelvbams-wordopenfiledialog

How to make a macro that allows the user to choose and open a word file


I have an Excel file and I want to have a macro in it that allows the user to choose any Word File and then open this selected file. Is this possible?

May I know what is the correct way to achieve my objective?


Solution

  • To select the file, you can use Excel Application's .GetOpenFilename method.
    The method returns the selected file's full path.

    Dim oWFile As String
    oWFile = Application.GetOpenFilename("Word File, *.docx")
    

    Now to open the file, you need to get/create an instance of Word.
    Meaning you have to bind Word to Excel. Sample below

    Dim oWApp As Word.Application
    '~~> get instance if already existing
    On Error Resume Next
    Set oWApp = GetObject(, "Word.Application")
    On Error GoTo 0
    '~~> create it otherwise
    If oWApp Is Nothing Then Set oWApp = CreateObject("Word.Application")
    '~~> make sure it is visible
    oWApp.Visible = True
    '~~> Open the word file using the grabbed/created Word Application Object
    '~~> and the full file path we get using the .GetOpenFilename method
    oWApp.Documents.Open oWFile
    

    I used Early Binding where in you need to reference the Microsoft Word Object Library.
    To do this, in VBE go to Tools > References and select
    Microsoft Word 14.0 Object Library (for office 2010).
    The number varies depending on the office version.