2016-06-22 121 views
0

我想通過VBA將文本文件導入到Excel中,但經過大量搜索和測試後,我似乎無法弄清楚如何格式化它,因爲我想要。從文本文件導入特定文本到excel表

這裏的文本文件的一部分:

^USER ADDRESS 
User's name 
Street address 
Postal code and town 
^USER ORDER NUMBER 
Order number 
^AND SO ON..... 

導入時,我希望它格式化這樣的:

^USER ADDRESS | User's name | Street address | Postal code and town 
^USER ORDER NUMBER | Order number 
^AND SO ON .... 

這是我的腳本這麼遠。它複製包含^ USER的行並將其粘貼 - 但我需要它複製每個^下面的行,直到下一個^。

Private Sub DatafrmTxt() 

Dim myFile As String, text As String 
Dim F As Long 
Dim x As Integer 

myFile = "C:\test.txt" 

F = FreeFile 
x = 1 

Open myFile For Input As F 
Do Until EOF(F) 
Line Input #F, text 

If InStr(text, "^USER ") > 0 Then 
Range("A" & x).Value = text 
x = x + 1 
End If 
Loop 
Close F 

End Sub 

回答

1

這應該做的工作。當您的.txt文件的下一行是不是一個「頭」,然後在相鄰列粘貼到x

Private Sub DatafrmTxt() 

Dim myFile As String, text As String 
Dim F As Long 
Dim x As Integer, col As Integer 

myFile = "C:\test.txt" 

F = FreeFile 
x = 1 

Open myFile For Input As F 
Do Until EOF(F) 
Line Input #F, text 

    If InStr(text, "^USER ") > 0 Then 
     Range("A" & x).Value = text 
     x = x + 1 
     col = 2 
    Else 
     Cells(x, col).Value = text 
     col = col + 1 
    End If 

Loop 

End Sub 
1

這樣的事情也許會有幫助,我沒有得到正確的文件,所以試了一下使用HTML標記的HTML,它可能需要一些調整。它使用腳本運行時參考

Sub TestTextStream() 

Dim f As Scripting.FileSystemObject 
Dim t As Scripting.TextStream 
Dim lngRow As Long 
Dim intXshift As Integer 

Set f = New Scripting.FileSystemObject 

Set t = f.OpenTextFile("c:\test\JavascriptAccordian.txt", ForReading) 

lngRow = 1 

While Not t.AtEndOfStream 

    If Left(t.ReadLine, 1) = "^" Then 
     intXshift = 0 
     lngRow = lngRow + 1 
     Range("a" & lngRow).value = t.ReadLine 
    Else 
     Range("b" & lngRow).Offset(0, intXshift).value = t.ReadLine 
     intXshift = intXshift + 1 
    End If 

Wend 

Set t = Nothing 
Set f = Nothing 

End Sub