从 VBA 中的文本文件中提取信息

Extracting information from text file in VBA

我目前正在尝试从文本文件中提取数据,作为我工作场所分析挑战的一部分。文本文件是一堆数据,每行 heading/entry 用逗号分隔。

我看过几个在线文本提取示例,但我得到的最多的是在单个单元格中提取一行,然后 Excel 冻结。其他人在我提出条件后都冻结了Excel

我目前的尝试包括以下内容:

Do Until EOF #1, textLine
Line Input #1, textLine

    Do Until Count = Len(text line) + 1
    Text = Text & Mid(textLine, Count, Count)
    If Right(text, 1) = "," Then
    textImport = Left(text, Count - 1)
    Cells(rowCount, column count) = textImport
    Text = ""
     columnCount = columnCount + 1
    Loop

    rowCount = rowCount + 1

Loop

谁能告诉我哪里出错了?由于挑战的性质和涉及的数据,我无法共享任何数据或文本文件。

查询表导入

你可以这样做:

Sub QueryImport()

    Const cSheet As Variant = "Sheet1"  ' Worksheet Name/Index
    Const cSource As String = "A1"      ' Source Range

    Dim vntFile As Variant  ' Source Array

    vntFile = Application.GetOpenFilename("Text Files (*.txt), *.txt")

    If vntFile <> False Then
        With ThisWorkbook.Worksheets(cSheet).QueryTables _
                .Add(Connection:="TEXT;" & vntFile, _
                Destination:=ThisWorkbook.Worksheets(cSheet).Range(cSource))
            .Name = "Pets"
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = xlWindows
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = True
            .TextFileSpaceDelimiter = False
            .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With
    End If
End Sub

这将打开一个对话框,您可以在其中选择文件,然后将其导入 Excel,然后您可以进一步操作它,但由于缺乏信息,这超出了范围。 Post部分结果在另一题中得到想要的结果。

如果这不是可以在 Excel 中打开的 CSV,请尝试此操作。

Sub readCSVLikeFile()
    r = 1
    Open "<path of the file> For Input As #1
    While Not EOF(1)
        Line Input #1, txtline
        v = Split(txtline, ",")
        Range(Cells(r, 1), Cells(r, UBound(v) + 1)) = v
        r = r + 1
    Wend
    Close #1

End Sub