Say I have two workbooks open with two tabs both named "Tab1". If in VBA, I want to refer to something on a tab, one would say "Tab1!" followed by what one is referring to, e.g. "Tab1!R1C1", etc.
However, how does the code know what Tab1 I am referring to in this case?
If it's worth mentioning, the code I am running is inside one of the workbooks. So will it always default back to that workbooks tab 1? If not, what does it do, and if yes, how would I make it refer to the tab 1 of the other workbook?
For context, I need to do this in the case of calling the method "ChangePivotCache" and give it a SourceData.
CodePudding user response:
Without the code it's difficult to say definitively, but lets assume that you're using a range
object. When you put "Tab1!R1C1"
into that range object it uses the workbook of it's parent to make the determination. Most (if not all) methods that take a range argument like that will require that some parent of theirs is a workbook or worksheet.
In general if you're working with multiple workbooks best practice is to assign an object to them as you open them. That object can then be used to anchor any range calls you make. Either by calling directly from it or making children from it.
For example:
set workbook_code_is_in = Thisworkbook
set another_workbook = Application.Workbooks.Open(...)
set active_workbook = Activeworkbook
The first line will set workbook_code_is_in
to the workbook that the code is located in.
The second line will set another_workbook
to whatever you open.
The third line will set active_workbook
to whatever workbook currently has focus. This is dangerous and prone to errors. It's very possible for a user to click a different workbook while a script is running and make the Activeworkbook an unintended one.
CodePudding user response:
Referring to a Second Workbook
- If you only have two workbooks open, then you refer to the workbook containing this code with
ThisWorkbook
and you can refer to the other workbook by using aFor Each...Next
loop to compare the workbooks' names.
Option Explicit
Sub ReferToSecondWorkbook()
Dim wb1 As Workbook: Set wb1 = ThisWorkbook ' workbook containing this code
If Workbooks.Count <> 2 Then
MsgBox "You need to have only two workbooks open.", vbCritical
Exit Sub
End If
Dim wb2 As Workbook
For Each wb2 In Workbooks
If StrComp(wb2.Name, wb1.Name, vbTextCompare) <> 0 Then ' different
Exit For
' Else ' it is 'wb1'
End If
Next wb2
Dim ws1 As Worksheet: Set ws1 = wb1.Worksheets("Tab1")
Dim ws2 As Worksheet: Set ws2 = wb2.Worksheets("Tab1")
Debug.Print "First: ", ws1.Name, wb1.Name
Debug.Print "Second: ", ws2.Name, wb2.Name
End Sub