vba 从文本文件中读取数据并定界

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16668090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:39:23  来源:igfitidea点击:

Reading data from text file and delimiting

excelvbaexcel-vbatext-filesdelimited-text

提问by

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

我有一个 Excel 2010 电子表格,我正在从 .txt 文件(以及将来的另一个 .xls 文件)中读取信息。

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.

这个文本文件每行有 3 个元素;姓名、姓氏和职务,每个元素之间用逗号分隔。我将数据读取并粘贴到 Excel 中,但是每一行都粘贴到一个单元格中。我希望将每个元素粘贴到不同的列中。我知道我应该尝试分隔,但我无法弄清楚语法。

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?

我的问题是如何分离每个元素并将其粘贴到它自己的单元格中?我目前使用逗号来分隔 .txt 文件中的每个元素,但未来的文件可能会使用制表符、句号、分号等。如何扩展它以便涵盖所有基础?

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.

注意:在其他编程语言中胜任,但在大约 6 或 7 年内没有完成 VB。我似乎永远无法理解 VB 语法,所以请把我当作新手。

采纳答案by

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

对于不同的分隔符,请使用此处的答案