【问题标题】:Excel VBA Saving File in Designated LocationExcel VBA 将文件保存在指定位置
【发布时间】:2021-01-12 19:38:17
【问题描述】:

之前我问了一个关于如何使用 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文件的保存位置,并在保存前在对话框中显示指定位置?谢谢!

【问题讨论】:

标签: vba excel


【解决方案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

谢谢!

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      相关资源
      最近更新 更多