write macro to open a word document

jakobt

Active Member
Joined
May 31, 2010
Messages
337
Want to write a VBA code to open a word document shored under S:\Book.Docx
 

Excel Facts

Move date out one month or year
Use =EDATE(A2,1) for one month later. Use EDATE(A2,12) for one year later.
Here's an example where the code first checks whether Word is already running. If so, it assigns it to an object variable. If not, it starts Word and assigns it to an object variable. If it's not successful in starting Word, it exits the sub. Otherewise, it tries to open a Word document. If successful, it assigns it to another object variable. If not, it exits the sub.

Code:
Sub test()

    Dim wdApp As Object
    Dim wdDoc As Object
    
    On Error Resume Next
    Set wdApp = GetObject(, "Word.Application")
    If Err.Number <> 0 Then
        Err.Clear
        Set wdApp = CreateObject("Word.Application")
        If Err.Number <> 0 Then
            MsgBox "Unable to open Word!", vbExclamation
            Exit Sub
        End If
    End If
    On Error GoTo 0
    
    On Error Resume Next
    Set wdDoc = wdApp.documents.Open("c:\users\domenic\desktop\doc1.docx")
    If wdDoc Is Nothing Then
        MsgBox "Unable to open Word document!", vbExclamation
        Exit Sub
    End If
    On Error GoTo 0
    
    'Make Word visible
    wdApp.Visible = True
    
    'etc
    '
    '
    
    'Release objects from memory
    Set wdDoc = Nothing
    Set wdApp = Nothing
    
End Sub

Hope this helps!
 
Upvote 0

Forum statistics

Threads
1,214,929
Messages
6,122,314
Members
449,081
Latest member
tanurai

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top