我有一个代码将文件夹中的文件从.txt(带" |"分隔符)转换为xslx, 但是代码适用于某些文件(当我在excel中打开它时),其他错误,当我尝试通过excel功能区(从文本获取外部数据 - >)手动导入wring时,文件是正确的
这是我的代码:
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
答案 0 :(得分:2)
首先,你有糟糕的数据。 AI060616.txt中总负债与 30,619,676.00 之间有一个制表符。 Excel不喜欢单元格内容中的选项卡。实际上,制表符是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 method'会记住'上次运行时使用的所有设置;无论是用户在工作表上还是通过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
答案 1 :(得分:1)
虽然我还不了解解决方案/问题,但如果您应用.TextToColumns
方法两次,它似乎已解决:
With ActiveSheet.Range("A1").Resize(LineIndex, 1)
.Value = WorksheetFunction.Transpose(strLine)
.TextToColumns Other:=True, OtherChar:="|"
.TextToColumns Other:=True, OtherChar:="|"
End With
也许其他人可以澄清为什么会这样。虽然这不是我通常提供的那种帖子,但上面应该给你一个解决方法,而其他人提出更好的解决方案(包括解释)。
答案 2 :(得分:1)