在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)
提前感谢您的答案
Edit 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)。
答案 0 :(得分:0)
要使用相对路径打开文件,需要URLEncode文件名。 VBA中没有内置支持(newer Excel versions除外),但您可以使用@Tomarak的 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)
答案 1 :(得分:0)
由于问题仅发生在相对路径名称上,因此可以使用解决方法: 将路径转换为绝对路径。
Set fs = CreateObject("Scripting.FileSystemObject")
Set doc = Documents.Open(fileName:=fs.GetAbsolutePathName("foo#bar.docx"))
也许这种解决办法在所有情况下都不起作用,因为Documents.Open
使用文件名执行不清楚的处理。