Can having multiple instances of Excel open cause VBA issues?

后端 未结 2 858
我在风中等你
我在风中等你 2021-01-25 19:47

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

2条回答
  •  不要未来只要你来
    2021-01-25 20:21

    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,

    • open Excel
    • open "EmptyTest.xlsx"
    • open "Tester.xlsm"
    • run "Tester" sub

    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)

提交回复
热议问题