为什么此 Excel 宏获取运行时错误 4198?

Why is this Excel Macro Getting Run-time error 4198?

提问人:MacroManRandySavage 提问时间:11/9/2023 最后编辑:FunThomasMacroManRandySavage 更新时间:11/9/2023 访问量:100

问:

我正在运行一个宏,该宏使用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
Excel VBA MS-Word

评论

1赞 Darren Bartrup-Cook 11/9/2023
xlBook是。。。。。你保存了文件了吗?否则,ThisWorkbook 没有路径。中是否有任何非法的文件名字符?如果放入“即时”窗口,它会返回有效路径吗?ThisWorkbookxlSheet.Cells(r, 1)?xlBook.Path & "\Letters\" & xlSheet.Cells(r, 1) & ".docx"
0赞 MacroManRandySavage 11/9/2023
你好。是的,工作簿已保存下来,文件名避免了除空格以外的任何非法字符,尽管删除这些字符仍会返回相同的运行时错误。放置 ?xlBook.Path & “\Letters\” & xlSheet.Cells(r, 1) & “.docx” 在“即时”窗口中返回运行时错误 424,但我不确定为什么,因为宏可以很好地保存到路径中。
0赞 CDP1802 11/9/2023
使用的范围内是否有任何空白单元格。添加后Msgbox xlSheet.UsedRange.AddressSet xlSheet = ..
1赞 Tim Williams 11/10/2023
文件夹是否已存在?如果您将它设置为可见,这可能会为您提供一些您看不到的其他信息,因为它被隐藏了。LetterswdApp
0赞 MacroManRandySavage 11/10/2023
谢谢。所以返回 ,但根据字母量,并非所有单元格都会被填充。MsgBox xlSheet.UsedRange.Address$A$1:$J$19

答: 暂无答案