Excel VBA automating Version Control creates Mysterious Saving Loop - Source?

145 Views Asked by At

The following subroutine is used for a Version Control sheet in an Excel workbook to capture a users name, time of saving and change comments before creating a new timestamped .xmls file to preserve past iterations of the document. The result is successful, however it creates a mysterious saving loop where it constantly asks for the user for input instead of saving or exiting. If

Any thoughts?

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim LastRow As Long
Dim ActBook As Workbook
Dim NewFile As String
Dim LongName As String

Application.ScreenUpdating = False
LongName = ThisWorkbook.FullName
NewFile = (Worksheets("Estimate Sheet").Range("B2") & Format(Now(), "yyyymmddhhmmss") & ".xlsm")

'Change Confirmation Dialogue
If MsgBox("Were changes made to this document?", vbYesNo, "Change Log") = vbYes Then

    'Adds change log
    With Me.Sheets("Version Control")
       LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
       .Cells(LastRow, 1) = Application.UserName
       .Cells(LastRow, 2) = Now
       .Cells(LastRow, 4) = NewFile
       .Cells(LastRow, 5) = InputBox("Please list changes below:", "Comments")
    End With

    'Maps Save to SaveAs by checking if file of current name exists
    If NewFile <> "" And NewFile <> "False" Then
        ActiveWorkbook.SaveAs Filename:=NewFile, _
        FileFormat:=52, _
        Password:="", _
        WriteResPassword:="", _
        ReadOnlyRecommended:=False, _
        CreateBackup:=False

        SetAttr LongName, vbNormal
        Set ActBook = ActiveWorkbook
        Workbooks.Open NewFile
    End If

End If

Application.ScreenUpdating = True
End Sub
1

There are 1 best solutions below

0
On

Given this code is in the Workbook_BeforeSave event, the Save operation has already been initiated.

You therefore don't need the ActiveWorkbook.SaveAs line within this event code. This is likely causing the recursive loop (i.e. re-triggering Workbook_BeforeSave) although I haven't been able to test this before posting.

Can you do the test for Save/SaveAs before initiating the save operation or consider moving this code (or most of it?) into a standard module?