【问题标题】:Prompting a macro on close of workbook, but kill the closing if user press "No"在关闭工作簿时提示宏,但如果用户按“否”则终止关闭
【发布时间】:2016-03-03 14:53:44
【问题描述】:

我正在尝试在关闭工作簿时执行宏。

宏运行良好,但问题在于关闭功能。我希望在关闭工作簿时提示用户说“是”或“否”。如果用户按“是”,工作簿应保存为 xlsm 并关闭。

如果用户按“否”,则应执行宏,以便将用户发送到工作表“Projektinformation”并且不应关闭工作簿。

这是我的代码,有什么想法吗?

Sub Auto_Close()
Dim OutPut As Integer
OutPut = MsgBox("Projektinformation ifylld?", vbYesNo, "Projektinformation.")
If OutPut = 6 Then
'Output = 6(Yes)
ThisWorkbook.SaveAs FileFormat:=xlOpenXMLWorkbookMacroEnabled
Else
'Output = 7(No)
Sheets("Projektinformation").Select
End If
End Sub

【问题讨论】:

  • 尝试使用If OutPut = vbYes Then。 ...但是什么在这里不起作用?是有错误,还是什么都没有发生?有什么问题?
  • 你是从 Workbook_BeforeClose 事件中调用这个函数吗?
  • 您好,我正在从工作簿关闭事件中调用该函数。问题是即使您按“否”它也只是关闭工作簿,而不是不关闭它并转到工作表“Projektinformation”。

标签: vba excel macros


【解决方案1】:

根据您的评论,我推断您的代码在 Workbook_BeforeClose 端看起来像这样:

Private Sub Workbook_BeforeClose(Cancel as Boolean)
    Call Auto_Close()
End Sub

问题是代码完全按照您的要求执行!它运行您的 Auto_Close 子例程(在工作簿关闭之前),然后继续关闭工作簿!

为了实现您想要实现的目标,您必须将传递给 Workbook_BeforeClose 子的Cancel 参数更改为True。当Cancel = True 工作簿将取消关闭事件,否则将照常继续。我会通过引用将Cancel 传递到您的子程序中,并根据您的用户单击的内容更改标志,或者使Auto_Close() 成为一个返回布尔值的函数,指示是否继续关闭工作簿。

示例

Private Sub Workbook_BeforeClose(Cancel as Boolean)
    If SomeCondition = True Then
        Cancel = True  '<-- Workbook will stay open
    Else
        Cancel = False  '<-- Workbook will close as usual
    End If
End Sub

【讨论】:

    【解决方案2】:

    您将代码放在错误的位置。它应该在 ThisWorkbook 代码表的 Workbook.BeforeClose Event 事件宏中。

    Private Sub Workbook_BeforeClose(Cancel As Boolean)
        Dim OutPut As Integer
        OutPut = MsgBox("Projektinformation ifylld?", vbYesNo, "Projektinformation.")
            If OutPut = 6 Then
            'Output = 6(Yes)
            ThisWorkbook.SaveAs FileFormat:=xlOpenXMLWorkbookMacroEnabled
        Else
            'Output = 7(No)
            Cancel = True
            Sheets("Projektinformation").Select
        End If
    End Sub
    

    注意Cancel = True。这告诉 Excel 停止关闭操作并继续处理指令。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多