Excel VBA自动化版本控制创建神秘的节约循环 - 来源?

时间:2014-12-10 06:07:12

标签: excel vba controls version before-save

以下子例程用于Excel工作簿中的版本控制工作表,以在创建新的带时间戳的.xmls文件之前捕获用户名,保存时间和更改注释,以保留文档的过去迭代次数。结果是成功的,但它创建了一个神秘的保存循环,它不断要求用户输入而不是保存或退出。如果

有什么想法吗?

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 个答案:

答案 0 :(得分:1)

鉴于此代码位于Workbook_BeforeSave事件中,已启动保存操作。

因此,您不需要此事件代码中的ActiveWorkbook.SaveAs行。这可能导致递归循环(即重新触发Workbook_BeforeSave),尽管我还没有能够在发布之前对其进行测试。

在启动保存操作之前,您是否可以对Save / SaveAs进行测试,还是考虑将此代码(或大部分代码?)移动到标准模块中?