提问人:MacroManRandySavage 提问时间:11/9/2023 最后编辑:FunThomasMacroManRandySavage 更新时间:11/9/2023 访问量:100
为什么此 Excel 宏获取运行时错误 4198?
Why is this Excel Macro Getting Run-time error 4198?
问:
我正在运行一个宏,该宏使用excel中的各种字段填充Word模板书签。宏本身运行良好并生成字母,但每次我也会由于以下行而弹出运行时错误 4198:
wdDoc.SaveAs2 xlBook.Path & "\Letters\" & xlSheet.Cells(r, 1) & ".docx"
我不确定 VBA 哪里出了问题,因此非常感谢任何帮助。
谢谢
Sub LetterGenerator()
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim wdApp As word.Application
Dim wdDoc As word.Document
Dim wdTemplatePath As String
Dim r As Long
'// INSTANIATE EXCEL OBJECTS
Set xlBook = ThisWorkbook
Set xlSheet = xlBook.Worksheets("Sheet1")
'// INSTANIATE WORD OBJECTS
Set wdApp = New word.Application
'// SET TEMPLATE PATH
wdTemplatePath = xlBook.Path & "\Letters\letterDoc.docx"
'// LOOP THORUGH EXCEL DATA ROWS
For r = 2 To xlSheet.UsedRange.Rows.Count
'// OPEN TEMPLATE
Set wdDoc = wdApp.Documents.Open(wdTemplatePath, , True)
'// LOOP THROUGH EXCEL COLUMNS
For c = 2 To xlSheet.UsedRange.Columns.Count
'// FILL BOOKMARK
wdDoc.Bookmarks(xlSheet.Cells(1, c)).Range = xlSheet.Cells(r, c)
Next c
'// SAVE AS DOC
wdDoc.SaveAs2 xlBook.Path & "\Letters\" & xlSheet.Cells(r, 1) & ".docx"
'// SAVE AS PDF
wdDoc.ExportAsFixedFormat xlBook.Path & "\Letters\" & xlSheet.Cells(r, 1) & ".pdf", wdExportFormatPDF
'// CLOSE WORD TEMPLATE
wdDoc.Close False
'// RELEASE OBJECT
Set wdDoc = Nothing
Next r
'// QUIT WORD
wdApp.Quit
'// RELEASE OBJECTS
Set wdApp = Nothing
Set xlSheet = Nothing
Set xlBook = Nothing
End Sub
有人建议添加以下内容,但没有用:
Sub UpdateBookmark(doc As Word.Document, bookmarkName As String, replacementText As String)
On Error Resume Next
doc.Bookmarks(bookmarkName).Range.Text = replacementText
On Error GoTo 0
End Sub
答: 暂无答案
评论
xlBook
是。。。。。你保存了文件了吗?否则,ThisWorkbook 没有路径。中是否有任何非法的文件名字符?如果放入“即时”窗口,它会返回有效路径吗?ThisWorkbook
xlSheet.Cells(r, 1)
?xlBook.Path & "\Letters\" & xlSheet.Cells(r, 1) & ".docx"
Msgbox xlSheet.UsedRange.Address
Set xlSheet = ..
Letters
wdApp
MsgBox xlSheet.UsedRange.Address
$A$1:$J$19