简体   繁体   中英

Runtime error 1004 document not saved with Vba Excel 2016

I am getting a Runtime error 1004 document not saved using vba when I want to save an Excel workbook in my folder on desktop. Here are the details of my code:

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

I think you are missing an 'End If' at the bottom of your code. The 'If fName = False Then...' part. Try the following

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

fName is a String , therefore you can't compare it with False , but with "False" .

Try replacing the last section of your code with the lines below:

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

Note : using FileFormat:=51 , means xlOpenXMLWorkbook , an .xlsx format (without MACROs).

However since you want to use the SaveAs command with ThisWorkbook , which contains this code, you will get a prompt screen that asks if you want to save it as .xslx , which means all your code will be lost.

You can select FileFormat:=52 , means xlOpenXMLWorkbookMacroEnabled , an .xlsm format ( with MACROs ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM