+ Reply to Thread
Results 1 to 5 of 5

Create csv file with double quotes on all fields

Hybrid View

  1. #1
    Registered User
    Join Date
    02-29-2008
    Posts
    13

    Create csv file with double quotes on all fields

    When I create csv files, I need to have all columns wrapped in double-quotes. Currently, Excel only wraps those columns that contain commas in double-quotes. I have access to both Excel 2003 and 2007. Is there a way to configure Excel to wrap all columns and if not, is there some VB magic that I can run to do this?

    I tried to search the forum to see if this had already been discussed, but did not find anything.

    Thanks,

    Jack

  2. #2
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834
    try
    Sub test()
    Dim r As Range, txt As String
    With ActiveSheet.UsedRange
        For i = 1 To .Rows.Count
            For Each r In .Rows(i).Cells
                txt = txt & "," & Chr(34) & r.Text & Chr(34)
            Next
            txt = txt & IIf(i <> .Rows.Count, vbCrLf, "")
        Next
    End With
    Open ThisWorkbook.Path & "\" & ActiveSheet.Name & ".csv" For Output As #1
        Print #1, Mid$(txt, 2)
    Close #1
    End Sub

  3. #3
    Registered User
    Join Date
    02-29-2008
    Posts
    13
    Thanks Jindon for the code. This is working fine for the first row in my spreadsheet. However, for every other row, the resulting csv file starts with a comma. For instance, my original file has 3 rows with 3 columns each:

    apple smith 100
    pear jones 20
    orange jackson 120

    After running your code, the resulting csv file has:

    "apple","smith","100"
    ,"pear","jones","20"
    ,"orange","jackson","120"

    The commas that begin rows 2 and 3 are not supposed to be there.

    Thanks, Jack

  4. #4
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834
    try
    Sub test()
    Dim r As Range, temp As String, txt As String
    With ActiveSheet.UsedRange
        For i = 1 To .Rows.Count
            For Each r In .Rows(i).Cells
                temp = temp & "," & Chr(34) & r.Text & Chr(34)
            Next
            txt = txt & vbCrLf & Mid$(temp,2)
            temp = ""
        Next
    End With
    Open ThisWorkbook.Path & "\" & ActiveSheet.Name & ".csv" For Output As #1
        Print #1, Mid$(txt, Len(vbCrLf) + 1)
    Close #1
    End Sub

  5. #5
    Registered User
    Join Date
    02-29-2008
    Posts
    13
    Thanks Jindon,

    That works!!

    Jack

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1