2017-10-10 114 views

回答

0

這個頁面有一個很好的例子,說明你需要做什麼:

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 
+0

我試過了,但有兩個問題:1.它不會自動選擇啓用宏的工作簿2.如果用戶按下取消按鈕,代碼將繼續,這是我最大的問題。我一直在嘗試幾個小時,而我似乎無法讓它工作(我已經嘗試了大概六種代碼結構)。 – CC268

0

當點擊取消按鈕時,您必須捕捉事件。

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 
+0

感謝這個作品 - 唯一的事情是我想當前的文件名稱顯示在另存爲框,而不是「測試名稱」 - 有沒有辦法做到這一點? – CC268

+0

將當前文件名稱放入一個變量中,並用變量替換「test name」。 – mooseman

相關問題