How do i go about putting the last line of a text file in a string?
Printable View
How do i go about putting the last line of a text file in a string?
Dim LineInString as string
open FNAME foro intut as #1
do until eof(1)
line input #1, LineInString
loop
close #1
'now the last line of the file in in LineInString
kevin
'Set Microsoft Scripting Runtime as a reference
The following uses the FileSystemObject and TextStream Object to read from a file. The message box will display the last line of the text file.
Dim fso As FileSystemObject
Dim ts As TextStream
Dim f As Object
Dim strLastLine As String
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile("FilePath\FileName")
Set ts = f.OpenAsTextStream(ForReading)
'Loops through text file capturing each line in the variable
Do While ts.AtEndOfStream <> True
strLastLine = ts.ReadLine
Loop
MsgBox strLastLine
ts.Close
Set ts = Nothing
Set f = Nothing
Set fso = Nothing
Here is a quick way to do it :)
Code:Dim A$, I&
Open "C:\test.txt" For Binary Access Read As #1
A = String(LOF(1), 0)
Get #1, , A
Close #1
I = InStrRev(A, vbLf)
A = Mid(A, I + 1)
MsgBox A
Is there a way to make this more flexible? Like have a variable of int with a line number... and get it to read that line number... and everytime i change the variable it wont matter because it just reads the variable in the line number?
Check out this code and modify it to suit your need.
http://www.freevbcode.com/ShowCode.Asp?ID=2667
This goes to the line number you specify and deletes it. You can change the code to read it instead.
'Try this.
'If you put a line number in that is not valid you will not get a msg
'Set Microsoft Scripting Runtime as a reference
Dim fso As FileSystemObject
Dim ts As TextStream
Dim f As Object
Dim strLine As String
Dim LineNumber As Double
Dim Result
LineNumber = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile("c:\test1.txt")
Set ts = f.OpenAsTextStream(ForReading)
Result = InputBox("Enter Line Number", "Line Number")
'Loops through text file capturing each line in the variable
Do While ts.AtEndOfStream <> True
strLastLine = ts.ReadLine
If LineNumber = Result Then
MsgBox strLine
Exit Do
End If
LineNumber = LineNumber + 1
Loop
ts.Close
Set ts = Nothing
Set f = Nothing
Set fso = Nothing
This might help you out. The first line of the file will have an index of 1.
Code:Private Function GetLine(ByVal Index As Long) As String
Dim A$, I&, S$()
If Index < 1 Then Exit Function
Index = Index - 1
Open "C:\test.txt" For Binary Access Read As #1
A = String(LOF(1), 0)
Get #1, , A
Close #1
S = Split(A, vbCrLf)
I = UBound(S)
If Index > I Then Index = I
GetLine = S(Index)
End Function