Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
934 views
in Technique[技术] by (71.8m points)

vba - Reading data from text file and delimiting

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...