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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:28:49  来源:igfitidea点击:

Workbooks.Open Method in VBA

vbaexcel-vbaexcel-2003excel

提问by Nano HE

My vba script in myMacro.xlsWorkbooks.OpenMethod work well as below,

我在myMacro.xlsWorkbooks.Open方法中的vba 脚本运行良好,如下所示,

Workbooks.Open Filename:="D:\ExcelMacroProj\myTest.xls", ReadOnly:=True

But when I try to change the Filenamevalue 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.xlsmyTest.xls放在同一个文件夹中。这就是为什么我要更改为灵活文件夹目录的原因。

how could I fix this issue? Appreciated for your read and reply.

我怎么能解决这个问题?感谢您的阅读和回复。

回答by GSerg

Filenameis 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 EnsureSlashis your custom function that appends a backslash (\) to the end of the string, if it's not already there (because ThisWorkbook.Pathends 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.Pathto 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.

确保包含一个反斜杠,因为工作簿路径不以一个结尾。