Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to Text File VBA

Tags:

csv

excel

vba

I need to take values from a selected range to a comma delimited text file and append them. The code below gives me an error at Set TS. Why??

Sub Wri()

Dim myrng As Range
Dim Cell As Range

On Error Resume Next
Set myrng = Application.InputBox("Select range", Type:=8)
On Error GoTo 0

If myrng Is Nothing Then
    MsgBox "No cells selected"
    Exit Sub
End If

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0

Dim fs, f, TS, s
Dim cellv As String

Set fs = CreateObject("Scripting.FileSystemObject")
fs.CreateTextFile "C:\Users\HP\Documents\fil.txt"
Set f = fs.GetFile("C:\Users\HP\Documents\fil.txt")
Set TS = f.OpenTextFile(myrng.Value, 8, True, 0)

For Each Cell In myrng
    cellv = Cell.Value
    TS.Write (cellv & Chr(44))
Next Cell

End Sub
like image 693
Neha Avatar asked Mar 15 '14 19:03

Neha


People also ask

How do you append text in VBA?

Starting the program and sub procedure to write VBA Code to Append an existing text file and adding the data. Declaring the strFile_Path variable as String Data Type to store the text file path. Assigning the Existing File path to the variable strFile_Path. Opening the text file for Append with FileNumber as 1.

How do I append to a text file?

To append to a text fileUse the WriteAllText method, specifying the target file and string to be appended and setting the append parameter to True . This example writes the string "This is a test string." to the file named Testfile. txt .


1 Answers

Ive made you a custom sub, replace the sub with these two - the last param determins if it is an append or not and it will handle the new lines too :D

Sub writeCSV(ByVal thisRange As Range, ByVal filePath As String, Optional ByVal fileAppend As Boolean = False)
    Dim cLoop As Long, rLoop As Long
    Dim ff As Long, strRow As String

    ff = FreeFile
    If fileAppend Then
        Open filePath For Append As #ff
    Else
        Open filePath For Output As #ff
    End If

    For rLoop = 1 To thisRange.Rows.Count
        strRow = ""
        For cLoop = 1 To thisRange.Columns.Count
            If cLoop > 1 Then strRow = strRow & ","
            strRow = strRow & thisRange.Cells(rLoop, cLoop).Value
        Next 'cLoop
        Print #ff, strRow
    Next 'rLoop

    Close #ff
End Sub

Sub Wri()

Dim myrng As Range
Dim Cell As Range

On Error Resume Next
Set myrng = Application.InputBox("Select range", Type:=8)
On Error GoTo 0

If myrng Is Nothing Then
    MsgBox "No cells selected"
    Exit Sub
Else
    writeCSV myrng, "C:\Users\HP\Documents\fil.txt", True
End If

End Sub
like image 156
Denzil Newman Avatar answered Oct 19 '22 11:10

Denzil Newman