Documents.Open使用FileSystemObject返回“5174 - 找不到文件”,但并非总是如此

问题描述 投票:0回答:1

我想将文件夹中的所有docx文件转换为PDF。为了实现我的目标,我将所有文件(仅docx)放在与docm相同的文件夹中并运行宏。它工作,但现在它没有,即使相同的文件不再工作。有时适用于第一个文件并停止使用以下警报:“运行时错误'5174':找不到此文件(C:\ Users ... \ Archive.docx)”

问题始终在Documents.Open上

试过“OpenAndRepair”,“ReadOnly”,什么都不做,等等。

Sub Converter()
    Dim CurrentFolder As String
    Dim FileName As String
    Dim myPath As String

    'Store Information About Word File
    myPath = ActiveDocument.FullName

    FileName = Mid(myPath, InStrRev(myPath, "\") + 1)
    Dim strCaminho As String

    strCaminho = ActiveDocument.Path

    Dim fso As Object 'Scripting.FileSystemObject
    Dim fld As Object 'Scripting.Folder
    Dim fl As Object 'Scripting.File
    Dim atual As String


    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fld = fso.GetFolder(strCaminho)


        For Each fl In fld.Files

        If fl.Name <> FileName Then 'doesn't try to open the file with macro
        Documents.Open FileName:=fl.Name

        Word_ExportPDF 'A function that works

        ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
        End If


        Next fl

End Sub

我的代码是来自其他宏的Frankenstein,有没有更好的方法来自动化这种转换?

vba ms-word
1个回答
1
投票

实施共产国际提出的建议:

您不需要解析FileName - Word.Document让您直接访问.Name。我要做的第一件事是首先收集文件的名称,然后导出它们。在迭代它时,您正在修改目录内容。 - 共产国际

然后,可以将以下内容添加到代码中以检查有效的文档扩展名:

If fl.Name <> FileName Then 'doesn't try to open the file with macro

    If LCase(fso.GetExtensionName(fl.Path)) = "docx" Then  '<----This Line
        Documents.Open FileName:=fl.Path   '<--------------------This Line

        Word_ExportPDF 'A function that works

        ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
    End if

End if
© www.soinside.com 2019 - 2024. All rights reserved.