如何禁用保存function

我目前有一个macros来做数据挖掘并最终保存工作簿。 我打算禁用工作簿的保存function,并强制用户每次需要保存工作簿时使用macros。 这是我迄今为止,但似乎并没有工作。 当我这样做的时候,我的macros和下面介绍的这个sub都是循环运行的。 每次我的macros试图保存工作簿,这个子不允许它。 我基本上想强制用户使用macros来保存工作簿。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Dim NoSave NoSave = MsgBox("Changes have to be submitted before the workbook can be saved, Proceed and submit ?", vbYesNo, "Continue?") If NoSave = vbNo Then Cancel = True Else Main End If End Sub 

这是一个例子。 将其粘贴到ThisWorkbook 。 这不会让你使用SaveSaveAs 。 但是,您可以使用macrosSaveThisFile保存该工作簿。 请修改它以适应您的需求。

 Option Explicit Dim SaveByCode As Boolean Const msg As String = "Please use the macro to save the file" Private Sub Workbook_BeforeClose(Cancel As Boolean) If Me.Saved = False And SaveByCode = False Then MsgBox msg, vbExclamation, "Unable to save" Cancel = True End If End Sub Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Application.EnableEvents = False If SaveByCode = True Then SaveThisFile Else MsgBox msg, vbExclamation, "Unable to save" Cancel = True End If Application.EnableEvents = True End Sub '~~> Your macro to save the file Sub SaveThisFile() SaveByCode = True ThisWorkbook.Save End Sub 

注意 :如果您的保存macros在模块中,然后从ThisWorkbook删除此Dim SaveByCode As Boolean并将Public SaveByCode As Boolean在模块中。

另外,这个怎么样(我刚开始误解了这个问题,也想试一试,因为它很有趣):
在这个工作簿模块中声明公共布尔(例外):

 Option Explicit Public bSave As Boolean 

在BeforeSave事件中:

 Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Dim sNoSave As String If bSave = True Then bSave = False Exit Sub End If sNoSave = MsgBox("Changes have to be submitted before the workbook can be saved, Proceed and submit ?", vbYesNo, "Continue?") If sNoSave = vbNo Then bSave = False Cancel = True Exit Sub Else bSave = True Call Main(bSave) End If End Sub 

主要:

选项显式

 Sub Main(bSave) If bSave = True Then ThisWorkbook.SaveAs Filename:="U:\Book1.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled MsgBox "Main method called" End If End Sub