如何修复 VBA 中的 "Execution Error 429 : ActiveX can't create object" 错误

How to fix "Execution Error 429 : ActiveX can't create object" error in VBA

下面的这个 Excel 宏应该将所有 .Docx 转换为选定文件夹中的 .Pdf

这是为我提供错误代码 429 的代码行,但几个小时前,同一行代码还在工作。

Documents.Open (filePath & currFile) 'Error Code 429

这里是完整的宏代码

Sub ConvertDocxInDirToPDF()

Dim filePath As String
Dim currFile As String

filePath = ActiveWorkbook.Path & "\"
MsgBox filePath
currFile = Dir(filePath & "*.docx")

Do While currFile <> ""

    Documents.Open (filePath & currFile) 'Error Code 429

    Documents(currFile).ExportAsFixedFormat _
        OutputFileName:=filePath & Left(currFile, Len(currFile) - Len(".docx")) & ".pdf", _
        ExportFormat:=17
    Documents(currFile).Close

    currFile = Dir()

Loop

Application.ScreenUpdating = True

End Sub

有没有一种简单的方法可以使这个宏工作并修复这个错误。

此致。

Documents.Open 是 Documents 对象的一个​​方法,它需要 "MS Word Object Library" 才能起作用,而不是明确地引用一个单词对象:

这是什么意思?如果 Microsoft Word 1X.0 引用被选中(VBE>Extras>Libraries),那么下面的代码工作得很好:

Sub TestMe()

    Dim filePath As String
    filePath = ThisWorkbook.Path & "\"
    Dim currFile As String
    currFile = Dir(filePath & "*.docx")

    Dim wrdDoc As Object
    Documents.Open filePath & currFile

End Sub

如果 "MS Word Object Library" 没有被引用,那么后期绑定仍然可以引用对象。 (后期绑定为 CreateObject("Word.Application")):

Sub TestMe()

    Dim filePath As String
    filePath = ThisWorkbook.Path & "\"
    Dim currFile As String
    currFile = Dir(filePath & "*.docx")

    Dim wrdApps As Object
    Set wrdApps = CreateObject("Word.Application")
    wrdApps.Documents.Open (filePath & currFile)

End Sub

如果需要,Documents.Open 可以 return 文档对象:

Sub TestMe()

    Dim filePath As String
    filePath = ThisWorkbook.Path & "\"
    Dim currFile As String
    currFile = Dir(filePath & "*.docx")

    Dim wrdApps As Object
    Set wrdApps = CreateObject("Word.Application")

    Dim wrdDoc As Object
    Set wrdDoc = wrdApps.Documents.Open(filePath & currFile)

End Sub