【问题标题】:VBA read/search text fileVBA 读取/搜索文本文件
【发布时间】:2013-09-12 19:43:26
【问题描述】:

我正在尝试读取一个有 1147 行的文本文件。下面的代码仅读取第 1050-1147 行。我的目标是读取整个文件并提取位于不同行的特定值以在脚本中使用。例如,包含“BlockList: 2”的行中的值 2。我已经包含了文本文件格式的 sn-p,因为它的格式不同于我遇到的任何示例(第 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

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

【问题讨论】:

    标签: vba excel


    【解决方案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 文本文件,因此您遇到了这个问题。如果你做一个SaveAs,然后在编码中选择ANSI,然后运行上面的代码,能行吗?

    点击here查看reading txt files using VBA的替代方式

    【讨论】:

    • 嗨,悉达多,感谢您的快速回复。我运行了脚本,但根据 Debug.Print Split(strData(i), ":")(1) 行,即时窗口中没有显示任何内容。我在 Get #1, , MyData 行之后包含了 Debug.Print MyData 行,看来它仍然只读取第 1050-1147 行。另一个问题也浮现在脑海。如果这是一个 excel 文件,并且“标题”下的值在整个文本文件中发生变化,则名称 BlockList 将是一个标题。我正在尝试弄清楚如何获取例如阻止列表值一、阻止列表值二等。
    • 数据是否真的用换行符分隔?我有机会看到 txt 文件吗?
    • 同样在这行之前Debug.Print Split(strData(i), ":")(1)把这行Debug.Print strData(i)你得到什么了吗?
    • 插入语句后仍然没有。如果你愿意,我可以把文件发给你。我似乎无法在您的个人资料中找到电子邮件。
    • 你可以上传到 www.wikisend.com 并在这里分享链接:)
    猜你喜欢
    • 1970-01-01
    • 2011-07-03
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多