How to I create a text file from part of another text file (for given line numbers like Line No. 2 to 7)
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 'Text File Handling - How to I create a text file from part of another text file (for given line numbers like Line No. 2 to 7) Option Explicit Sub CreateTextFileFromFile(ByVal intStart As Integer, ByVal intEnd As Integer, _ ByVal strSourceFile As String, ByVal strFinalFile As String) 'How to Call this function: 'Call CreateTextFileFromFile(2, 7, "C:\Temp\test.txt", "C:\Temp\test1.txt") Dim strFileArray() As String, sText As String Dim I As Integer If intStart < 1 Then Call MsgBox("Starting Line Number should not be less than 1", vbCritical, App.Title) GoTo ExitHere End If If intStart > intEnd Then Call MsgBox("Starting Line Number should be less than Ending Line Number", vbCritical, App.Title) GoTo ExitHere End If 'Read the text file strFileArray() = Split(ReadTextFileContents(strSourceFile), vbCrLf) If intEnd - 1 > UBound(strFileArray) Then Call MsgBox("Ending Line Number should be less than Number of Lines in the Text file", vbCritical, App.Title) GoTo ExitHere End If For I = intStart - 1 To intEnd - 1 sText = sText & strFileArray(I) & vbCrLf Next I 'Create a new file with part of text file Call WriteTextFileContents(sText, strFinalFile) ExitHere: Exit Sub End Sub Public Function ReadTextFileContents(filename As String) As String Dim fnum As Integer, isOpen As Boolean On Error GoTo Error_Handler ' Get the next free file number. fnum = FreeFile() Open filename For Input As #fnum ' If execution flow got here, the file has been open without error. isOpen = True ' Read the entire contents in one single operation. ReadTextFileContents = Input(LOF(fnum), fnum) ' Intentionally flow into the error handler to close the file. Error_Handler: ' Raise the error (if any), but first close the file. If isOpen Then Close #fnum If Err Then Err.Raise Err.Number, , Err.Description End Function Sub WriteTextFileContents(Text As String, filename As String, Optional AppendMode As Boolean) Dim fnum As Integer, isOpen As Boolean On Error GoTo Error_Handler ' Get the next free file number. fnum = FreeFile() If AppendMode Then Open filename For Append As #fnum Else Open filename For Output As #fnum End If ' If execution flow gets here, the file has been opened correctly. isOpen = True ' Print to the file in one single operation. Print #fnum, Text ' Intentionally flow into the error handler to close the file. Error_Handler: ' Raise the error (if any), but first close the file. If isOpen Then Close #fnum If Err Then Err.Raise Err.Number, , Err.Description End Sub |