Link to home
Create AccountLog in
Avatar of Bob Schneider
Bob SchneiderFlag for United States of America

asked on

Find Last *.txt Line in VB6

What is the fastest way to find the value of the last line in a plain text file with records like I am listing below.  I want to write it to a variable sLastTriRcd (There are usually thousands of records so a quick and efficient way is necessary.)

aaC4000000018ff900011909281324072bf8FS
aaC4000000018ff900011909281324072bf8BS
aaC4000000018ff900011909281324072bf8LS
aaC40000000190ac000119092813241243b7FS
aaC40000000190ac000119092813241243b7BS
aaC40000000190ac000119092813241243b7LS
aaC400000001905800011909281324181f96FS
aaC400000001905800031909281324183a95BS
aaC60000000191f700011909281324184bc8FS
aaC60000000191f700021909281324184bc9BS
aaC400000001905800031909281324183a95LS
aaC60000000191f700021909281324185ac9LS
aaC4000000019ffa000119092813243313f0FS
aaC4000000019ffa000219092813243322f1BS

Open in new window

Avatar of Martin Liss
Martin Liss
Flag of United States of America image

Are you getting the file from a server? If so can your query that server for COUNT?
you probably can load the text field into a ADO Recordset object and then look for the last record to get the value. like this:

Public Function LoadText() As String
    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim connString As String, SQL As String
   
    connString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=C:\yourPath\;Extensions=asc,csv,tab,txt;"
    Set conn = New ADODB.Connection
    conn.ConnectionString = connString
    conn.Open
   
    SQL = "Select * from [source.txt]"
    Set rs = New ADODB.Recordset
    rs.Open SQL, conn, 1, 1
    If rs.EOF = False Then
        rs.MoveLast
        LoadText = rs(0)
    End If
   
    rs.Close
    Set rs = Nothing
    conn.Close
    Set conn = Nothing
End Function

Open in new window

To implement:

Sub test()
    Dim v As String
    v = LoadText()
    Debug.Print v
End Sub

Open in new window

I tested this with a 9999 record dummy file and it's pretty fast for me.

User generated image
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Bob Schneider

ASKER

Awesome.  Very nicely done (and no, the, file is on the local machine...not a server.)
Thank you both!