2017-07-06 71 views
0

我是VBA的新用戶,並嘗試讀取大小很大的文本文件。有時也有一些MB的文本文件。使用VBA讀取和處理文本文件的問題

數據由打印結果和不同時間戳的某個數字組成。

時間戳,其中我需要存儲的值如下:

STEP時間內完成1.00,TOTAL的時間內完成1.00

然後,將印刷數據如下:

90000354 1  -3.9630E-02 -3.5410E-02 -0.2695  0.4523  2.424  0.5630 

現在,我想查找數字90000354,並需要將這些數字-3.9630E-02,-3.5410E-02 & -0.2695複製並粘貼到Excel表格中。現在,我正在使用下面的代碼,但它給出了問題。請幫助解決這個問題。

非常感謝提前。

Option Explicit 

Private Sub CommandButton1_Click() 

Dim text As String, MyData As String, strData() As String, myFile As String, textLine As String 

Dim v As Variant 

Dim numIde As Long, i As Long 

myFile = Application.GetOpenFilename("Dat Files (*.dat), *.dat") 

Open myFile For Input As #1 

MyData = Space$(LOF(1)) 

Do Until EOF(1) 

    Line Input #1, textLine 

    MyData = MyData & textLine & vbCrLf 

Loop 

Close #1 

strData() = Split(MyData, vbCrLf) 

numIde = 90000354 

For i = LBound(strData) To UBound(strData) 

    If InStr(1, strData(i), numIde, vbTextCompare) Then 

     Cells(2, 2).Value = Mid(numIde, numIde + 20, 11) 

     Cells(2, 3).Value = Mid(numIde, numIde + 32, 11) 

     Cells(2, 4).Value = Mid(numIde, numIde + 44, 11) 

     Exit For 
    End If 
Next i 

末次

運行代碼結束了一個錯誤,如下所示:

「運行時錯誤‘54’:錯誤的文件模式」

嘗試調試雖然,它停在此代碼行「Get#1,,MyData」

+0

尼斯問題,但你需要提供在那裏給人的問題,如果你可以在更明確什麼樣的錯誤你得到,當這將幫助別人解答 –

+0

謝謝您的建議@Gary文思信息。我忘了在運行代碼後添加輸出。錯誤是「運行時錯誤」54':錯誤的文件模式「。在嘗試調試時,它正停在此代碼行「Get#1,,MyData」。 –

回答

0

Get用於讀取二進制數據,並且您想要讀取文本。使用Line Input

編輯:更新 - 這應該會更好。閱讀每一行,然後檢查它。省去了與可能或可能無法識別vbCRLF,取決於OS等

做這樣的事情的split功能打擾:

私人小組CommandButton1_Click()

Dim text As String, MyData As String, strData() As String, myFile As String 
Dim numIde As Integer 
Dim i As Long 

numIde = 90000354 
myFile = Application.GetOpenFilename("Dat Files (*.dat), *.dat") 

Open myFile For Input As #1 

Do Until EOF(1) 
    Line Input #1, textline 
    If InStr(1, textline, numIde, vbTextCompare) Then 
     Cells(2, 2).Value = Mid(textline, numIde + 20, 11) 
     Cells(2, 3).Value = Mid(textline, numIde + 32, 11) 
     Cells(2, 4).Value = Mid(textline, numIde + 44, 11) 
    End If 
Loop 
Close #1 

如果你喜歡它的完成方式,那麼我之前發佈的代碼存在一些小問題。它是將每行文本附加到單個字符串中,而不是將其添加爲新行,因此Split()函數不起作用。這裏更新的代碼應該可以工作。

Do Until EOF(1) 
Line Input #1, text 
    MyData = MyData & text & vbCrLf '<-need to append the vbCRLF 
Loop 
Close #1 
strData = Split(MyData, vbCrLf) 
+0

謝謝。實施修改後,現在沒有錯誤。但輸出是空白的。請幫忙。 –

+0

再次感謝@ainwood。我修改了代碼,但是現在出現了一個新的錯誤:「運行時錯誤」9:下標超出範圍「彈出。如果試圖進行調試,它會指出「If」循環(代碼底部的第6條生命)。好心檢查。 –

+0

請使用修改後的代碼更新您的文章。 Instr()不應該給下標超出範圍錯誤。我看到一個錯誤,我把中間代碼 - 將文本更改爲文本行。 – ainwood