我當前使用以下代碼來強制用戶將該文件保存爲啓用宏的工作簿。Excel VBA - 另存爲對話框窗口 - 如果按下「取消」按鈕,繼續停止代碼?
問題是,如果用戶按下「取消」按鈕,代碼將繼續。如果按下「取消」按鈕,我需要停止它。
任何幫助表示讚賞。
謝謝。
我當前使用以下代碼來強制用戶將該文件保存爲啓用宏的工作簿。Excel VBA - 另存爲對話框窗口 - 如果按下「取消」按鈕,繼續停止代碼?
問題是,如果用戶按下「取消」按鈕,代碼將繼續。如果按下「取消」按鈕,我需要停止它。
任何幫助表示讚賞。
謝謝。
這個頁面有一個很好的例子,說明你需要做什麼:
http://codevba.com/excel/dialogs.htm#SaveAs
本質上,它是這樣的:
' Application.Dialogs(xlDialogSaveAs).Show returns
' True or False depending on whether the user canceled or not
If Application.Dialogs(xlDialogSaveAs).Show Then
' User saved
Else
' User canceled
End If
以從上面和鏈接更完整的示例稍微修改它以達到您的目的:
Sub thing()
Dim strFilename As String: strFilename = "report1"
Dim strFolder As String: strFolder = "C:\temp\" 'initial directory - NOTE: Only works if file has not yet been saved!
'Dim xlfFileFormat As XlFileFormat: xlfFileFormat = XlFileFormat.xlOpenXMLWorkbook 'or replace by other XlFileFormat
Dim xlfFileFormat As XlFileFormat: xlfFileFormat = XlFileFormat.xlOpenXMLWorkbookMacroEnabled 'or replace by other XlFileFormat
Dim strPassword As String: 'strPassword = "password" 'The password with which to protect the file - if any
Dim booBackup As Boolean: 'booBackup = True '(Whether to create a backup of the file.)
Dim strWriteReservationPassword As String: 'strWriteReservationPassword = "password2" ' (The write-reservation password of the file.)
Dim booReadOnlyRecommendation As Boolean: booReadOnlyRecommendation = False '(Whether to recommend to the user that the file be opened in read-only mode.)
Dim booWorkbookSaved As Boolean ' true if file saved, false if dialog canceled
If Len(strFolder) > 0 Then ChDir strFolder
booWorkbookSaved = Application.Dialogs(xlDialogSaveAs).Show(Arg1:=strFilename, Arg2:=xlfFileFormat, Arg3:=strPassword, _
Arg4:=booBackup, Arg5:=strWriteReservationPassword, Arg6:=booReadOnlyRecommendation)
If Not booWorkbookSaved Then
Exit Sub
End If
MsgBox "Workbook saved"
End Sub
當點擊取消按鈕時,您必須捕捉事件。
Sub saveasxml()
Dim userResponce As Boolean
On Error Resume Next
userResponce = Application.Dialogs(xlDialogSaveAs).Show("Test name", 52)
On Error GoTo 0
If userResponce = False Then
MsgBox "Cancel clicked"
Exit Sub
Else
MsgBox "You saved file "
End If
End Sub
我試過了,但有兩個問題:1.它不會自動選擇啓用宏的工作簿2.如果用戶按下取消按鈕,代碼將繼續,這是我最大的問題。我一直在嘗試幾個小時,而我似乎無法讓它工作(我已經嘗試了大概六種代碼結構)。 – CC268