我一生无法弄清楚为什么在随后的运行中会出错。
它将第一次运行完美,然后在行上出错:Selection.WholeStory
当错误开始发生时,我在TaskManager中确认没有单词实例在我尝试再次运行之前运行。 Restarting Access似乎可以解决该问题,因为它将在重新启动后第一次成功运行。
我正在创建文件中的文件夹并不是oneDrive同步
初始化我也尝试过的对象时:
Set gobjWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Err.Clear
Set gobjWord = **CreateObject("Word.Application")**
gblnWordCreated = True
gobjWord.Activate
gobjWord.Visible = True
End If
我尝试了晚期和早期绑定
Dim objWord As Object
there是完整的功能:
Public Function f_Test(lID As Long, strSQL As String)
Dim objWord As Word.Application
Dim blnWordCreated As Boolean
Dim NewDoc As Word.Document
Dim TemplateDoc As Word.Document
Dim strTemplatePath As String
Dim strNewFilePath As String
Dim strNewFileName As String
Dim rs As DAO.Recordset
On Error Resume Next
blnWordCreated = False
Set objWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Err.Clear
Set objWord = New Word.Application
blnWordCreated = True
objWord.Activate
objWord.Visible = True
End If
On Error GoTo Error_Handler
Set rs = CurrentDb.OpenRecordset(strSQL)
If rs.RecordCount > 0 Then
With rs
strNewFilePath = "c:\Test\" & lID & "\"
strNewFileName = strNewFilePath & "Empty " & f_GetDateForUseInFileName(Now()) & ".docx"
.MoveFirst
Set NewDoc = objWord.Documents.Add 'Create a new document
NewDoc.SaveAs2 strNewFileName
Do Until .EOF
strTemplatePath = !FileName
Set TemplateDoc = objWord.Documents.Open(FileName:=strTemplatePath)
' Copy Entire Document
TemplateDoc.Activate
Selection.WholeStory ' THIS IS WHERE IT ERRORS OUT ON SUBSEQUENT RUNS
Selection.Copy
' Activate New Document and Paste
NewDoc.Activate
Selection.PasteAndFormat (wdUseDestinationStylesRecovery)
Selection.InsertBreak Type:=wdPageBreak
' Close Template without saving
TemplateDoc.Close SaveChanges:=wdDoNotSaveChanges
.MoveNext
Loop
End With
End If
Exit_Routine:
' cleanup
rs.Close
Set rs = Nothing
NewDoc.Close SaveChanges:=wdSaveChanges
Set TemplateDoc = Nothing
Set NewDoc = Nothing
If blnWordCreated Then
objWord.Quit
Set objWord = Nothing
End If
Exit Function
Error_Handler:
Debug.Print Err.Number & " " & Err.Description
Resume Exit_Routine
End Function
解决方案是按照蒂姆建议的选择。election。