Reading data from text file and delimiting

梦想与她 提交于 2019-11-28 04:19:53

问题


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:


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



来源:https://stackoverflow.com/questions/16668090/reading-data-from-text-file-and-delimiting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!