Reading data from text file and delimiting

2019-02-17 15:23发布

I have an Excel 2010 spreadsheet, and I am reading in information from a .txt file (and another .xls file in future).

This text file has 3 elements per row; firtname, surname and Job title, and each element is separated by a comma. I have the data reading and pasting into Excel, however each row is pasted into the one cell. I am looking to paste each element into different columns. I know that I should try and delimit, but I just can't figure out the syntax.

My question is how do I separate each element and paste it into it's own cell? I currently use commas to separate each element on my .txt file, but future files might use tabs, full-stops, semi-colons etc. How do I extend it so all bases are covered?

Below is my code, and under my code is a sample of dummy data

Sub FetchDataFromTextFile()
    Dim i As Long
    Dim LineText As String
    Open "C:\mytxtfile.txt" For Input As #24
    i = 2
    While Not EOF(24)
        Line Input #24, LineText
        ActiveSheet.Cells(i, 2).Value = LineText
        P = Split(Record, ",")
        i = i + 1
    Wend
    Close #24
End Sub

John, Doe, Boss

Johnny, Steele, Manager

Jane, Smith, Employee

NOTE: Competant in other programming languages, however not done VB in about 6 or 7 years. I can never seem to wrap my head around VB Syntax, so please treat me like a novice for this.

1条回答
趁早两清
2楼-- · 2019-02-17 15:38
Sub FetchDataFromTextFile()
    Dim i As Long
    Dim LineText As String
    Open "C:\mytxtfile.txt" For Input As #24
    i = 2
    While Not EOF(24)
        Line Input #24, LineText
            Dim arr
            arr = Split(CStr(LineText), ", ")
            For j = 1 To 
                ActiveSheet.Cells(i, j).Value = arr(j - 1)
            Next j
            i = i + 1
    Wend
    Close #24
End Sub

For different delimiters, make use of the answers in here

查看更多
登录 后发表回答