2014-11-01 202 views
1

我試圖通過VBA代碼將.txt文件導入到Excel中,然後使用文本格式將內容格式化爲列命令。將txt文件導入excel並將文本格式化爲列

TXT文件保存在下面的內容:

DATE | 1 | 2 | 3 | 4 | Something ||||| Not Sure ||||| 
DATE | 5 | 6 | 7 | 8 | New ||||| Whatever ||||| 

目前,使用代碼我發現和抨擊在一起,我已經成功地走到這一步

Sub Sample() 
    Dim MyData As String, strData() As String, myFile As String 

    myFile = Application.GetOpenFilename() 

    Open myFile For Binary As #1 
    MyData = Space$(LOF(1)) 
    Get #1, , MyData 
    Close #1 
    strData() = Split(MyData, "|") 


End Sub 

這僅僅得到來自txt文件的所有數據並將每個項目分隔成一個數組。

我想將數組中的項目放入從Range(「A5」)開始的excel列和每個新行的帳戶。

幫助? (編輯:我想在任何時候,我得到一個空的數組選擇,但每行內有很多空白,這是行不通的。而且,行的長度是不一致的,取決於內容。)

+0

你正在處理_Text_文件任何特別的原因作爲_Binary_? – 2014-11-01 00:41:17

+0

沒有理由,除了天真地嘗試的東西 – jchemp 2014-11-03 17:32:42

回答

2

您需要兩種方式分割數據:使用|

注到使用換行符線,然後進入細胞,在文本文件中的換行符chacter可能不vbNewLine。如果這段代碼沒有分成幾行,這就是第一個看到的地方。

爲了方便您的代碼poseted,嘗試

Sub Sample() 
    Dim MyData As String 
    Dim lineData() As String, strData() As String, myFile As String 
    Dim i As Long, rng As Range 

    ' lets make it a little bit easier for the user 
    myFile = Application.GetOpenFilename("Text Files (*.txt), *.txt") 

    Open myFile For Binary As #1 
    MyData = Space$(LOF(1)) 
    Get #1, , MyData 
    Close #1 
    ' Split into wholes line 
    lineData() = Split(MyData, vbNewLine) 
    Set rng = Range("A5") 
    ' For each line 
    For i = 0 To UBound(lineData) 
     ' Split the line 
     strData = Split(lineData(i), "|") 
     ' Write to the sheet 
     rng.Offset(i, 0).Resize(1, UBound(strData) + 1) = strData 
    Next 
End Sub 

作爲替代,治療中的.txt文件,以及,文本

Sub Sample() 
    Dim fn As Integer 
    Dim MyData As String 
    Dim lineData As String, strData() As String, myFile As String 
    Dim i As Long, rng As Range 

    myFile = Application.GetOpenFilename("Text Files (*.txt), *.txt") 

    Set rng = Range("A5") 

    ' Lets not rely on Magic Numbers 
    fn = FreeFile 
    Open myFile For Input As #fn 
    i = 1 
    Do While Not EOF(fn) 
     Line Input #fn, lineData 
     strData = Split(lineData, "|") 
     rng.Cells(i, 1).Resize(1, UBound(strData) + 1) = strData 
     i = i + 1 
    Loop 
    Close #fn 
End Sub 
相關問題