PDA

View Full Version : Export to CSV with New Name and Time Stamp



Billsy
03-28-2021, 11:43 AM
Hi hopefully this in an easy one for someone. I'm using the following code to save a CSV copy of the current open workbook. The CSV is saved with the same name and in the same directory. The original xlsm stays open.
I would like assign a new name to the CSV and include a date/time stamp at the end. For example:
"Revise Price 28-03-2021 2145.csv"
Many thanks


Sub ExportAsCSV()


Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook


Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy


Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With


MyFileName = CurrentWB.Path & "" & Left(CurrentWB.Name, InStrRev(CurrentWB.Name, ".") - 1) & ".csv"
'Optionally, comment previous line and uncomment next one to save as the current sheet name
'MyFileName = CurrentWB.Path & "" & CurrentWB.ActiveSheet.Name & ".csv"




Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub

Billsy
03-29-2021, 05:30 AM
I have figured this out.

I changed this:

MyFileName = CurrentWB.Path & "" & Left(CurrentWB.Name, InStrRev(CurrentWB.Name, ".") - 1) & ".csv"

with this:

MyFileName = CurrentWB.Path & "" & "Revise_Price " & Format(CStr(Now), "dd-mm-yy hh-mm") & ".csv"