Referencing Workbook and Worksheet by Variables

心不动则不痛 提交于 2020-01-13 17:03:25

问题


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

回答1:


Change

Set mWS = Sheets("Invoices")

To

Set mWS = mWb.Sheets("Invoices")

Then just write mWS.Range("A1").FormulaR1C1 = "Import Date" on the last line.

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.



来源:https://stackoverflow.com/questions/13146558/referencing-workbook-and-worksheet-by-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!