I have code in workbook A that opens and does stuff to workbook B. Code runs fine when workbook A and B are the only excel files open (or if workbook A is the only file open). H
There is a subtle bug (I hesitate to call it that, but that's what it looks like) you need to watch out for.
If the workbook you're trying to open via code is already open then occasionally you will see some unexpected behavior (such as the return value from Workbooks.Open()
being assigned to ThisWorkbook
instead of the file you expect).
For example the code below runs in "Tester.xlsm" and is opening "EmptyTest.xlsx", but if that file is already open, the Workbooks.Open
call fails to correctly assign the wb
variable, and it ends up pointing at "Tester.xlsm". That can cause problems.
To replicate,
Test code:
Sub Tester()
Dim wb As Workbook
'with "EmptyTest" already open
Set wb = Workbooks.Open("C:\Tester\EmptyTest.xlsx")
Debug.Print wb.Name '>> Tester.xlsm - oops!
'close"EmptyTest" before proceeding
Workbooks("EmptyTest.xlsx").Close False
'with "EmptyTest" closed
Set wb = Workbooks.Open("C:\Tester\EmptyTest.xlsx")
Debug.Print wb.Name '>>EmptyTest.xlsx - OK
End Sub
Totally reproducible on my system (win10/Office 365)