Read specific line from text file
Posted on June 25, 2011
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 | 'Text File Handling - Read specific line from text file Public Function ReadLine(fName As String, LineNumber As Long) As String 'Parameters: fName = FullPath to File ' LineNumber = LineToRead 'Returns: Contents of the line, or a blank string if ' LineNumber is greater than the total number of lines 'Requires: Reference to Microsoft Scripting Runtime 'Example: MsgBox ReadLine("C:\AutoExec.bat", 3) ' Displays third line of autoexec.bat Dim oFSO As New FileSystemObject Dim oFSTR As Scripting.TextStream Dim ret As Long Dim lCtr As Long If oFSO.FileExists(fName) Then Set oFSTR = oFSO.OpenTextFile(fName) Do While Not oFSTR.AtEndOfStream lCtr = lCtr + 1 If lCtr = LineNumber Then ReadLine = oFSTR.ReadLine Exit Do End If oFSTR.SkipLine Loop oFSTR.Close Set oFSTR = Nothing End If End Function |