3

我目前有一个宏,它可以进行数据挖掘并最终保存工作簿。我打算禁用工作簿的保存功能,并在每次需要保存工作簿时强制用户使用宏。这是我到目前为止所拥有的,但它似乎不起作用。当我这样做时,我的宏和下面描述的这个子都在一个循环中运行。每次我的宏尝试保存工作簿时,这个子都不允许它。我基本上想强制用户使用宏来保存工作簿。

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
4

2 回答 2

2

这是一个例子。将此粘贴到ThisWorkbook. 这不会让您使用SaveSaveAs。但是,您可以使用宏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在模块中。

于 2012-07-24T12:47:57.340 回答
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

在主要:

选项显式

Sub Main(bSave)

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

End Sub
于 2012-07-24T13:54:37.383 回答