Opening and closing a Word document from Access VBA - Microsoft Community


Mon Oct 16 2023 09:52:14 GMT+0000 (Coordinated Universal Time)

Saved by @paulbarry

Private Sub Command0_Click()
    Dim DocN As String
    Dim LWordDoc As String
    Dim oApp As Object
    Dim oDoc As Object
    Dim oVariable As Variable
    DocN = "Demo use of variables.docx"
    'Path to the word document
    LWordDoc = "C:\Temp\20230411 test\" & DocN
    If Dir(LWordDoc) = "" Then
        MsgBox "Document not found."
        'Create an instance of MS Word
        Set oApp = CreateObject(Class:="Word.Application")
        oApp.Visible = True
        'Open the Document
        Set oDoc = oApp.Documents.Open(Filename:=LWordDoc)
    End If
    Call dump_to_file("")
    For Each oVariable In oDoc.Variables
        Call append_to_file(oVariable.Name & " : " & oVariable.Value)
    Next oVariable
    ' Close doc
    oDoc.Close SaveChanges:=True ' True to save, False to close without saving
    Set oDoc = Nothing
    Set oApp = Nothing
    MsgBox "done"
End Sub