2

我正在尝试读取一个包含 1147 行的文本文件。下面的代码仅读取第 1050-1147 行。我的目标是读取整个文件并提取位于不同行的特定值以在脚本中使用。一个示例是包含“BlockList: 2”的行中的值 2。我已经包含了文本文件格式的片段,因为它的格式与我遇到的任何示例都不同(第 1116-1128 行);我试图访问的值的缩进与显示的第一行相同(不确定这是否重要)。

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

级别:1 * LogFrame 开始 * 实验:ChoiceofLotteries_fMRI_I

到目前为止的代码:

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

有没有人有任何建议如何做到这一点?

4

1 回答 1

1

试试这个(关于如何提取值的示例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

跟进

您拥有的文本文件是Unicode文本文件,因此您遇到了这个问题。如果你在编码中做aSaveAs然后选择ANSI然后运行上面的代码,它可以工作吗?

单击此处了解使用 VBA 读取 txt 文件的另一种方法

于 2013-01-17T19:59:05.217 回答