How to replace a line for particular line number
Posted on January 4, 2009
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 'Text File Handling - How to replace a line for particular line number 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 |
Related posts:
- How to Search & Replace the Line for Given Search String in a text file
- How to count number of lines in a text file
- Search & Delete the Line for Given Search String in a text file
- How to Extract each and every word individually from a text file
- How to I create a text file from part of another text file (for given line numbers like Line No. 2 to 7)
- How to Delete a specific line from a file (note: first line = line number 0)
- How to Read Line By Line & Retrieve Each Word From Text File
- How to Return a specific line number from a file (note: first line = line number 0)
- How to delete a line for a given line number from a text file
- How to read text file contents for a given file (in four ways)