1

以下子例程用于 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
4

1 回答 1

1

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

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

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

于 2014-12-10T08:45:54.577 回答