Search code examples
excelvba

VBA: Workbooks.Save & Close not saving


I have the following code that is working but the line .close closes the WB without saving:

Option Explicit
Public Function updateStatus(fpath As String, fname As String, num As String)

Dim wk As String, yr As String
Dim owb As Workbook
Dim trow As Variant

With Application
    .DisplayAlerts = False
    .ScreenUpdating = False
    .EnableEvents = False
End With

Set owb = Application.Workbooks.Open(fpath & fname)

trow = owb.Sheets(1).Range("Change" & num).Row
owb.Sheets(1).Cells(trow, 5).value = "Test"

With owb
    .Save
    .Close SaveChanges:=True 'This line doesn't seem to work
End With

With Application
    .DisplayAlerts = True
    .ScreenUpdating = True
    .EnableEvents = True
End With

End Function

If I remove the line, the WB stays open and I see the change. If I add the line, and open the specific file, I see no change.


Solution

  • As mentioned in the comments, the code looks ok, you probably have some Data Protection enabled on your Excel, which does not allow the saving. Try to make a minimal example like this:

    Option Explicit
    
    Public Sub TestMe()
    
        Dim owb As Workbook
    
        Set owb = Application.Workbooks.Open("C:\Users\vityata\Desktop\Testing.xlsx")
        owb.Save
        owb.Close
    
    End Sub
    

    Then debug with F8 and see the message that you got, once you go pass by owb.Save.

    Just that you know:

    .Save
    .Close SaveChanges:=True
    

    With the .Save line you make the SaveChanges:=True part useless. And vice versa.