Created
October 26, 2017 21:15
-
-
Save richard512/a58dbd6c97ca226aad11e6a3b72e3d31 to your computer and use it in GitHub Desktop.
Append to CSV in VBA
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment