2021年3月4日星期四

How to get rid of unwanted commas at end of string in CSV file

I have made the following code where the aim is to save two ranges into a CSV file:

Sub Export_range_to_CSV()

Dim myCSVFileName As String  Dim myWB As Workbook  Dim tempWB As Workbook  Dim range1 As Range  Dim range2 As Range  Set range1 = Sheets("sheet1").Range("G2:G4")  Set range2 = Sheets("sheet1").Range("G5:H53")      Application.DisplayAlerts = False  On Error GoTo err    Set myWB = ThisWorkbook  myCSVFileName = "filepath" & "\" & "name" & VBA.Format(VBA.Now, "yyyymmdd_hhmm") & ".csv"    range1.Copy    Set tempWB = Application.Workbooks.Add(1)  With tempWB      .Sheets(1).Range("A1").PasteSpecial xlPasteValues       range2.Copy      .Sheets(1).Range("A4").PasteSpecial xlPasteValues      .SaveAs filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False      .Close  End With  

err: Application.DisplayAlerts = True End Sub

The code above does the job, but for range1 it has commas at the end of the string when saved as CSV. I need to remove these in order for a job downstream to work. How do I get rid of the commas at the end of range1?

This is how it looks once saved as the CSV file:

range1

  • X=Y, <- need to remove these commas

  • Z=U,

  • M=Q,

Range2

  • datetime,quantity
  • 2021-03-05 23:00:00+00:00,17
  • 2021-03-05 23:30:00+00:00,17
  • 2021-03-06 00:00:00+00:00,17
  • 2021-03-06 00:30:00+00:00,17
https://stackoverflow.com/questions/66485748/how-to-get-rid-of-unwanted-commas-at-end-of-string-in-csv-file March 05, 2021 at 10:07AM

没有评论:

发表评论