matt
matt

Reputation: 75

VBA read/search text file

I’m trying to read a text file that has 1147 lines. The code below is only reading lines 1050-1147. My goal is to read the entire file and pull out the specific values located on various lines to use within a script. An example would be the value 2 from the line containing “BlockList: 2”. I've included a snippet of the format of the text file as it's formatted differently than any example that I've come across (lines 1116-1128); The values I'm trying to access are indented the same as the first line shown (not sure if that matters).

    fixation.OffsetTime: 426611
    *** LogFrame End ***
Level: 2
*** LogFrame Start ***
Procedure: TestProc
BlockList: 2
BlockList.Cycle: 1
BlockList.Sample: 2
Running: BlockList
*** LogFrame End ***

Level: 1 * LogFrame Start * Experiment: ChoiceofLotteries_fMRI_I

The code so far:

Sub OpenTextFileTest()
    Const ForReading = 1, ForWriting = 2, ForAppending = 3
    Dim fs, f, contents, var1
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.OpenTextFile("C:\NameOfFile.txt", 1)
    contents = f.ReadAll
    f.Close
    Debug.Print contents
End Sub

Does anyone have any suggestions how to accomplish this?

Upvotes: 2

Views: 4769

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149287

Try this (An example on how to extract the value of BlockList:)

Sub Sample()
    Dim MyData As String, strData() As String
    Dim i As Long

    '~~> Replace this with the relevant file
    Open "C:\NameOfFile.txt" For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)

    For i = LBound(strData) To UBound(strData)
        If InStr(1, strData(i), "BlockList:", vbTextCompare) Then
            Debug.Print Split(strData(i), ":")(1)
            Exit For
        End If
    Next i
End Sub

FOLLOWUP

The Text file that you have is Unicode text File and hence you are getting that problem. If you do a SaveAs and then select ANSI in the encoding and then run the above code, does it work?

Click here For an alternative way of reading txt files using VBA

Upvotes: 1

Related Questions