Private Sub Save_Click()
' --> User Settings, change to suit
Const PathCell = "Table1!B2" ' Path to CSV with "\" at the end, like "C:\Users\Desktop\Folder\"
Const FNameCell = "Table1!C4" ' Name of CSV file, like "testdata"
Const DataSheet = "Table2" ' Name of the sheet with data for CSV file
' <-- End of User Setings
Dim CsvFile As String, Wb As Workbook
' Build full path name to CSV file
CsvFile = Range(PathCell).Value
CsvFile = CsvFile & Range(FNameCell).Value & ".csv"
' Remember active workbook
Set Wb = ActiveWorkbook
' Turn blinking off
Application.ScreenUpdating = True
' Copy data sheet to the temporary new workbook
Worksheets(DataSheet).Copy
' Save temporary workbook as CSV
With ActiveWorkbook
.SaveAs Filename:=CsvFile, _
FileFormat:=xlCSV, CreateBackup:=False, _
Local:=False
' Close it
.Close False
End With
' Restore selection
Wb.Activate
' Restore screen updating
Application.ScreenUpdating = True
' Clean up extra commas at the end of CSV lines
FixCsv CsvFile
End Sub
Sub FixCsv(Optional CsvFile As String)
Const LineSeparator = vbCrLf ' <-- Change to suit
Dim Txt As String, PathName As String, Fso As Object, File As Object
' Choose CSV file
If Len(CsvFile) = 0 Then
' Choose CSV file
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = ThisWorkbook.Path
.Filters.Clear
.Filters.Add "CSV files", "*.csv"
.AllowMultiSelect = False
If .Show = False Then Exit Sub
PathName = .SelectedItems(1)
End With
Else
' Check the presence of CSV file
PathName = CsvFile
If Dir(PathName) = "" Then
MsgBox "File not found:" & vbLf & PathName, vbCritical, "Exit"
Exit Sub
End If
End If
' Trap errors
On Error GoTo exit_
' Read CSV file
Set Fso = CreateObject("Scripting.FileSystemObject")
Set File = Fso.OpenTextFile(PathName, 1)
Txt = File.ReadAll
File.Close
' Trim all commas at the end of lines
If Right(Txt, Len(LineSeparator)) <> LineSeparator Then Txt = Txt & LineSeparator
With CreateObject("vbscript.regexp")
.Global = True
.Pattern = ",+" & LineSeparator
Txt = .Replace(Txt, LineSeparator)
End With
' Write CSV
Set File = Fso.CreateTextFile(PathName, True)
File.Write Txt
File.Close
exit_:
' Report
If Err Then
MsgBox Err.Description, vbCritical, "Error #" & Err.Number
Err.Clear
Else
MsgBox "File is fixed now:" & vbLf & PathName, vbInformation, "Well done!"
End If
End Sub