使用多个分隔符将txt文件parsing到Excel中

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

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

我正在遍历多个目录中的一堆文件。 以下是我正在使用的代码:

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可以是除了单个字符之外的东西吗?

逐行读取文件。 然后通过使用Replace()将多个分隔符转换为单个分隔符。 然后在公共分隔符上使用Split()

编辑#1:

这里是一些示例代码来说明。 假设我们想用+

数据如下:

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

这个macros:

 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 

会产生:

在这里输入图像说明