通过变量引用工作簿和工作表

时间:2012-10-30 19:45:56

标签: variables excel-vba vba excel

引用不同工作簿工作表的正确语法是什么?以下代码在最后一行引发错误。谢谢!

'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 个答案:

答案 0 :(得分:7)

更改

Set mWS = Sheets("Invoices")

Set mWS = mWb.Sheets("Invoices")

然后在最后一行写下mWS.Range("A1").FormulaR1C1 = "Import Date"

实际上,您可以将最后一行更改为我放置的内容,因为您的ActiveWorkbook没有更改,但是,最佳做法是准确限定所有变量,因此意外行为不会发生。