按路径和名称引用工作簿 - VBA
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13751610/
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
Ref workbook by path and name - VBA
提问by Sam
Sub Quack()
Dim LookupWB As Workbook
Set LookupWB = Application.Workbooks("C:\Users\user1\Desktop\Book1.xlsx")
End Sub
This code gives an error:
这段代码给出了一个错误:
Subscript out of range I think it's because of the "Set" line. How do you correctly reference a workbook by path?
下标超出范围我认为是因为“设置”行。如何按路径正确引用工作簿?
If I write: Set LookupWB = Application.Workbooks("Book1.xlsx")
(without full path) it work perfectly.
Thanks a lot!
如果我写:(Set LookupWB = Application.Workbooks("Book1.xlsx")
没有完整路径)它工作得很好。非常感谢!
回答by thornomad
I think you need to use the Open
function first:
我认为您需要先使用该Open
功能:
Workbooks.Open Filename:="C:\Users\user1\Desktop\Book1.xlsx"
Set LookupWB = Application.Workbooks("Book1.xlsx")
回答by Kes Perron
If the workbook is already open, you don't need to include the path. That's why Set LookupWB = Application.Workbooks("Book1.xlsx")
works.
如果工作簿已打开,则不需要包含路径。这就是为什么Set LookupWB = Application.Workbooks("Book1.xlsx")
有效。
If the workbook is closed, then you have to include the Open function (see @thornomad's answer).
如果工作簿已关闭,则您必须包含 Open 函数(请参阅@thornomad 的回答)。