2013-01-17 95 views
2

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

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

等级:1 *逻辑框架开始* 实验: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 

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

回答

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

+0

嗨亚洲时报Siddharth的另一种方式,感谢您的快速反应。我运行了脚本,没有任何内容显示在Debug.Print Split(strData(i),“:”)(1)行的即时窗口中。我在Get#1,MyData这一行后面加入了Debug.Print MyData行,看起来它仍然只读取了第1050-1147行。另一个问题也浮现在脑海里。如果这是一个Excel文件并且“标题”下的值在整个文本文件中改变,名称BlockList将是一个标题。我试图弄清楚如何获取阻塞列表值1,阻塞列表值2等。 – matt

+0

数据是否实际上由换行符分隔?任何机会我可以看到txt文件? –

+0

在此行之前'Debug.Print Split(strData(i),“:”)(1)'把这行写成'Debug.Print strData(i)'你有什么东西吗? –