【问题标题】:How to disable the save function如何禁用保存功能
【发布时间】:2012-07-24 21:54:37
【问题描述】:

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

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

【问题讨论】:

  • 你能不能只从宏中取出保存部分,然后在 BeforeSave 事件上运行宏?
  • 成功了!好主意,谢谢

标签: vba excel


【解决方案1】:

这是一个例子。将此粘贴到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

注意:如果您的 Save 宏位于模块中,则从 ThisWorkbook 中删除此 Dim SaveByCode As Boolean 并将 Public SaveByCode As Boolean 放入模块中。

【讨论】:

    【解决方案2】:

    另类,这个怎么样(我一开始误解了这个问题,但也想尝试一下,因为它很有趣):
    在 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
    

    【讨论】:

      猜你喜欢
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      相关资源
      最近更新 更多