簡體   English   中英

將txt文件導入excel,並用文本到列進行格式化

[英]Import a txt file into excel and format with text to column

我試圖通過 VBA 代碼將 .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 列中,並為每個新行添加帳戶。

幫助?

(編輯:我想在遇到空數組選擇時向下移動一行,但每行中有很多空格,這不起作用。此外,行的長度根據內容不一致。)

您需要以兩種方式拆分數據:使用 NewLine 字符拆分為行,然后使用|拆分為單元格|

請注意,在你的文本文件中的換行符chacter可能不vbNewLine 如果這段代碼沒有分成幾行,那就是第一個要查看的地方。

要按照提出的方式完成您的代碼,請嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM