运行时错误1004文档未使用Vba Excel 2016保存

时间:2016-11-30 08:31:56

标签: excel vba

当我想在桌面上的文件夹中保存Excel工作簿时,我正在使用vba获得Runtime error 1004 document not saved。以下是我的代码的详细信息:

Private Sub Save_Click()

'Popup the Window "Save As"

Application.DisplayAlerts = False


MsgBox "Do not change the default file name proposed on the next step please !"

Dim fName As Variant

Dim DName As String  ' Variable storing name of excel workbook which has to be saved

DName = UserForm.CustomerApplication.Value & " - " & UserForm.L2GType.Value

& " - " & UserForm.Title.Value & " - " & UserForm.Country.Value & "(" & 

Year(Date) & ")"

fName = Application.GetSaveAsFilename(InitialFileName:=DName, _

FileFilter:="Excel Files (*.XLSX), *.XLSX", Title:="Save As")

If fName = False Then

 Exit Sub

ActiveWorkbook.SaveAs filename:=fName, FileFormat:=51

ActiveWorkbook.Close

End Sub

2 个答案:

答案 0 :(得分:0)

我认为你错过了代码底部的'End If'。 'if fName = False Then ...'部分。请尝试以下

Private Sub Save_Click()

'Popup the Window "Save As"

Application.DisplayAlerts = False


MsgBox "Do not change the default file name proposed on the next step please !"

Dim fName As Variant

Dim DName As String  ' Variable storing name of excel workbook which has to be saved

DName = UserForm.CustomerApplication.Value & " - " & UserForm.L2GType.Value

& " - " & UserForm.Title.Value & " - " & UserForm.Country.Value & "(" & 

Year(Date) & ")"

fName = Application.GetSaveAsFilename(InitialFileName:=DName, _

FileFilter:="Excel Files (*.XLSX), *.XLSX", Title:="Save As")

If fName = False Then

 Exit Sub

End If

ActiveWorkbook.SaveAs filename:=fName, FileFormat:=51

ActiveWorkbook.Close

End Sub

答案 1 :(得分:0)

fNameString,因此您无法将其与False进行比较,但与"False"进行比较。

尝试使用以下行替换代码的最后一部分:

fName = Application.GetSaveAsFilename(InitialFileName:=DName, _
        fileFilter:="Excel Files (*.XLSX), *.XLSX", Title:="Save As")

If fName <> "False" Then
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=fName, FileFormat:=51
Else
    MsgBox "No File was selected !"
    Exit Sub
End If

Application.DisplayAlerts = True

注意:使用FileFormat:=51,表示xlOpenXMLWorkbook,.xlsx格式(不含MACRO)。

但是,因为您要使用包含此代码的SaveAs命令ThisWorkbook,您将看到一个提示屏,询问您是否要将其另存为.xslx,这意味着您的所有代码都将丢失。

您可以选择FileFormat:=52,表示xlOpenXMLWorkbookMacroEnabled,.xlsm格式(带有MACRO 的)。