【问题标题】:Documents.Open using FileSystemObject returns "5174 - could not find the file" but not alwaysDocuments.Open 使用 FileSystemObject 返回“5174 - 找不到文件”,但并非总是如此
【发布时间】:2019-07-01 18:54:26
【问题描述】:

我想将文件夹中的所有 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

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

【问题讨论】:

  • 您无需解析 FileName - Word.Document 即可通过 .Name 直接访问它。我要做的第一件事是先收集文档的名称,然后然后 导出它们。您在迭代时正在修改目录内容。

标签: vba ms-word


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2020-01-19
    相关资源
    最近更新 更多