首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Excel VBA在指定位置保存文件

Excel VBA在指定位置保存文件
EN

Stack Overflow用户
提问于 2016-04-14 16:45:38
回答 2查看 707关注 0票数 1

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

我有以下代码:

代码语言:javascript
运行
AI代码解释
复制
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文件的保存位置,并在保存之前在对话框中显示指定的位置吗?谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-04-15 02:45:15

我设法用下面的代码解决了这个问题。

代码语言:javascript
运行
AI代码解释
复制
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
EN

Stack Overflow用户

发布于 2021-01-12 03:38:17

我对FileDialog(msoFileDialogOpen)也有同样的问题,我还注意到,如果没有重置为InitialFileName = "“(Excel2013),.InitialFileName会在随后的调用中持久化。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36636460

复制
相关文章

相似问题

领券
社区富文本编辑器全新改版!诚邀体验~
全新交互,全新视觉,新增快捷键、悬浮工具栏、高亮块等功能并同时优化现有功能,全面提升创作效率和体验
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文