vba to save xltm file as xlsb file - excel

I have a script which opens an external file to execute a script and after finishing the script, it saves as an xlsb file. The code worked perfectly for saving from xlsb file to xlsb file. But because I want to have some security for the original file, I want the original xlsb file to be a xltm file. I adapted the save as script to it and tested it as a separate routine in the file itself. It works perfectly.
Now I added the routine to the external script file, but when I execute the script then, Excel freezes and no 'save as' screen appears at all.
I expect the external script to have some other external reference to work properly but I cannot figure out how to adjust my script to this.
This is the code of the original file:
Option Explicit
Sub vernieuwalles()
Dim myTemplate As String: myTemplate = ActiveWorkbook.Name
Dim myTool As String: myTool = "refresh_segment_template.xlsm"
Application.ScreenUpdating = False
Workbooks.Open GetPath & myTool
Application.Run myTool & "!vernieuwalles", myTemplate
Call Windows(myTool).Close(False)
Application.ScreenUpdating = True
End Sub
Private Function GetPath() As String
Dim myPosition As Integer
Dim myPath As String: myPath = ActiveWorkbook.Path
myPosition = InStr(StrReverse(myPath), "\") - 1
myPosition = Len(myPath) - myPosition
GetPath = Mid(myPath, 1, myPosition - 1) & "\XLAM\"
End Function
It refers to the external script file to be opened and executed.
The external file has this script (I only pasted the save as part of the script):
Option Explicit
Dim aantalrijen As Long
Const SheetSchaduwblad As String = "schaduwblad"
Sub vernieuwalles(mytemplate As String)
Windows(mytemplate).Activate
On Error GoTo Err_
Application.StatusBar = "Bezig met vernieuwen"
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' Call SheetOpschonen
Call datawissen
Call dataplaatsen
Call kolomtitels
Call toevoegen
Call maaktabel
Call refreshpivots
Exit_:
Application.StatusBar = ""
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Exit Sub
Err_:
Call MsgBox(Err.Number & vbCrLf & Err.Description)
Resume Exit_
Application.Calculation = xlCalculationAutomatic
End Sub
Sub refreshpivots()
Dim workbook_Name As Variant
Dim location As String
Dim workbookdirectory As String
Dim activewb As String
ActiveWorkbook.RefreshAll
activewb = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
workbookdirectory = "M:\Commercie\Marktdata\IRi\Segment Ontwikkeling\"
workbook_Name = Application.GetSaveAsFilename(fileFilter:="Excel binary sheet (*.xlsb), *.xlsb", InitialFileName:=workbookdirectory & activewb)
If workbook_Name = False Then
ActiveWorkbook.SaveAs filename:=activewb, FileFormat:=50
End If
But when I execute the script from the original file, excel freezes as pointed out. What should be changed for this code to be working with the external file and the save from xltm to xlsb script?
As pointed out: the save as script is the only thing that has changed in the script and the xlsb to xltm extension-change is the only thing that has changed in the original file.

Related

external tool to copy data from external workbook to target workbook

I have 1 external xlsm file that contains the macro code I need to perform operations for several templates. This is the actual process how I would like to have it in short:
'Template' is opened by user. User clicks 'refresh' button
'mytool' is opened and performs several operations in 'template'
after performing operations 'mytool' is closed again and templates is saved
user works in template with updated data.
I now want to change this tool a bit so it not only performs operations on the target workbook, but firstly, copies the needed data from another external workbook. I have been trying and searching to find code to have this done, but I am struggling with it to get it right.
'Template' is opened by user. User clicks 'refresh' button
'mytool' is opened and performs several operations in 'template' including opening the raw data file and copying the data in the file to 'template'
after performing operations 'mytool' is closed again and templates is saved
user works in template with updated data.
edit: own solution added to question on the bottom of this question.
I have this code to make the external tool act/work in the target workbook:
Sub vernieuwalles(mytemplate As String)
Windows(mytemplate).Activate
In the target workbook, I have this code:
Sub vernieuwalles()
Dim myTemplate As String: myTemplate = ActiveWorkbook.Name
Dim myTool As String: myTool = "refresh_base_incrementals.xlsm"
Application.ScreenUpdating = False
Workbooks.Open GetPath & myTool
Application.Run myTool & "!vernieuwalles", myTemplate
Call Windows(myTool).Close(False)
Application.ScreenUpdating = True
End Sub
Private Function GetPath() As String
Dim myPosition As Integer
Dim myPath As String: myPath = ActiveWorkbook.Path
myPosition = InStr(StrReverse(myPath), "\") - 1
myPosition = Len(myPath) - myPosition
GetPath = Mid(myPath, 1, myPosition - 1) & "\XLAM\"
End Function
I want the tool to open another excel file which is located in a seperate directory. This is the directory structure I use for this:
location target workbook:
\Promo reports\test\
this is the location for the tool:
\promo reports\xlam\
this is the location for the external workbook:
\Promo reports\test\data files\
I was already busy with adjusting existing code to have the correct location in it:
Sub import_data()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Workbooks.Open GetPath & fileName
fileName = Mid(mytemplate,18,Len(mytemplate) - 4
End Sub
Private Function GetPath() As String
Dim myPosition As Integer
Dim myPath As String: myPath = ActiveWorkbook.Path
myPosition = InStr(StrReverse(myPath), "\") - 1
myPosition = Len(myPath) - myPosition
GetPath = Mid(myPath, 1, myPosition - 1) & "\test\data files\"
End Function
But then I got stock. I want the data from 3 sheets having copied to those some sheets (they already exist) in the target workbook.
There are 3 sheets: Food-Drug, ASW A, ASW P.
The external workbook is a data file which filename will be consequently the same as the templates name but shorts. for example:
the template name is promo rapportage prostaat.xlsb
the datafile name will be prostaat.xlsb
I want the tool to use the name of the template to get the right filename to open in the data files directory.
How can I add these operations to "mytool"?
edit:
I now changed the code(s) to this:
in the target workbook:
Option Explicit
Sub vernieuwalles()
Dim mytemplate As String: mytemplate = ActiveWorkbook.Name
Dim myTool As String: myTool = "refresh_base_incrementals.xlsm"
Dim myData As String: myData = Mid(ActiveWorkbook.Name, 18, Len(ActiveWorkbook.Name) - 4)
Application.ScreenUpdating = False
Workbooks.Open GetPath & myTool
Workbooks.Open GetPath2 & myData
Application.Run myTool & "!vernieuwalles", mytemplate
Call Windows(myTool).Close(False)
Application.ScreenUpdating = True
End Sub
Private Function GetPath() As String
Dim myPosition As Integer
Dim myPath As String: myPath = ActiveWorkbook.Path
myPosition = InStr(StrReverse(myPath), "\") - 1
myPosition = Len(myPath) - myPosition
GetPath = Mid(myPath, 1, myPosition - 1) & "\XLAM\"
End Function
Private Function GetPath2() As String
Dim myPosition As Integer
Dim myPath As String: myPath = ActiveWorkbook.Path
myPosition = InStr(StrReverse(myPath), "\") - 1
myPosition = Len(myPath) - myPosition
GetPath2 = Mid(myPath, 1, myPosition - 1) & "\test\data files\"
End Function
And in the external script file (mytool):
Sub importdata()
Dim mytemplate As String: mytemplate = ActiveWorkbook.name
Dim myData As String: myData = Mid(ActiveWorkbook.name, 18, Len(ActiveWorkbook.name) - 4)
Dim sheetnames As Variant, i As Integer
sheetnames = Array("food-drug", "ASW A-merk", "ASW PL")
For i = LBound(sheetnames) To UBound(sheetnames)
With Workbooks(myData).Sheets(sheetnames(i))
aantalrijen = .Range("A1", .Range("A1").End(xlDown)).Cells.Count - 1
.Range(.Cells(1, "A"), .Cells(aantalrijen, "DO")).Copy _
Workbooks(mytemplate).Sheets(sheetnames(i)).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
End With
Next i
End Sub
I tested this with a template called 'promo rapportage prostaat.xlsb' and it perfectly opens the file prostaat.xlsb and copies the data on the 3 worksheets in this file to the worksheets in the target workbook.

Read only opened excel file saved with VBA but is not saved at all?

I have an excel template which is recommended to open as read-only on opening to users (I have the password to open file to be able to change/edit the file).
I have a vba script which saves the read-only opened file.
When I save the file the normal way (menu > save as > choose file > save) excel returns a message telling me the file cannot saved because it is opened as read-only.
When I use the script, a popup shows me the desired directory with the proper filename, and saving is possible (so opened as read-only, it still can be saved with the same filename). No errors at all.
But when I look in the directory now, most of the files I have updated and saved do not have an updated 'last edited date/time'. And when I open the file, all changes I have made are not in the file anymore.
Is it possible that VBA says it has saved the file with the same filename, although the file was opened as read-only, but in fact did not save anything?
here is the save-as code:
Sub vernieuwalles(mytemplate As String)
Dim workbook_Name As Variant
Windows(mytemplate).Activate
On Error GoTo Err_
MsgBox ("Bezig met vernieuwen")
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' Call SheetOpschonen
Call datawissen
Call dataplaatsen
Call kolomtitels
Call toevoegen
Call maaktabel
Call refreshpivots
workbook_Name = Application.GetSaveAsFilename(fileFilter:="Excel binary sheet (*.xlsb), *.xlsb", InitialFileName:="M:\Commercie\Marktdata\IRi\Segment ontwikkeling\")
MsgBox workbook_Name
If workbook_Name <> False Then
ActiveWorkbook.SaveAs Filename:=workbook_Name, FileFormat:=50
End If
Exit_:
Application.StatusBar = ""
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Exit Sub
Err_:
Call MsgBox(Err.Number & vbCrLf & Err.Description)
Resume Exit_
Application.Calculation = xlCalculationAutomatic
End Sub
it seems to work, but as I found out, it does not work when the file is opened as read-only, although I looks like the file is saved and can overwrite the original file while being opened as read-only.
update 2019-04-11 10:00 AM:
with the suggestion from ZACK I adjusted my save as code to:
Sub vernieuwalles(mytemplate As String)
Dim workbook_Name As Variant
Windows(mytemplate).Activate
On Error GoTo Err_
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' Call SheetOpschonen
Call datawissen
Call dataplaatsen
Call kolomtitels
Call toevoegen
Call maaktabel
Call refreshpivots
If ActiveWorkbook.ReadOnly = True Then ActiveWorkbook.ChangeFileAccess Mode:=xlReadWrite
workbook_Name = Application.GetSaveAsFilename(fileFilter:="Excel binary sheet (*.xlsb), *.xlsb", InitialFileName:="M:\Commercie\Marktdata\IRi\Segment ontwikkeling\")
If workbook_Name <> False Then ActiveWorkbook.SaveAs Filename:=workbook_Name, FileFormat:=50
ActiveWorkbook.ChangeFileAccess Mode:=xlReadOnly
Exit_:
Application.StatusBar = ""
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Exit Sub
Err_:
Call MsgBox(Err.Number & vbCrLf & Err.Description)
Resume Exit_
Application.Calculation = xlCalculationAutomatic
End Sub
opening a read-only file and saving it while overwriting the original read-only file works. Except for that I know have to enter the filename again. While if before uses the original filename, there is no filename shown in the save as popup screen anymore.
update 2 2019-04-11 10:31 AM:
I had some additional "save as code" for getting the right filename which I used before (was in the original post). I added this code to my main macro and tested if it works. Now the file access is changed correctly, the save as popup shows the correct filename in the right directory and the file is saved.
Conclusion: case closed, question answered!
Here is how it works (for me):
Sub vernieuwalles(mytemplate As String)
Dim workbook_Name As Variant
Dim workbookdirectory As String
Dim activewb As String
Windows(mytemplate).Activate
On Error GoTo Err_
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' Call SheetOpschonen
Call datawissen
Call dataplaatsen
Call kolomtitels
Call toevoegen
Call maaktabel
Call refreshpivots
If ActiveWorkbook.ReadOnly = True Then ActiveWorkbook.ChangeFileAccess Mode:=xlReadWrite
activewb = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
workbookdirectory = "M:\Commercie\Marktdata\IRi\Segment Ontwikkeling\"
workbook_Name = Application.GetSaveAsFilename(fileFilter:="Excel binary sheet (*.xlsb), *.xlsb", InitialFileName:=workbookdirectory & activewb)
If workbook_Name <> False Then ActiveWorkbook.SaveAs Filename:=workbook_Name, FileFormat:=50
ActiveWorkbook.ChangeFileAccess Mode:=xlReadOnly
Exit_:
Application.StatusBar = ""
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Exit Sub
Err_:
Call MsgBox(Err.Number & vbCrLf & Err.Description)
Resume Exit_
Application.Calculation = xlCalculationAutomatic
End Sub
One other solution you can try is this, which is what Zac was talking about. It will change the access of the active workbook so you can run your code then change it back to read only.
Sub saveas()
Dim workbook_Name As Variant
Dim location As String
Dim workbookdirectory As String
Dim activewb As String
ActiveWorkbook.ChangeFileAccess Mode:=xlReadWrite
activewb = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
workbookdirectory = "M:\Commercie\Marktdata\IRi\Segment Ontwikkeling\"
workbook_Name = Application.GetSaveAsFilename(fileFilter:="Excel binary sheet (*.xlsb), *.xlsb", InitialFileName:=workbookdirectory & activewb)
If workbook_Name = False Then ActiveWorkbook.saveas Filename:=activewb, FileFormat:=50
ActiveWorkbook.ChangeFileAccess Mode:=xlReadOnly
End Sub

vba to save excel file with given name to specific location

I recently asked about saving an excel file with a specific name to a set location:
Getting correct default save name and save directory with spaces in VBA
I want to use this same procedure but in a somewhat different way. I tried to edit the code to make it work, but I keep on have a black filename screen when I execute the code.
The file I want to save with the routine is a template which is being refreshed with new data every 4 weeks. It is a read-only file which functions as a source template and after updating the data, I has to be saved on a different location to keep the original source file save from errors/unwanted modification.
When refreshing, the template opens a file which contains the refresh script named "refresh_segment_template.xlsm".
the code in the template is:
Option Explicit
Dim aantalrijen As Long
Const SheetSchaduwblad As String = "schaduwblad"
-------
Sub vernieuwalles()
Dim myTemplate As String: myTemplate = ActiveWorkbook.Name
Dim myTool As String: myTool = "refresh_segment_template.xlsm"
Application.ScreenUpdating = False
Workbooks.Open GetPath & myTool
Application.Run myTool & "!vernieuwalles", myTemplate
Call Windows(myTool).Close(False)
Application.ScreenUpdating = True
End Sub
Private Function GetPath() As String
Dim myPosition As Integer
Dim myPath As String: myPath = ActiveWorkbook.Path
myPosition = InStr(StrReverse(myPath), "\") - 1
myPosition = Len(myPath) - myPosition
GetPath = Mid(myPath, 1, myPosition - 1) & "\XLAM\"
End Function
the code in the refresh_segment_template is:
Option Explicit
Dim aantalrijen As Long
Const SheetSchaduwblad As String = "schaduwblad"
------------------
Sub vernieuwalles(mytemplate As String)
Windows(mytemplate).Activate
On Error GoTo Err_
Application.StatusBar = "Bezig met vernieuwen"
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' Call SheetOpschonen
Call datawissen
Call dataplaatsen
Call kolomtitels
Call toevoegen
Call maaktabel
Call refreshpivots
Exit_:
Application.StatusBar = ""
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Exit Sub
Err_:
Call MsgBox(Err.Number & vbCrLf & Err.Description)
Resume Exit_
Application.Calculation = xlCalculationAutomatic
End Sub
-------------
Sub refreshpivots()
Dim workbook_Name As Variant
Dim location As String
Dim filename As String
filename = "M:\Commercie\Marktdata\IRi\Segment Ontwikkeling\" & ActiveWorkbook.Name
ActiveWorkbook.RefreshAll
workbook_Name = Application.GetSaveAsFilename(fileFilter:="Excel binary sheet (*.xlsb), *.xlsb", InitialFileName:="M:\Commercie\Marktdata\IRi\Segment Ontwikkeling\")
If workbook_Name <> False Then
ActiveWorkbook.SaveAs filename:=filename, WriteResPassword:="TM", FileFormat:=50
End If
End Sub
I am now wondering how I can make the last script to use the filename of the template and save it on the give location in the script (i.e. M:\Commercie\Marktdata\IRi\Segment Ontwikkeling).
When I execute the code above, I get a 'save as' screen, but with no filename given, only the set directory is correct.
The refresh_segment_template is a .xlsm file. The template is a .xlsb file.

How to save xlsm as xlsx?

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

Loop Freezing Excel After Printing

I have a spreadsheet that creates a CSV file and deposits the CSV file in a folder next to the original file. The spreadsheet seems to work fine. When you have your data entered, you click export, and a CSV file is put in a folder called "Uploads" that is next to the original file.
The issue is when I use the quick print button on my Excel quick access toolbar. When I click the quick print button, everything seems to print fine. However, as soon as I close the file, (EDIT: ALL Printing seems to be freezing the file. As soon as the file is closed) Excel then goes into a freeze where it looks like it is trying to run some code? I am a novice in VBA so I am not sure what is happening, all I know is that after my file is closed, Excel freezes up and I have to restart Excel. I do not even have any macros or VBA for an Excel close or Excel open trigger.
Can anyone recreate the issue and give me insight into how my code might be doing this?
Private Sub Export_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim MyPath As String
Dim MyFileName As String
'The path and file names:
MyPath = ActiveWorkbook.Path & "\Uploads"
MyFileName = "" & Range("a2") & "_Upload"
On Error GoTo Ending
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
'Makes sure the filename ends with ".csv"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
'Copies the sheet to a new workbook:
Sheets("UploadData").Copy
'The new workbook becomes Activeworkbook:
With ActiveWorkbook 'Saves the new workbook to given folder / filename:
.SaveAs FileName:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False 'Closes the file
.Close False
End With
ChDir MyPath
Workbooks.Open FileName:= _
MyPath & "\" & MyFileName & """"
ActiveWorkbook.Save
ActiveWorkbook.Close
GoTo Skip
Ending:
MsgBox ("ERROR! Please make sure you have a folder named Uploads next to the template file")
ActiveWorkbook.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Skip:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This actually shouldn't work at all, regardless of what you do before you run it. First, you ensure that MyPath ends with a \ here...
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
...but then when you (re)build the same path below you're inserting a second \:
Workbooks.Open FileName:= _
MyPath & "\" & MyFileName & """"
This should always fail. You can avoid this entire problem with paths by using the Scripting.FileSystemObject's .BuildPath function:
'Requires a reference to Microsoft Scripting Runtime.
Dim filePath As String, fso As New Scripting.FileSystemObject
filePath = fso.BuildPath(ThisWorkbook.Path, MyFileName)
You can also use this for the file extension:
If LCase$(fso.GetExtensionName(MyFileName)) <> "csv" Then
MyFileName = MyFileName & ".csv"
End If
Note that this test will never be true...
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
...because MyFileName will always end with "load":
MyFileName = "" & Range("a2") & "_Upload"
Also, you should remove all the references to ActiveWorkbook. I have no idea why printing would effect this, but there isn't anything else I can identify that should be an issue. I'd structure it more like this (error handler removed for clarity - don't put it back until you're finished debugging it):
'Add a reference to Microsoft Scripting Runtime.
Private Sub Export_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
With New Scripting.FileSystemObject
Dim filePath As String
Dim targetDir As String
targetDir = .BuildPath(ThisWorkbook.Path, "Uploads")
If Not .FolderExists(targetDir) Then
MsgBox ("ERROR! Please make sure you have a folder named Uploads next to the template file")
Exit Sub
End If
filePath = .BuildPath(targetDir, ActiveSheet.Range("A2").Value & "_Upload.csv")
End With
'Copies the sheet to a new workbook:
Dim csv As Workbook
Set csv = Application.Workbooks.Add
With csv
ThisWorkbook.Sheets("UploadData").Copy .Sheets(1)
.SaveAs Filename:=filePath, _
FileFormat:=xlCSV, _
CreateBackup:=False 'Closes the file
.Close xlDoNotSaveChanges
End With
'Reopen and re-save to fix formatting.
Set csv = Workbooks.Open(filePath)
csv.Close xlSaveChanges
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Resources