标签:VBA,工作簿事件
使用下面的代码,可以强迫用户在保存Excel工作簿时将其保存为.xlsm文件。
在VBE中,双击ThisWorkbook代码模块,在代码窗口输入下面的代码:
代码语言:javascript复制Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim strWorkbookName As String
Dim FileFormatValue As Integer
On Error GoTo Quit
Application.EnableEvents = False
If SaveAsUI = True Then
strWorkbookName = Application.GetSaveAsFilename( _
fileFilter:="Excel启用宏工作簿(*.xlsm), *.xlsm")
Cancel = True
If strWorkbookName <> "False" Then
Select Case LCase(Right(strWorkbookName, Len(strWorkbookName) - InStrRev(strWorkbookName, ".", , 1)))
Case "xlsm": FileFormatValue = 52
End Select
ActiveWorkbook.SaveAs strWorkbookName
End If
End If
Quit:
If Err.Number > 0 Then
If Err.Number <> 1004 Then
MsgBox "Error: " & Err.Number & Err.Description & vbCrLf & vbCrLf & vbCrLf & _
"Title", vbCritical
End If
End If
Application.EnableEvents = True
End Sub
这样,在保存Excel工作簿时,在“另存为”对话框的“保存类型”下拉列表中,只有一个选项即“Excel启用宏工作簿(*.xlsm)”,如下图1所示,从而让用户只能将工作簿保存为.xlsm文件。