Can having multiple instances of Excel open cause VBA issues?

后端 未结 2 860
我在风中等你
我在风中等你 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:22

    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.

提交回复
热议问题