Home > How-To Library > Text File Handling

How to replace a line for particular line number

**************************************************************** * © 2007 CodeItBetter http://www.codeitbetter.com * * This notice MUST stay intact for legal use * ****************************************************************
Public Function ReplaceLine(ByVal strTxtFilePath As String, ByVal intReplaceLineNo As Integer, _ ByVal strReplaceLine As String) As Boolean 'This function will Replace the Line for given line number from the given file Dim strTxt As String Dim I As Integer Dim strLines() As String On Error GoTo ReplaceLine_Error 'Open the text file Open strTxtFilePath For Input As #1 'load the text file in strTxt variable strTxt = Input(LOF(1), 1) 'close the text file Close #1 'store the lines strLines = Split(strTxt, vbCrLf) strTxt = "" For I = LBound(strLines) To UBound(strLines) If I = intReplaceLineNo - 1 Then strTxt = strTxt & strReplaceLine & vbCrLf Else strTxt = strTxt & strLines(I) & vbCrLf End If Next I 'open the text file to write the content of strTxt Open strTxtFilePath For Output As #1 Print #1, strTxt 'Close the text file Close #1 On Error GoTo 0 Exit Function ReplaceLine_Error: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure " & _ "ReplaceLine of Module Module1" End Function

If you would like to submit your code here please us. Do not forget to mention your name. We are always thankful to each and everyone of you who submitted their code here.