2016-04-15 71 views
1

以前我問過如何使用XLDialogaveAs(它適用於尚未保存的文件)將Excel文件保存到指定位置的問題 - Excel VBA XLDialogSaveAs function not working。但是,我正在嘗試爲已經保存在計算機中的Excel文件執行相同的操作,但改爲改變位置。Excel VBA將文件保存在指定位置

下面我有以下代碼:

Option Explicit 

Sub externalRatingChangeFile() 

    'Declare the data type of the variables 
    Dim wks As Worksheet 
    Dim sFilename As String 

    'Set wks to the current active worksheet 
    Set wks = ActiveWorkbook.ActiveSheet 

    'Set the location to save the file to a variable 
    sFilename = "H:\testing file" 

    'Save as .xlsx file in the specific location stated earlier 
    'If there are errors in the code, set wks to nothing and end the process 
    On Error GoTo err_handler 
    ChDrive sFilename 
    ChDir sFilename 
    Application.Dialogs(xlDialogSaveAs).Show (sFilename & "\TestingFile - " & Format(Date, "YYYYMMDD") & ".xlsx") 

    'System to/not display alerts to notify Users that they are replacing an existing file. 
    Application.DisplayAlerts = True 

    err_handler: 
    'Set Wks to its default value 
    Set wks = Nothing 

End Sub 

有誰知道它擅長VBA功能我可以用更改Excel文件的保存位置,並在保存之前顯示在對話框中指定的位置?謝謝!

+1

請參閱SaveAs不會在Excel VBA []中包含「。」的字符串(http://stackoverflow.com/questions/36320580/saveas-wont-accpet-strings-that-c​​ontain-in-excel-vba/36320966#36320966)。 – Jeeped

+0

謝謝! @Jeeped – JJ2015

回答

1

我設法用下面的代碼解決了這個問題。

Set fdlg = Application.FileDialog(msoFileDialogSaveAs) 
With fdlg 
    .InitialFileName = sFilename 
    .Show 

'If there are errors in the code, set wks to nothing and end the process 
On Error GoTo err_handler 
    wks.SaveAs (fdlg.SelectedItems(1)) 
End With 

謝謝!

相關問題