使用vba上的选项卡拆分文本

时间:2018-06-19 10:24:45

标签: vba split tabs

我读过一个包含100多列的文本文件,用制表符分隔。此代码将每一行的一行读入一个字符串。如何将所有行导入不同的列(我必须对大约100个文件执行此过程)。

Sub reader()

Dim filePath As String
Dim text As String
Dim x As Integer
filePath = "C:\Users\Squirrel\Desktop\CodePack\account_inf.txt"

Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)

Do While Not txtStream.AtEndOfStream
    text = txtStream.ReadLine
    x = x + 1
    Cells(x, 1).Value = Left(text, 1)
Loop
txtStream.Close

End Sub

3 个答案:

答案 0 :(得分:1)

使用您的代码,您必须构建一个程序,通过选项卡分割字符串并将值写入其他列:

Cells(1, 1) = "ah" & vbTab & "kakva si!" & vbTab & _
                "antilopa" & vbTab & "Gazella"

在范围内写入ah kakva si! antilopa Gazella(" A1"),然后将其拆分为其他列,如下所示:

enter image description here

Sub TestMe()

    Cells(1, 1) = "ah" & vbTab & "kakva si!" & vbTab & _
                    "antilopa" & vbTab & "Gazella"

    Dim wholeString As Variant
    wholeString = Split(Cells(1, 1), vbTab)

    Dim i As Long
    For i = LBound(wholeString) To UBound(wholeString)
        Cells(1, i + 1) = wholeString(i)
    Next i

End Sub

答案 1 :(得分:0)

如果您使用QueryTables.Add并设置属性TextFileTabDelimiter = True,则最好导出按标签分割的文本文件:

Sub TestMe()

    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\Squirrel\Desktop\CodePack\account_inf.txt", Destination:=Range("A1"))
        .CommandType = 0
        .Name = "SomeName"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 65001
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

答案 2 :(得分:0)

您可以使用以下命令打开制表符分隔文件:

@Query(value = "SELECT count(1) FROM que_table que " +
            "WHERE que.CREATED_DATE >= (SELECT CREATED_DATE " +
            "   FROM que_table " +
            "   WHERE id = :selectedId " +
            "   ORDER BY CREATED_DATE DESC LIMIT 1) " +
            "AND que.QUEUE_STATUS in (:queueStatuses)", nativeQuery = true)
    Long countCurrentPosition(@Param("selectedId ") String selectedId , @Param("queueStatuses") Set<QueueStatus> queueStatuses);

更多信息: