Go Premium for a chance to win a PS4. Enter to Win

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 781
  • Last Modified:

vb macro reading from txt file in excel


I have a macro that reads data from a log file into excel but I want it to only add records
to the excel sheet rows ontop the records that already exist in the sheet, how can i ensure only new records get added if they are unique

below is my current code which merely overwrites, I have attached the txt file and the excel sheet for test purposes

Sub ReadFile()
Dim FF As Integer
Dim strData As String
Dim strParts() As String
Dim lngRow As Long
' A one-line heading is assumed.
lngRow = 1

' Get the first unused file number
FF = FreeFile

' Open the file for reading
Open "C:\temp\output.txt" For Input As #FF

' Read the reacords until end of file
Do While Not EOF(FF)
    lngRow = lngRow + 1
    ' Read one line at a time into strData
    Line Input #FF, strData
    ' Split the data at the comma
    strParts = Split(strData, ",")
    ' Place the data in columns A to B.
    Cells(lngRow, 1) = strParts(0)
    Cells(lngRow, 2) = strParts(1)

' Close the file
End Sub

fyi, the output file is a text file that goes and adds entries on a periodic basis hence me wanting to add only new entries

1 Solution

* Your imported example does not match the worksheet contents.
* Your sample files do not seem to show the duplicates scenario you described, since they are entirely duplicates.
Michael FowlerSolutions ConsultantCommented:
Your code appears to place the log files into excel in date order ascending. Is this correct?

I would read the last entry of the current excel sheet to get the date.
Then read through the log file until you get to line where the datetime in the log is greater than or equal to the last excel entry AND the message in the log is different to the message in excel.
Once this is true you can start adding the lines to excel.

If you are trying to add entries at the top of the file you will need to insert a line before adding the value

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now