VBA将分隔符文本文件转换为Excel

我有一个代码,将文件从.txt(带有“|”分隔符)文件转换为xslx,但代码工作正常的一些文件(当我打开它在Excel中),其他人是错误的,当我尝试导入通过excelfunction区(获取外部数据 – >从文本)手动拧紧,文件是正确的。

这是我的代码:

Sub tgr() Const txtFldrPath As String = "C:\...\txtFiles" Const xlsFldrPath As String = "C:\excelFiles" Dim CurrentFile As String: CurrentFile = Dir(txtFldrPath & "\" & "*.txt") Dim strLine() As String Dim LineIndex As Long Application.ScreenUpdating = False Application.DisplayAlerts = False While CurrentFile <> vbNullString LineIndex = 0 Close #1 Open txtFldrPath & "\" & CurrentFile For Input As #1 While Not EOF(1) LineIndex = LineIndex + 1 ReDim Preserve strLine(1 To LineIndex) Line Input #1, strLine(LineIndex) Wend Close #1 With ActiveSheet.Range("A1").Resize(LineIndex, 1) .Value = WorksheetFunction.Transpose(strLine) .TextToColumns Other:=True, OtherChar:="|" End With ActiveSheet.UsedRange.EntireColumn.AutoFit ActiveSheet.Copy ActiveWorkbook.SaveAs xlsFldrPath & "\" & Replace(CurrentFile, ".txt", ".xlsx"), xlOpenXMLWorkbook ActiveWorkbook.Close False ActiveSheet.UsedRange.ClearContents CurrentFile = Dir Wend Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub 

在这里输入图像说明 这张图片显示了excel和原始文件.txt的结果

首先,你有不好的数据。 总负债AI060616.txt中的30,619,676.00之间有一个制表符。 Excel不喜欢单元格内容中的选项卡。 实际上,Tab字符是TextToColumns命令的默认分隔符,当数组被引入时,这将转换为两列数据。

  Open txtFldrPath & "\" & CurrentFile For Input As #1 While Not EOF(1) LineIndex = LineIndex + 1 ReDim Preserve strLine(1 To LineIndex) Line Input #1, strLine(LineIndex) 'STRIP TABS OUT AND REPLACE WITH A SPACE!!!!! strLine(LineIndex) = Replace(strLine(LineIndex), Chr(9), Chr(32)) Wend Close #1 

接下来, Range.TextToColumns方法 “记住”上次运行时使用的所有设置; 无论是用户在工作表上还是通过VBA都无关紧要。 您需要比您提供的参数多得多的参数,以保证它将以您想要的方式运行。

  With ActiveSheet.Range("A1").Resize(LineIndex, 1) .Value = WorksheetFunction.Transpose(strLine) 'DEFINE THE OPERATION FULLY!!!! .TextToColumns Destination:=.Cells(1), DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _ Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _ Other:=True, OtherChar:="|" End With 

import_TXT

虽然我还不明白解决scheme/问题,但是如果您应用两次.TextToColumns方法,似乎解决了这个问题。

 With ActiveSheet.Range("A1").Resize(LineIndex, 1) .Value = WorksheetFunction.Transpose(strLine) .TextToColumns Other:=True, OtherChar:="|" .TextToColumns Other:=True, OtherChar:="|" End With 

也许别人可以澄清这是为什么。 虽然这通常不是我通常提供的职位,但上面应该给你一个解决方法,而其他人提出一个更好的解决scheme(包括解释)。

文件AI150616在“B”列中具有数据30,619,676.00 Net worth = ZAR 83,456,466.00 Hence, final required BG should be (63,503,915.82)
在这里输入图像说明 分隔符只能用于一列。 这应该是可以允许的吗? 如果不是,则可能需要另外的程序来检查数据是否正确,如果是的话,附加它,否则警告用户数据已经以某种方式受到损害。