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).
Related
I have working save as line for my VBA script in excel before and the file is saving to a network folder. Before, the server has name, now we access the server folders using an IP (192.168.20.212), hence I changed the address in code using the IP.
Now, the problem is that the file naming I set is not working. When the dialog box appears, the filename is empty and the user needs to manually enter the filename. However, if I put a server name or use local address, the file naming is working. I have no choice but use the IP to save file.
The following is the line for the file naming;
filenme = "PENDING CLAIMS_" + szNextDatereformat
And the following is the line for saving the file before;
Dim sFileSaveName As String
sFileSaveName = Application.GetSaveAsFilename _
(InitialFileName:="\\SERVERNAME\excel_files\" & filenme & sTargetFile, _
FileFilter:="Excel Files (*.xlsx), *.xlsx")
If sFileSaveName <> "False" Then
'-- Savethe file --
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=sFileSaveName, _
FileFormat:=51
Application.DisplayAlerts = True
Else
'-- Popup message --
MsgBox "Template not saved!", vbExclamation, "Warning"
End If
The new one should be;
Dim sFileSaveName As String
sFileSaveName = Application.GetSaveAsFilename _
(InitialFileName:="\\192.168.20.212\excel_files\" & filenme & sTargetFile, _
FileFilter:="Excel Files (*.xlsx), *.xlsx")
If sFileSaveName <> "False" Then
'-- Savethe file --
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=sFileSaveName, _
FileFormat:=51
Application.DisplayAlerts = True
Else
'-- Popup message --
MsgBox "Template not saved!", vbExclamation, "Warning"
End If
something like this works for me:
Dim txtFileName As String
Dim finalPath As String
finalPath = "\\10.10.10.11\PUBLIC\SOMETHING\"
finalPath = finalPath & "myWorkbookName.xlsx"
txtFileName = Application.GetSaveAsFilename(finalPath, "Excel (*.xlsx), *.xlsx", , "Excel network save")
If txtFileName = "False" Then
MsgBox ("We could not save Excel.")
Exit Sub
End If
From my observations problems are when:
- computer does not have access to network share,
- workbook name that is proposed does not match "rules" of saving, e. g. is too long or has same strange characters.
You should try to:
1) check if computer has access to this network drive
2) check if IP address is correct
3) check if file name is correct.
Thanks to Mikisz with a little modification of his code, the below has worked with me;
Dim txtFileName As String
Dim finalPath As String
finalPath = "\\192.168.20.212\networkfolder\"
finalPath = finalPath & filenme & ".xlsx"
txtFileName = Application.GetSaveAsFilename(finalPath, "Excel (*.xlsx), *.xlsx", , "Template saved on the Network")
If txtFileName <> "False" Then
'-- Savethe file --
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=txtFileName, _
FileFormat:=51
Application.DisplayAlerts = True
Else
'-- Popup message --
MsgBox "Canceled saving the template!", vbExclamation, "Warning"
'Exit Sub
End If
Simple macro to SaveAs a basic excel file to SharePoint and then do a bunch of other stuff. The macro works perfectly when the user has an access to the specified folder FLUX PL.
ActiveWorkbook.SaveAs Filename:="https://xxxxcorp.sharepoint.com/sites/CEEControlling/Shared%20Documents/Reporting/FLUX%20Analysis/FLUX%20PL/FLUX%20analysis%20PL%20" & Date & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
If the user doesn't have access (so he does not see the file), it half-saves in place of the original file so it is broken and I have to go to the previous version.
I tried include code to check if I have access/the folder exists in SharePoint, but it gives me
Run-time error '52': Bad file name or number.
mypath = "https://xxxxcorp.sharepoint.com/sites/CEEControlling/Shared%20Documents/Reporting/FLUX%20Analysis/FLUX%20PL"
mypath = Replace(Replace(mypath, "https:", ""), "/", "\")
mypath = Replace(mypath, Split(mypath, "\")(2), Split(mypath, "\")(2) & "#SSL")
If Dir(mypath, vbDirectory) = "" Then
MsgBox ("Doesnt exist!")
Else:
MsgBox ("Exists!")
End If
I also thought about On Error Goto [label] but by the time it gives me error the file is already renamed (and the original one broken).
I would be grateful for any help.
If anyone would need it in the future, I got it working. I try to save it and if it gives me error I use On Error GoTo and open SaveAs Dialog.
On Error GoTo savior
ActiveWorkbook.SaveAs Filename:= "https://xxxxcorp.sharepoint.com/sites/CEEControlling/Shared%20Documents/Reporting/FLUX%20Analysis/FLUX%20" & Range("H2").Value & "/FLUX%20analysis%20" & Range("H2").Value & "%20" & Date & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Application.DisplayAlerts = False
On Error Goto 0
GoTo rest
savior:
MsgBox ("You do NOT have access to the default folder on Teams:" & vbNewLine & "Controlling CEE >> Reporting >> Files >> FLUX Analysis >> FLUX " & Range("H2").Value & vbNewLine & vbNewLine & "Select different location for the new trimmed file!")
Filename = "FLUX analysis " & Range("H2") & " " & Date
varResult = Application.GetSaveAsFilename(FileFilter:= _
"Excel Files (*.xlsx), *.xlsx", Title:="Select File Location", _
InitialFileName:=Filename)
If varResult <> False Then
ActiveWorkbook.SaveAs Filename:=varResult, _
FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = False
End If
On Error Goto 0
GoTo rest
rest:
I'm trying to get my Save As path to open up as the same folder the original document was opened from. For example, if the file was in public/forms I want it prompt save as in public/forms. Currently it is defaulting to mypc/documents. This is my code:
Dim IntialName As String
Dim fileSaveName As Variant
InitialName = Range("d1") & "_" & "#" & Range("l1") & "-" & "RW" &
Range("q1")
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
filefilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
If fileSaveName = False Then
Exit Sub
End If
If Not fileSaveName = False Then
ActiveWorkbook.SaveAs Filename:=Application.ThisWorkbook.Path &
fileSaveName
Else
On Error Resume Next
If Err.Number = 1004 Then
On Error GoTo 0
Else
ActiveWorkbook.SaveAs Filename:=Application.ThisWorkbook.Path &
fileSaveName
End If
End If
Thanks!
The code below will save to the file name you've used. I've made it reference the ranges on Sheet1 rather than whichever sheet is currently active when your execute the code. Change the sheet name as required.
It will also open to the folder that the file containing the code is in (ThisWorkbook).
Change this to ActiveWorkbook or any other path as required.
Sub Test1()
Dim InitialName As String
With ThisWorkbook.Worksheets("Sheet1")
InitialName = .Range("D1") & "_" & "#" & .Range("L1") & "-" & "RW" & .Range("Q1")
InitialName = ThisWorkbook.Path & "\" & InitialName
End With
InitialName = Application.GetSaveAsFilename(InitialName, "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
If Not InitialName = "False" Then
ThisWorkbook.SaveAs InitialName
End If
End Sub
Assuming that InitialName contains only a filename without path, change the parameter InitialFileName to
Application.GetSaveAsFilename(InitialFileName:= thisWorkbook.Path & "\" & InitialName, ...
I think this is what you want:
File filter can take a full folder in the initial path, so you can assign it based on the workbooks path
Dim InitialName As String
Dim fileSaveName As Variant
Dim FilePath, FileOnly, PathOnly As String
FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
InitialName = PathOnly & "\" & Range("d1") & "_" & "#" & Range("l1") & "-" & "RW" &
Range("q1")
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
filefilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
If fileSaveName = False Then
Exit Sub
End If
If Not fileSaveName = False Then
ActiveWorkbook.SaveAs Filename:=Application.ThisWorkbook.Path & fileSaveName
Else
On Error Resume Next
If Err.Number = 1004 Then
On Error GoTo 0
Else
ActiveWorkbook.SaveAs Filename:=Application.ThisWorkbook.Path & fileSaveName
End If
End If
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
filefilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
I have a xslm file. I want to save the file as xlsx and email.
I am able to SaveCopyAs it as xls file. If I try to save it as xlsx, it does get saved but when I open it, it gives an error.
ActiveWorkbook.SaveCopyAs Filename:=ActiveWorkbook.Path & "\MyFileName - " & Format(Date, "mm-dd-yyyy") & ".xlsx"
Excel cannot open the file '...path\MyFileName.xlsx' because the file format or file extension is not valid. Verify that file has not been corrupted and that file extension matches the format of the file
SaveCopyAs does not change the file-type.
You simply cannot save a .xlsm as .xlsx via SaveCopyAs.
EDIT
a workaround is to save a copy which then is changed in type while the old copy will be deleted like:
Dim wb As Workbook, pstr As String
pstr = ActiveWorkbook.Path & "\MyFileName - " & Format(Date, "mm-dd-yyyy") & ".xlsm"
ActiveWorkbook.SaveCopyAs Filename:=y
Set wb = Workbooks.Open(pstr)
wb.SaveAs Left(pstr, Len(pstr) - 1) & "x", 52
wb.Close False
Kill pstr
Try this:
Sub SaveAsXLSX()
ThisWorkbook.Save 'Optional
Application.DisplayAlerts = False
ThisWorkbook.SaveAs ActiveWorkbook.Path & "\MyFileName - " & Format(Date, "mm-dd-yyyy"), 51 '51 = xlsx
Application.DisplayAlerts = True
ThisWorkbook.Close 'Optional
End Sub
All you need to do is SaveAs and change the file format to 51 (xlsx)
If you want to "Save a copy" - SaveAs does practically the same thing - the difference being your currently open file becomes the saved file, but you can simply reopen the old one if you wish and nothing changes.
What you actually want to do is SaveAs a different file type, so use SaveAs.
I This is more readable. TESTED.
Sub SaveXlsmAsXlsx()
Dim wb As Workbook, Filenamepath As String, Filenameext As String, Filenameonly As String, Filepathonly As String
Application.DisplayAlerts = False
Filenamepath = ActiveWorkbook.FullName
Filenameext = ActiveWorkbook.Name
Filenameonly = Replace(Filenameext, ".xlsm", "")
Filepathonly = Replace(Filenamepath, ".xlsm", "")
Set wb = Workbooks.Open(Filenamepath)
'51 = xlsx
wb.SaveAs Filename:=Filepathonly & "_" & Format(Date, "mm-dd-yyyy"), FileFormat:=51
wb.Close True
'Kill- Best not to kill anyone, you might be sorry
ThisWorkbook.Close SaveChanges:=True
Application.DisplayAlerts = True
End Sub
This code add to any module:
Public Sub XLSMtoXLSX(FaylAdi As String)
Dim FullPath As String
Dim wb As Workbook
MsgBox "YOU WILL GET A WARNING AFTER COMPLETED, PLEASE WAIT"
ThisWorkbook.Save
On Error GoTo XETA
'You can change the name of the folder path below
FullPath = "C:\kohne sistem\Excel\VBA\Anbar\temp\" & FaylAdi & ".xlsm"
ThisWorkbook.SaveCopyAs FullPath
Application.DisplayAlerts = False
Set wb = Workbooks.Open(FullPath)
wb.SaveAs Left(FullPath, Len(FullPath) - 1) & "x", 51
wb.Close False
Kill FullPath
Application.DisplayAlerts = True
MsgBox "COMPLETED CORRECTLY"
Exit Sub
XETA: MsgBox "THERE WAS A FAULT SOMEWHERE"
End Sub
Then you can use it like this:
Private Sub CommandButton1_Click()
Call XLSMtoXLSX(Date)
End Sub
I use the code below to save a workbook using two fields as the name. This part works dead on but when the save as window opens and i click cancel, it creates a false.xml excel file. Not sure as to why. I have tried using without the if statement but still creates it.
Can someone tell me why this happens and how to stop it?
Also is there code to catch errors in vb?
Regards
Sub FileSave()
Dim IntialName As String
Dim fileSaveName As Variant
InitialName = Range("C2") & " " & Range("H2") & " Cash Sheet"
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
fileFilter:="Excel Files (*.xls), *.xls")
If fileSaveName <> False Then
MsgBox "Save as " & fileSaveName
End If
ActiveWorkbook.SaveAs fileSaveName
End Sub
In your code you check for If fileSaveName <> False but if it is false you save the workbook in spite. So VBA builds an filename from this False value. Write
If fileSaveName <> False Then
MsgBox "Save as " & fileSaveName
ActiveWorkbook.SaveAs fileSaveName
End If
instead.
For error handling in VBA look here.