Excel VBA - 为什么我的“另存为”不起作用?

时间:2014-03-10 16:00:32

标签: excel vba excel-vba

我有一个VBA脚本,这样如果一个单元格为空,那么Excel将提示保存该文件。

这可确保模板不会被更改。但是,当用户在“另存为”对话框中单击“保存”时,文件不会保存。

这是我正在使用的代码:

If Worksheets("Input").Range("E2").Value = "" Then
    Application.EnableEvents = False
    Application.GetSaveAsFilename InitialFileName:="\\ac35542\Problem Management\Action Plans\ChangeMe.xlsm", FileFilter:="Excel Macro-Enabled Workbook (*.xlsm),*.xlsm"
    Application.EnableEvents = True
    MsgBox "Please ensure fill in the Problem Reference Number, Problem Title, and Select a Contract", vbExclamation, "PR Reference & Title"
    Worksheets("Input").Select
    Range("E2").Select
End If

为什么文件没有保存?

2 个答案:

答案 0 :(得分:3)

MSDN

开始跟进
  

Application.GetSaveAsFilename显示标准的“另存为”对话框   并从用户获取文件名,而不实际保存任何文件   文件。

改为使用这个:

Dim fileSaveName
If Worksheets("Input").Range("E2").Value = "" Then
    Application.EnableEvents = False
    fileSaveName = Application.GetSaveAsFilename(InitialFileName:="\\ac35542\Problem Management\Action Plans\ChangeMe.xlsm", FileFilter:="Excel Macro-Enabled Workbook (*.xlsm),*.xlsm")
    Application.EnableEvents = True

    If fileSaveName <> "False" Then
        Application.DisplayAlerts = False
        ThisWorkbook.SaveAs (fileSaveName)
        Application.DisplayAlerts = True
    End If

    MsgBox "Please ensure fill in the Problem Reference Number, Problem Title, and Select a Contract", vbExclamation, "PR Reference & Title"
    Worksheets("Input").Select
    Range("E2").Select
End If

答案 1 :(得分:0)

我认为Dmitry Pavliv的方法很好,但我认为&#34; InitialFileName:=&#34; \ ac35542 \问题管理\行动计划\ ChangeMe.xlsm&#34;部分使它变得不那么动态。

对我来说,下面的代码完美无缺:

ExportPath = Application.GetSaveAsFilename(FILEFILTER:="Excel Files (*.xlsx), *.xlsx", Title:="")
'Basically, user will specify the path and give it a name and click on Save. It won't get saved until the next line though.
ActiveWorkbook.SaveAs (ExportPath)