VBA 中的 Workbooks.Open 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5944068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Workbooks.Open Method in VBA
提问by Nano HE
My vba script in myMacro.xlsWorkbooks.Open
Method work well as below,
我在myMacro.xlsWorkbooks.Open
方法中的vba 脚本运行良好,如下所示,
Workbooks.Open Filename:="D:\ExcelMacroProj\myTest.xls", ReadOnly:=True
But when I try to change the Filename
value to a new path as below, but all my practices didn't work. Show Run time error 1004.
但是当我尝试将Filename
值更改为如下所示的新路径时,但我的所有做法均无效。显示运行时错误 1004。
Workbooks.Open Filename:="myTest.xls", ReadOnly:=True
or
Workbooks.Open Filename:="./myTest.xls", ReadOnly:=True
or
Workbooks.Open Filename:=".\myTest.xls", ReadOnly:=True
Actually myMacro.xlsand myTest.xlswas placed in the same folder. That's why I want to change to a flexible folder directory.
实际上myMacro.xls和myTest.xls放在同一个文件夹中。这就是为什么我要更改为灵活文件夹目录的原因。
how could I fix this issue? Appreciated for your read and reply.
我怎么能解决这个问题?感谢您的阅读和回复。
回答by GSerg
Filename
is relative to the current Excel directory (which is different from the directory in which an opened document is).
Filename
相对于当前 Excel 目录(不同于打开文档所在的目录)。
You change the current directory by using ChDir "x:\new\path"
.
您可以使用 更改当前目录ChDir "x:\new\path"
。
But what you actually want to do is:
但你真正想做的是:
Workbooks.Open Filename:=EnsureSlash(ThisWorkbook.Path) & "myTest.xls", ReadOnly:=True
, where EnsureSlash
is your custom function that appends a backslash (\
) to the end of the string, if it's not already there (because ThisWorkbook.Path
ends with a slash when the path is the root directory, and doesn't otherwise).
,在字符串末尾EnsureSlash
附加反斜杠 ( \
) 的自定义函数在哪里,如果它不存在(因为ThisWorkbook.Path
当路径是根目录时以斜杠结尾,否则不会)。
回答by Greg Haskins
You might try using ThisWorkbook.Path
to make an absolute path. It returns the folder path of the workbook running the macro (excluding the filename). Something like this should work:
您可以尝试使用ThisWorkbook.Path
来创建绝对路径。它返回运行宏的工作簿的文件夹路径(不包括文件名)。这样的事情应该工作:
Workbooks.Open Filename:=ThisWorkbook.Path & "\myTest.xls", ReadOnly:=True
Make sure to include a backslash, since the workbook path doesn't end with one.
确保包含一个反斜杠,因为工作簿路径不以一个结尾。