Consulting

Results 1 to 1 of 1

Thread: Auto save word document not running if document opened using VBA?

  1. #1

    Auto save word document not running if document opened using VBA?

    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:

    Option Explicit
    
    Public WithEvents oApp As Word.Application
    Private Sub oApp_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
        ActiveDocument.Save
    End Sub
    c. This class needs to be instantiated so add a new (normal) module.
    d. in this module paste the following code:

    Option Explicit
    Dim oAppClass As New oAppClass
    
    Public Sub AutoOpen()
        Set oAppClass.oApp = Word.Application
    End Sub
    The problem I have is I open the document from access using:

    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
    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.

    Can anyone help with what is going wrong?
    Last edited by Aussiebear; 02-05-2025 at 11:58 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •