我使用下面的代码强制用户保存在xlsm中。问题是此代码在另存为事件时正常工作,但在用户单击关闭按钮时不起作用。当关闭关闭按钮时,Excel会显示一个对话框,提供包含各种文件类型的保存选项。考虑到用户单击关闭按钮,如何获得下面代码的相同行为? 提前谢谢。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim txtFileName As String
'1. Check of Save As was used.
If SaveAsUI = True Then
Cancel = True
'2. Call up your own dialog box. Cancel out if user Cancels in the dialog box.
txtFileName = Application.GetSaveAsFilename(, "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm", , "Save As XLSM file")
If txtFileName = "False" Then
MsgBox "Cancelled.", vbOKOnly
Cancel = True
Exit Sub
End If
'3. Save the file.
Application.EnableEvents = False
ThisWorkbook.SaveAs Filename:=txtFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Application.EnableEvents = True
End If
End Sub
答案 0 :(得分:1)
Workbook_BeforeClose
事件中的此代码如何解决该问题。我刚刚测试过它并且有效。
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If ThisWorkbook.FileFormat <> 52 Then '52 is enum for xlOpenXMLWorkbookMacroEnabled
txtFileName = Application.GetSaveAsFilename(, "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm", , "Save As XLSM file")
If txtFileName = "False" Then
MsgBox "Cancelled.", vbOKOnly
Cancel = True
Exit Sub
End If
Application.EnableEvents = False
ThisWorkbook.SaveAs Filename:=txtFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Application.EnableEvents = True
End If
End Sub
答案 1 :(得分:0)
@ Scott-Holtzman,你的想法救了我。考虑到我的具体问题,我必须做出一些改变。当fileformat已经是xlsm时,excel会显示一个内置的标准消息框,提供保存选项。此时,用户可以选择其他文件格式。所以我省略了差异条款并且包含了一个msgbox以允许用户完成退出过程。非常感谢您的帮助!!这是我的最终版本:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim msg As String
Dim ireply As Integer
If Not Me.Saved Then
msg = "Do you want to Save this book? "
ireply = MsgBox(msg, vbQuestion + vbYesNoCancel)
Select Case ireply
Case vbNo
Me.Saved = True
Exit Sub
Case vbCancel
Cancel = True
Exit Sub
End Select
End If
txtFileName = Application.GetSaveAsFilename(, "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm", , "Save As XLSM file")
If txtFileName = "False" Then
MsgBox "Cancelled.", vbOKOnly
Cancel = True
Exit Sub
End If
Application.EnableEvents = False
ThisWorkbook.SaveAs Filename:=txtFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Application.EnableEvents = True
End Sub