Skip to content

Instantly share code, notes, and snippets.

@richard512
Created October 26, 2017 21:15

Revisions

  1. richard512 created this gist Oct 26, 2017.
    40 changes: 40 additions & 0 deletions Append2CSV.vba
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    Sub Append2CSV(CSVFile As String, CellRange As String)
    Dim tmpCSV As String 'string to hold the CSV info
    Dim f As Integer
    f = FreeFile
    Open CSVFile For Append As #f
    tmpCSV = Range2CSV(Range(CellRange))
    Print #f, tmpCSV
    Close #f
    End Sub

    Function Range2CSV(list) As String
    Dim tmp As String
    Dim cr As Long
    Dim r As Range

    If TypeName(list) = "Range" Then
    cr = 1

    For Each r In list.Cells
    If r.Row = cr Then
    If tmp = vbNullString Then
    tmp = r.Value
    Else
    tmp = tmp & "," & r.Value
    End If
    Else
    cr = cr + 1
    If tmp = vbNullString Then
    tmp = r.Value
    Else
    tmp = tmp & Chr(10) & r.Value
    End If
    End If
    Next
    End If

    Range2CSV = tmp
    End Function

    Append2CSV("C:\VBA Code\test.csv", "A2:H3")