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)
I think your problem is that you are opening Workbook B. You state, if you close and re-open it then it works.
Therefore, any changes you have made to Workbook B will be lost as it will re-open the original workbook. (Auto Save does not actually save the workbook, it saves a separate copy.)
You need instead to check if the workbook is already open and only re-open it if it is not currently open.
(Very rough code)
Sub test()
Dim wb As Workbook
For Each wb In ThisWorkbook.Application.Workbooks
If wb.Path & "\" & wb.Name = "U:\workbookB.xlsx" Then Exit For
Next
If wb.Path & "\" & wb.Name <> "U:\workbookB.xlsx" Then Set wb = ThisWorkbook.Application.Workbooks.Open("U:\workbookB.xlsx")
wb.Worksheets("ED").Range("Z1").Value = "TEST"
End Sub
But (as others have said) you should really check that there are no other instances of Excel running and account for them also.