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

前端 未结 1 660
情歌与酒
情歌与酒 2021-01-25 07:52

I am attempting to import a .txt file into Excel via VBA code and then format the content with a text to column command.

The txt file holds content in the following:

1条回答
  •  梦毁少年i
    2021-01-25 08:33

    You need to Split the data two ways: into lines using the NewLine character, then into cells using |

    Note that the line break chacter in your text file may not be vbNewLine. If this code doesn't split into lines, thats the first place to look.

    To complete your code as poseted, try

    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
    

    As an alternative, treat the .txt file as, well, Text

    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
    

    0 讨论(0)
提交回复
热议问题