不需要的循环工作簿_AfterSave

时间:2017-09-29 19:10:44

标签: excel vba excel-vba

我是宏的新手,我在VBA上使用了Workbook_AfterSave函数。由于某种原因,它保持循环保存功能。我不知道怎么摆脱这个。它永远保存excel文件并最终崩溃。这是代码。

Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:= _
        "F:\Ten Year Load Forecasts 2017-2026.xlsm", _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub

2 个答案:

答案 0 :(得分:1)

添加静态变量以防止递归:

Private Sub Workbook_AfterSave(ByVal Success As Boolean)
  Static bHere as Boolean
  If bHere then Exit Sub

  bHere = True
  Application.DisplayAlerts = False
  ActiveWorkbook.SaveAs Filename:= _
        "F:\Ten Year Load Forecasts 2017-2026.xlsm", _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
  Application.DisplayAlerts = True
  bHere = False
End Sub

答案 1 :(得分:0)

您可以将Application对象的EnableEvents属性设置为False,以防止在Workbook_AfterSave事件中保存时再次触发事件。

以下代码获取标志的当前状态;将其设置为False;运行您的原始代码;然后重置错误处理程序中的标志。如果在保存期间出现IO错误,则应在此处设置错误处理程序,并将重置放入错误处理程序,以确保将EnableEvents设置恢复为原始值。示例代码:

Option Explicit

Private Sub Workbook_AfterSave(ByVal Success As Boolean)

    Dim blnSetting As Boolean

    ' IO operations should have an event handler
    On Error GoTo CleanExit

    ' remember existing setting and set flag to False
    blnSetting = Application.EnableEvents
    Application.EnableEvents = False

    ' your original code
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:= _
        "F:\Ten Year Load Forecasts 2017-2026.xlsm", _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

CleanExit:

    If Err.Number <> 0 Then
        ' handle error
        Debug.Print Err.Description
    End If

    ' reset the Application flag here
    Application.EnableEvents = blnSetting

End Sub