在工作簿closures时提示macros,但如果用户按“否”

我正试图在工作簿closures时执行一个macros。

macros完美的工作,但问题是closuresfunction。 我想让用户在closures工作簿时提示“是”或“否”。 如果用户按下“是”,工作簿应该保存为xlsm并closures。

如果用户按下“否​​”,则应该执行macros以使用户被发送到“工程图信息”表并且工作簿不应该被closures。

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

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 

你把代码放在错误的地方。 它应该在ThisWorkbook代码表中的Workbook.BeforeClose事件事件macros中。

 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停止closures操作并继续处理指令。

从你的评论中,我推断你的代码在Workbook_BeforeClose方面看起来像这样:

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

问题是代码完全是你问的! 它运行您的Auto_Close子例程(在工作簿closures之前),然后继续closures工作簿!

为了实现您正在尝试实现的目标,必须将传递到Workbook_BeforeClose子项中的Cancel参数更改为True 。 当Cancel = True ,工作簿将取消closures事件,否则将继续照常。 我要么通过引用传递Cancel到您的子和更改标志取决于您的用户点击或使Auto_Close()函数返回一个布尔值,指示是否继续closures工作簿。

 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