我目前有一个宏进行数据挖掘并最终保存工作簿。我打算禁用工作簿的保存功能,并强制用户每次需要保存工作簿时使用宏。这是我到目前为止所做的,但似乎没有用。当我这样做时,我的宏和下面描述的这个子都在循环中运行。每次我的宏试图保存工作簿时,这个子都不允许它。我基本上想强制用户使用宏来保存工作簿。
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
答案 0 :(得分:2)
这是一个例子。将其粘贴到ThisWorkbook
中。这不允许您使用Save
或SaveAs
。但是,您可以使用宏SaveThisFile
来保存工作簿。请根据您的需要进行修改。
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
注意:如果您的保存宏位于模块中,请从Dim SaveByCode As Boolean
移除此ThisWorkbook
并将Public SaveByCode As Boolean
放入模块中。
答案 1 :(得分:0)
替代方案,这个怎么样(我起初误解了这个问题,但也想尝试一下,因为它很有趣):
在thisworkbook模块中声明公共布尔值(例外):
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
在Main:
选项明确
Sub Main(bSave)
If bSave = True Then
ThisWorkbook.SaveAs Filename:="U:\Book1.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
MsgBox "Main method called"
End If
End Sub