Chuck0185
Chuck0185

Reputation: 531

MS Access VBA Open a Text file and write to a specific line without overwriting the file

I have a text file that I would like to add a header and a footer to. I don't want to overwrite the first or last lines, rather I'd like to add a new first line and append a line to the end of the file.

The below Function works for appending to the bottom of the file but I'd like to be able to control where the line is inserted. Thank you!

Function WriteToText(sFile As String, sText As String)

    On Error GoTo Err_Handler
    Dim iFileNumber           As Integer

    iFileNumber = FreeFile                   ' Get unused file number
    Open sFile For Append As #iFileNumber    ' Connect to the file
    Print #iFileNumber, sText                ' Append our string
    Close #iFileNumber                       ' Close the file   Exit_Err_Handler:
    Exit Function   Err_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: Txt_Append" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occured!"
    GoTo Exit_Err_Handler End Function

Upvotes: 0

Views: 2908

Answers (1)

Andre
Andre

Reputation: 27634

What you do for a task like this:

  1. Read the whole file into a string (Open For Input)
  2. Add the data you want: S = "header line" & vbCrLf & S & vbCrLf & "footer line"
  3. Write the whole string to the file, overwriting it (Open For Output)

Upvotes: 1

Related Questions