我有一个带有书签的Word模板。这些书签通过 VBA 代码从 Access 数据库应用程序中提取数据。
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"
问题是如何打开模板的副本以允许用户在查看文档后单击"保存"?目前使用原始模板,用户必须执行"另存为"。这不方便。
Word 中的"模板"是一种特定的文件类型(.dot、.dotx 或 .dotm)。就目前而言,您没有Word"模板",只有一个标准的Word文档(.doc)。
在 Word 中打开此.doc并将其另存为"文档模板 (.dot)"。
现在,更改行 Documents.Open to Documents.Add,引用新的 .dot 并更改参数以匹配 Add 方法的参数。
这将自动打开模板文件的 COPY,因此用户或您的代码永远不会有任何覆盖模板的危险。
但是请注意,由于这是一个新文档,因此仍然需要"另存为",但它会自动出现 - 用户不必考虑使用另存为。如果根本不希望用户看到"另存为",则代码需要执行 Document.SaveAs,并且需要知道应保存到的文件路径和位置。