[英]How to refer correct worksheet in specific workbook when multiple workbooks are open?
Sub debug_tester()
Dim A As Workbook
Set A = Workbooks.Open("D:\a.xlsm")
Dim B As Workbook
Set B = Workbooks.Open("D:\b.xlsm")
A.Sheets("sheet1_in_test").range("A1").Value = "test" 'pop out "subscript out of range" on this line
End Sub
And "sheet1_in_test" does exist in A. If I change it to number (ie sheet(1)) B is the one changed. 而且“ sheet1_in_test”确实存在于A中。如果我将其更改为数字(即sheet(1)),则B是已更改的。
Edit: Correct the typos. 编辑:更正错别字。 Workbook A has one sheet named "sheet1_in_test".
工作簿A有一个名为“ sheet1_in_test”的工作表。 Workbook B has one sheet named "sheet1".
工作簿B有一个名为“ sheet1”的工作表。
Edit: Thanks sancho.s ! 编辑:谢谢sancho.s ! It seems like
Workbook.Open
cannot refer the workbook when the sub located on it. 看起来
Workbook.Open
子项位于它时无法引用该工作簿。 Using Set A = ThisWorkbook
seems work, too. 使用
Set A = ThisWorkbook
似乎也可以。 I'm wondering why is that. 我想知道为什么会这样。
This sub
, located in a separate workbook, performs as intended 该
sub
位于单独的工作簿中,按预期执行
Sub open_test()
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = Workbooks.Open("C:\Users\user1\Documents\a.xlsx")
Set wb2 = Workbooks.Open("C:\Users\user1\Documents\b.xlsx")
wb1.Sheets("Hoja1").Range("A1").Value = "test"
wb2.Sheets(1).Range("A1").Value = "test2"
End Sub
Try reproducing this. 尝试重现此内容。
Using Workbooks.Open() makes the opened workbook the active workbook. 使用Workbooks.Open()使打开的工作簿成为活动工作簿。 That's why using sheet(1) goes into workbook B. It's the last workbook opened and therefore the active workbook.
这就是为什么在工作簿B中使用sheet(1)的原因。这是最后打开的工作簿,因此也是活动的工作簿。 Use Workbook.Activate to make A the active workbook.
使用Workbook.Activate使A成为活动工作簿。
Sub debug_tester()
Dim A As Workbook
Set A = Workbooks.Open("D:\a.xlsm")
Dim B As Workbook
Set B = Workbooks.Open("D:\b.xlsm")
A.Activate
A.Sheets("sheet1_in_test").range("A1").Value = "test"
End Sub
If you still get the "subscript out of range" message, the "sheet1_in_test" worksheet is not in the A workbook. 如果仍然收到“下标超出范围”消息,则“ sheet1_in_test”工作表不在A工作簿中。 Check the spelling between the code and the worksheet name.
检查代码和工作表名称之间的拼写。 This assumes that you are running the code from a 3rd workbook.
假定您正在从第3个工作簿中运行代码。
If you are running this code from workbook A, Excel will close the open instance of A and reopen it but the code won't be running. 如果您正在工作簿A中运行此代码,则Excel将关闭A的打开实例并重新打开它,但该代码将无法运行。 In that case you can use
在这种情况下,您可以使用
Set A = ThisWorkbook
Or if the code is in workbook B use 或者如果代码在工作簿B中使用
Set B = ThisWorkbook
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.