使用多个分隔符将txt文件解析为Excel

时间:2015-08-12 23:52:34

标签: excel vba parsing

有没有办法使用多个分隔符解析.txt文件中的数据行?具体来说,我使用VBA和QueryTables以及.TextFileOtherDelimiter方法导入.txt文件。但我的文件有不同的分隔符(例如:“:”&“=”),我想在一次传递中分开。

另外,有没有办法使用多个字符解析数据,例如“.-”或“:( tab)”?

我正在迭代多个目录中的一堆文件。这是我正在使用的代码:

For Each File In Folder.Files
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
          & File, Destination:=Range("A1"))
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 437
            .TextFileStartRow = DataStartRow
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = True
            .TextFileTabDelimiter = False
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFileOtherDelimiter = TestDataDelimiter
            .TextFileColumnDataTypes = Array(1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With
next

我的TestDataDelimiter除了单个char之外还可以吗?

1 个答案:

答案 0 :(得分:1)

逐行阅读文件。然后使用替换()将多个分隔符转换为单个分隔符。然后在公共分隔符上使用拆分()

修改#1:

以下是一些示例代码。假设我们要使用 + -

进行解析

使用以下数据:

hello+world-goodby+for-now
12+34+qwerty-poiunyt

这个宏:

Sub ParseData()
    Dim FileSpec As String, TextLine As String
    Dim RowNumber As Long
    folder = "C:\TestFolder\textfiles"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(folder)
    RowNumber = 1
    Close #1

    For Each file In folder.Files
        FileSpec = folder & "\" & file.Name
        Open FileSpec For Input As #1
        Do While Not EOF(1)
            Line Input #1, TextLine
            TextLine = Replace(TextLine, "+", "-")
            If InStr(TextLine, "-") = 0 Then
                Cells(RowNumber, 1) = TextLine
            Else
                ary = Split(TextLine, "-")
                ccol = 1
                For Each a In ary
                    Cells(RowNumber, ccol) = a
                    ccol = ccol + 1
                Next a
            End If
            RowNumber = RowNumber + 1
        Loop
        Close #1
    Next file
End Sub

将产生:

enter image description here