VBA Code hangs when Closing Workbook

I wrote some code to generate Excel Workbooks and Worksheets. All worked well on my Windows 10 development machine, but a when I ran it on the Server, running Windows 2019 Server, it hung on the Workbook.Close command, until I added the SaveChanges property like shown below.

This hung at the Close line.

Sub TestExcel()

    Dim obj As Object
    Dim wkb As Object

    Set obj = CreateObject("Excel.Application")
    Set wkb = obj.Workbooks.Open("C:\Users\[username]\Desktop\Excel\test.xlsx")

    ' Change True to False if you do not want to save
    wkb.Worksheets("Sheet1").Range("A1") = "Hello!"

    wkb.Close
    Set wkb = Nothing
    Set obj = Nothing

End Sub

 

This worked fine!

Sub TestExcel()

    Dim obj As Object
    Dim wkb As Object

    Set obj = CreateObject("Excel.Application")
    Set wkb = obj.Workbooks.Open("C:\Users\[username]\Desktop\Excel\test.xlsx")

    ' Change True to False if you do not want to save
    wkb.Worksheets("Sheet1").Range("A1") = "Hello!"

    DoEvents
    wkb.Close SaveChanges:=True
    Set wkb = Nothing
    Set obj = Nothing

End Sub

I retested with the SaveChanges option on Windows 10 and it worked fine. I added the DoEvents too, just to let the code catchup. But it was the SaveChanges that made the difference!

Happy Coding, Coder!

Add comment

Loading