vba 按变量引用工作簿和工作表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13146558/
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
Referencing Workbook and Worksheet by Variables
提问by Liquidgenius
What is the proper syntax for referencing a different workbook's worksheet? The following code is throwing an error on the last line. Thanks!
引用不同工作簿的工作表的正确语法是什么?以下代码在最后一行抛出错误。谢谢!
'Instantiate Workbook variables
Dim mWB As Workbook 'master workbook
'Instantiate Worksheet variables
Dim mWS As Worksheet 'master worksheet
'Open Workbook, set variables and reference range
Workbooks.Open ("Local 500GB HD:Users:user:Public:file.xlsx")
Set mWB = ActiveWorkbook
Set mWS = Sheets("Invoices")
mWB.mWS.Range("A1").FormulaR1C1 = "Import Date" ' <---- This is the where the error is
回答by Scott Holtzman
Change
改变
Set mWS = Sheets("Invoices")
To
到
Set mWS = mWb.Sheets("Invoices")
Then just write mWS.Range("A1").FormulaR1C1 = "Import Date"
on the last line.
然后只写mWS.Range("A1").FormulaR1C1 = "Import Date"
在最后一行。
In effect, you could just change the last line to read like I placed above, since your ActiveWorkbook
is not changing, however, it's a best practice to qualify all your variables exactly, so unexpected behavior doesn't occur.
实际上,您可以将最后一行更改为我上面放置的内容,因为您ActiveWorkbook
没有更改,但是,最佳做法是准确限定所有变量,因此不会发生意外行为。