2014-02-19 70 views
0

我被困在這個問題的時刻...我有以下文本文件格式(來自電子郵件,應該每週自動讀入excel):逐行讀取文本文件並將某些值保存在數組中

TextTextText 
Text 
TextText 
TextTextText 

2/2 2/3 2/4 2/5 2/6 
63 61 65 67 62 
59 51 45 11 20 

11 22 41 32 55 

TextTextText 
Text 
TextText 
TextTextText 

而我只需要基本上最後一列的數據。所以數據爲2/6。現在我該如何解壓? Split對於數字行不起作用,因爲它們之間有不同的空格(前兩個,後三個之間)。開頭的文字可以有不同的長度。但總有! 35個數據行。

我的問題基本上是: 1.您如何識別它是否是數據行? 2.如何正確分割數據線?

這是我這麼遠......

Sub ReadFile() 
    Dim FSO As FileSystemObject 
    Dim FSOFile As File 
    Dim FSOStream As TextStream 

    Dim aintData(35, 1) As Integer 

    Set FSO = New FileSystemObject 
    Set FSOFile = FSO.GetFile("C:\users\mp\Desktop\Test.txt") 
    Set FSOStream = FSOFile.OpenAsTextStream(ForReading, TristateUseDefault) 
    Do While Not FSOStream.AtEndOfStream 
     Debug.Print FSOStream.ReadLine 
    Loop 

End Sub 
+0

可以使用替換功能通過更換空間,例如,一個「#」,然後使用分割和修剪。 – CRondao

回答

0

這給一試:

Sub tgr() 

    Dim oFSO As Object 
    Dim varText As Variant 
    Dim arrText() As String 
    Dim strLine As String 
    Dim strResult As String 
    Dim strFilePath As String 

    strFilePath = Application.GetOpenFilename("Text Files, *.txt") 
    If strFilePath = "False" Then Exit Sub 'Pressed cancel 

    Set oFSO = CreateObject("Scripting.FileSystemObject") 
    arrText = Split(oFSO.OpenTextFile(strFilePath).ReadAll, vbCrLf) 

    For Each varText In arrText 
     strLine = Application.Trim(varText) 
     If IsNumeric(Left(strLine, 1)) Then strResult = strResult & vbCrLf & Trim(Right(Replace(strLine, " ", String(255, " ")), 255)) 
    Next varText 

    If Len(strResult) > 0 Then 
     strResult = Mid(strResult, Len(vbCrLf) + 1) 

     'At this point strResult contains the data you want 
     'I have used a MsgBox to verify 
     'However, you could output the data in any way you see fit 
     MsgBox strResult 

     'To put the result in an array, simply re-purpose arrText: 
     arrText = Split(strResult, vbCrLf) 
     MsgBox Join(arrText, vbCrLf) 'Again, I used a MsgBox to test its output 
    Else 
     MsgBox "No data found" 
    End If 

End Sub 
相關問題