On Error GoTo Err_cmdExportToWord_Click
Dim objApp As Object 'Word.Application
Dim objDoc As Object 'Word.Document
Dim win As Object 'Word.窗口
Dim doc As Object
Dim docApp As Object
Dim strTemplates As String '模板文件路径名
Dim strFileName As String '将数据导出到此文件
Dim rstDetails As DAO.Recordset
Set rstDetails = CurrentDb.OpenRecordset("SELECT 报告编号, 规格型号, 计量单位, 数量, 单价, 金额, 备注 FROM 发票明细表 WHERE 项目编号=" & Me项目编号)
'如果没有记录 , 不执行下面程序
If rstDetails.EOF Then Exit Sub
If Me.NewRecord Then
MsgBox "当前没有可导出的数据。", vbInformation, "提示"
Exit Sub
End If
'通过文件对话框生成另存为文件名
With FileDialog(2) 'msoFileDialogSaveAs
.InitialFileName = CurrentProject.Path & "\常规项目报告模板.doc"
If .Show Then strFileName = .SelectedItems(1)
End With
'如果对话框被取消,则变量没有被赋值,退出过程
If strFileName = "" Then Exit Sub
'文件名必须包括“.doc”的文件扩展名,如没有则自动加上
If Not strFileName Like "*.doc" Then strFileName = strFileName & ".doc"
'如果文件已存在,则删除已有文件
If Dir(strFileName) <> "" Then Kill strFileName
'将光标设置为沙漏形,以示正在执行程序
DoCmd.Hourglass True
'打开模板文件
Set objApp = CreateObject("Word.Application") 'createObject("类名")
objApp.Visible = True
Set objDoc = objApp.Documents.Open(strTemplates, , True)
Set win = doc.ActiveWindow
With win.Selection.Find '使用查找和替换
Exit_cmdExportToWord_Click:
If Not objDoc Is Nothing Then objApp.Visible = True
'恢复光标形状
DoCmd.Hourglass False
Set objApp = Nothing
Set objDoc = Nothing
Set objTable = Nothing
Exit Sub
On Error GoTo Err_cmdExportToWord_Click
Dim objApp As Object 'Word.Application
Dim objDoc As Object 'Word.Document
Dim win As Object 'Word.窗口
Dim doc As Object
Dim docApp As Object
Dim strTemplates As String '模板文件路径名
Dim strFileName As String '将数据导出到此文件
If Me.NewRecord Then
MsgBox "当前没有可导出的数据。", vbInformation, "提示"
Exit Sub
End If
'通过文件对话框生成另存为文件名
With FileDialog(2) 'msoFileDialogSaveAs
.InitialFileName = CurrentProject.Path & "\常规项目报告模板.doc"
If .Show Then strFileName = .SelectedItems(1)
End With
'如果对话框被取消,则变量没有被赋值,退出过程
If strFileName = "" Then Exit Sub
'文件名必须包括“.doc”的文件扩展名,如没有则自动加上
If Not strFileName Like "*.doc" Then strFileName = strFileName & ".doc"
'如果文件已存在,则删除已有文件
If Dir(strFileName) <> "" Then Kill strFileName
'将光标设置为沙漏形,以示正在执行程序
DoCmd.Hourglass True
'打开模板文件
Set objApp = CreateObject("Word.Application") 'createObject("类名")
objApp.Visible = True
Set objDoc = objApp.Documents.Open(strTemplates, , True)
Set win = objDoc.ActiveWindow
With win.Selection.Find '使用查找和替换
.Text = "[报告编号]"
.Replacement.Text = Nz(Me.报告编号)
.Execute , , , , , , , , , , 2 '全部替换
End With
Exit_cmdExportToWord_Click:
If Not objDoc Is Nothing Then objApp.Visible = True
'恢复光标形状
DoCmd.Hourglass False
Set objApp = Nothing
Set objDoc = Nothing
Set objTable = Nothing
Exit Sub
应该将查找替换功能独立写为函数:
function 查找替换(doc as Word.Document,str0 as string,str1 as string)
with doc.selection.find
.text=str0
.replacement.text=str1
end with
end function