不需要的循环Workbook_AfterSave

我是macros的新手,我在VBA上使用了Workbook_AfterSave函数。 由于某种原因,它保持循环保存function。 我不知道如何摆脱这个。 它永远保存的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 

添加一个静态variables来防止recursion:

 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 

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

下面的代码获取标志的当前状态; 将其设置为False ; 运行您的原始代码; 然后重置error handling程序中的标志。 如果在保存过程中出现IO错误, EnableEventsEnableEvents设置error handling程序,并将重置置于error handling程序中,以确保将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