Problem : Excel VBA Macro – save workbook to a relative path and assign name
I am having trouble with an Excel Macro. I need to save the current file with the same name in it’s current directory. I also need to save the file as *.xml with the same name in a second directory (overwriting the last file). I am having issues with getting the files to save in the correct directories and keeping the same name. The biggest problem is the directory names have to be relative to the current folder the file is in, because the files could be on any root directory.
What I am getting is recursive names like: FileName.xlsFilename.xls or the files are not in the right directory. *code attached*
Thanks!
Code Snippet:
Sub SaveXML()
‘
‘ SaveXML Macro
‘ Keyboard Shortcut: Ctrl+s
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:= ThisWorkbook.Path & ThisWorkbook.Name, FileFormat:= xlNormal, Password:=””, WriteResPassword:=””, ReadOnlyRecommended:=False, CreateBackup:=False
ChDir “..\xml\”
ActiveWorkbook.SaveAs Filename:= ThisWorkbook.Name, FileFormat:= xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=FalseActiveWorkbook.Save
End Sub
Solution : Excel VBA Macro – save workbook to a relative path and assign name
Unless you are going to close it immediately. It is probably best to keep to the last the name you want to use later.
It is best not to mix ThisWorkbook an ActiveWorkbook
Sub SaveXML()
‘
‘ SaveXML Macro
‘ Keyboard Shortcut: Ctrl+s
Dim strName As String
Dim strPath As String
Application.DisplayAlerts = False
strName = ActiveWorkbook.Name
strPath = ActiveWorkbook.Path
If strPath = “” Then
strPath = CurDir
End If
ActiveWorkbook.SaveAs Filename:=strPath & “\xml\” & strName, FileFormat:=xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
ActiveWorkbook.SaveAs Filename:=strName, FileFormat:=xlNormal
End Sub