2013-01-17 94 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)'你有什麼東西嗎? –