简体   繁体   中英

Word bookmarks template using Access data

I have a Word template with bookmarks. These bookmarks pull data from an Access database application via VBA code.

On Error GoTo ErrHandler
Me.Recalc

If Me!txtCount = 0 Then
    MsgBox "Please select a record to print.", vbOKOnly, "Error"
Else

Dim oWord As Object 'Word.Application
Dim doc As Object 'Word.Document

Set oWord = CreateObject("Word.Application")
Set doc = oWord.Documents.Open("C:\Request_Template.doc")
oWord.Visible = True

Dim oAccess As Object
Dim dbs As Database
Dim rst As Recordset

Dim strCriteria As String

      With oWord.ActiveDocument
            If .Bookmarks.Exists("DatePage1") = True Then
               .Bookmarks("DatePage1").Select
               If Not IsNull([Forms]![frmForRequest_Preview]!Date) Then
                  oWord.selection.Text = (CStr(Format([Forms]![frmForRequest_Preview]!Date, "mmm d, yyyy")))
               Else
                  oWord.selection.Text = ""
            End If
      End With
End If
Exit Sub

ErrHandler:
MsgBox Err.Number & ": " & Err.Description, vbOKOnly, "Error"

The question is how to open a copy of the template to allow the user to click on "Save" after reviewing the document? For now the original template is used and the user has to perform "Save As". That is not convenient.

"Template" in Word is a specific file type (.dot, .dotx or .dotm). As it stands, you don't have a Word "template", just a standard Word document (.doc).

Open this .doc in Word and save it as a "Document Template (.dot).

Now, change the line Documents.Open to Documents.Add, referencing the new .dot and changing the parameters to match those of the Add method.

This will automatically open a COPY of the template file, so there is never any danger of the user or your code overwriting the template.

Note, however, that "Save As" is still required since this is a new document, but it will come up automatically - the user won't have to think to use Save As. If you don't want the user to see Save As at all your code needs to perform Document.SaveAs and you need to know the file path and location to which it should be saved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM