'Using VBA to create a CSV from an Excel sheet, ignoring semicolons
I found some code somewhere, and tuned it a bit to suit my needs. However, some fields have semicolons in them, and whenever I open a freshly generated CSV file in Excel, anything after a semicolon is automatically placed in a new column. That's even before I transform the data. I tried wrapping the semicolons in double quotes, single quotes, quadruple quotes, and all that, but every time I open it in Excel, it's the same result. The code:
Sub CSV_contact()
Dim myCSVFileName As String
Dim myWB As Workbook
Dim rngToSave As Range
Dim fNum As Integer
Dim csvVal As String
Dim lastrow As Long
With Sheets("Contactpersonen").UsedRange
lastrow = .Rows(.Rows.Count).Row
End With
Set myWB = ThisWorkbook
myCSVFileName = Sheets("Instellingen").Range("B4").Value & "\" & "CSV_contactpersonen" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
csvVal = ""
fNum = FreeFile
Set rngToSave = Range("A10:O" & lastrow)
Open myCSVFileName For Output As #fNum
For i = 1 To rngToSave.Rows.Count
For j = 1 To rngToSave.Columns.Count
csvVal = csvVal & Chr(34) & Replace(rngToSave(i, j).Value, ";", Chr(34) & Chr(34) & ";" & Chr(34) & Chr(34)) & Chr(34) & ","
Debug.Print csvVal
Next
Print #fNum, Left(csvVal, Len(csvVal) - 2)
csvVal = ""
Next
Close #fNum
End Sub
When I use debug print, this is what a typical line looks like:
"normal string 1","normal string 2","string containing"";"" somewhere"";"" in the middle","","","","another normal string after some empty columns",
Mind that this is one of the things I tried, the first thing I tried created lines where the semicolon strings looked like this:
"string containing; somewhere; in the middle"
Isn't there just an escape character I can put in front of it? like a / or a *
I also read things about having to write my own CSV parser, but that's way beyond my skill level
Additionally, maybe it's important to note my client uses European excel, so the comma is the standard decimal delimiter. Maybe the solution would be to (temporarily) set the delimiter to a point? I'd really love it to be temporary though, as my client is an accountant and really values "correct" layout.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
