Insert line in first row of CSV text file with VBA



I have a CSV text file and would like to insert a row at the top using the
VBA Write statement from Excel. I am able to append, but can not add to the
first line.

RB Smissaert

Try this code:

Sub InsertLineAtBeginningTexFile(strFile As String, strLine As String)

Dim hFile As Long
Dim FileContents As String
Dim NewString As String

hFile = FreeFile
Open strFile For Binary As #hFile
FileContents = Space(FileLen(strFile))
Get #hFile, , FileContents
Close #hFile

NewString = strLine & vbCrLf
FileContents = NewString & FileContents

Open strFile For Binary As #hFile
Put #hFile, , FileContents
Close #hFile

End Sub


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question