Excel VBA在指定位置保存文件

时间:2016-04-15 00:45:39

标签: excel vba excel-vba

以前我问了一个关于如何使用XLDialogaveAs将Excel文件保存到指定位置的问题(适用于尚未保存的文件) - Excel VBA XLDialogSaveAs function not working。但是,我试图对已经保存在计算机中的Excel文件执行相同的操作,但改为改变位置。

我有以下代码:

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

有没有人知道我可以使用哪种excel VBA功能来更改Excel文件的保存位置,并在保存之前在对话框中显示指定的位置?谢谢!

2 个答案:

答案 0 :(得分: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

谢谢!

答案 1 :(得分:0)

我在 FileDialog(msoFileDialogOpen) 上遇到了同样的问题,我还注意到 .InitialFileName 如果不重置为 InitialFileName = "" (Excel 2013) 会在后续调用中持续存在

Application.GetOpenFileName 正确更改目标目录,但需要对返回值进行特殊处理。当 MultiSelect = False 时,它​​作为包含文件路径的字符串返回,如果取消则返回“False”。当 MultiSelect = True 时,它​​返回一个带有所选文件路径列表的变体,或者在取消时返回 Boolean = False。