【问题标题】:VBA Word : Error 5174 when Documents.Open with filename including pound sign #VBA Word:使用包含井号的文件名打开 Documents.Open 时出现错误 5174 #
【发布时间】:2016-10-17 22:48:37
【问题描述】:

在 Microsoft Word 2010 VBA 中

我在尝试打开文件名包含井号“#”的文档时遇到运行时错误 5174,并带有相对文件路径。

Sub openPoundedFilename()
    Dim doc As Object
    ' Both files "C:\Temp\foo_bar.docx" and "C:\Temp\foo#bar.docx" exist

    ' With absolute file paths
    Set doc = Documents.Open(fileName:="C:\Temp\foo_bar.docx") ' Works
    doc.Close
    Set doc = Documents.Open(fileName:="C:\Temp\foo#bar.docx") ' Works
    doc.Close

    ' With relative file paths
    ChDir "C:\Temp"
    Set doc = Documents.Open(fileName:="foo_bar.docx") ' Works
    doc.Close
    Set doc = Documents.Open(fileName:="foo#bar.docx") ' Does not work !!!!
    'Gives runtime error 5174 file not found (C:\Temp\foo)
    doc.Close
End Sub

我没有找到任何解释为什么最后一个 Documents.Open 失败。
这可能与用于 URL 的“#”符号不匹配有关。
(见https://support.microsoft.com/en-us/kb/202261

提前感谢您的回答


编辑 17/10/2016 13:37:17
宏录制会生成以下内容:

Sub Macro1()
'
' Macro1 Macro
'
'
    ChangeFileOpenDirectory "C:\Temp\"
    Documents.Open fileName:="foo#bar.docx", ConfirmConversions:=False, _
        ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
        PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
        WritePasswordTemplate:="", Format:=wdOpenFormatAuto, XMLTransform:=""
End Sub

此宏不起作用(给出相同的错误 5174)。

【问题讨论】:

  • #后面的都是子地址,可以试试Record Macro看看生成的代码。
  • 似乎只适用于完整路径Documents.Open CurDir & "\foo#bar.docx"

标签: vba ms-word


【解决方案1】:

要使用相对路径打开文件,您需要对文件名进行 URLEncode。 VBA 中没有内置支持这样做(除了newer Excel versions),但您可以使用@Tomalak 的URLEncode 函数,它应该将foo#bar.docx 编码为foo%23bar.docx

ChangeFileOpenDirectory "C:\Temp\"

Dim urlEncodedFilename as String
urlEncodedFilename = URLEncode("foo#bar.docx")
Set doc = Documents.Open(fileName:=urlEncodedFilename) 

【讨论】:

    【解决方案2】:

    由于该问题仅发生在相对路径名上,因此可以使用解决方法: 将路径转换为绝对路径。

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set doc = Documents.Open(fileName:=fs.GetAbsolutePathName("foo#bar.docx"))
    

    也许这种变通方法并不适用于所有情况,因为Documents.Open 对文件名进行了不明确的处理。

    【讨论】:

      猜你喜欢
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2020-08-28
      相关资源
      最近更新 更多