Search code examples
excelvbafilesystemobject

Using File System Object to read a line


I have a textbox where people insert an abbreviated word to search for it's whole meaning.

The search is being done in a database that is a txt file. I am using the File System Object to do so.

When a word is searched and found in the text file, I need to return the string from the next line, that is, the meaning. Take a look at the txt format below:

MS

Microsoft

SO

StackOverflow

How can I do that?

Thanks!!!


Solution

  • You match against the current line so

    if (oFS.ReadLine = search_text) then checks for a match

    and then if that's true then

    Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = oFS.ReadLine

    jumps to the next line and saved it in your column A

    Set oFS = oFSO.OpenTextFile(filePath)
    Do While Not oFS.AtEndOfStream
        if (oFS.ReadLine = search_text) then
            Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = oFS.ReadLine
        end if
    Loop
    oFS.Close