I have a word document I want to automatically save when it's closed. I found the code required to do this and it works:
To use application events do the following:
a. In your project add a new Class module.
b. Rename the module to (for instance): oAppClass
b. In this module paste the following code:
c. This class needs to be instantiated so add a new (normal) module.Option Explicit Public WithEvents oApp As Word.Application Private Sub oApp_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean) ActiveDocument.Save End Sub
d. in this module paste the following code:
The problem I have is I open the document from access using:Option Explicit Dim oAppClass As New oAppClass Public Sub AutoOpen() Set oAppClass.oApp = Word.Application End Sub
When I put the code to auto save into the document, save it as .docm open the file on its own, it saves fine when you close it. When I open it using the above code (having changed the docx to docm) upon manually closing it doesn't save.Dim oWord As Word.Application Dim oDoc As Word.Document Dim WordRange As Word.Range Set oWord = New Word.Application With oWord Set oDoc = .Documents.Open(Receipt, , False) End With Set WordRange = oDoc.GoTo(What:=wdGoToBookmark, Name:="Details") WordRange.InsertAfter Title & " " & [First Names] & " " & Surname & Chr(13) & ([Address 1] + Chr(13) + Chr(10)) & ([Address 2] + Chr(13) + Chr(10)) & ([City] + Chr(13) + Chr(10)) & ([Postal Code]) Set WordRange = oDoc.GoTo(What:=wdGoToBookmark, Name:="Date") If (WeekdayName(Weekday(Date))) <> "Monday" Then WordRange.InsertAfter WeekdayName(Weekday(Date) - 1) & " " & Format(Now, "long date") 'need -1 to set correct day or change in control panel Else WordRange.InsertAfter "Sunday" & " " & Format(Now, "long date") End If oWord.ActiveDocument.SaveAs filename:=drive & "Receipts\" & [First Names] & "_" & Surname & "_" & [ID] & ".docx" oWord.Quit Set oWord = Nothing Receiptexists: Set oWord = New Word.Application With oWord Set oDoc = .Documents.Open(drive & "Receipts\" & [First Names] & "_" & Surname & "_" & [ID] & ".docx", , False) End With oWord.Visible = True oWord.Activate oWord.Application.WindowState = xlMaximized
Can anyone help with what is going wrong?



Reply With Quote