TextToColumns函数使用错误的分隔符
我想打开一个目录中的所有csv(分隔符是分号)文件,这是我认为应该工作的代码:
Sub test() Dim MyFile As String Dim MyDir As String MyDir = Application.ActiveWorkbook.Path MyFile = Dir(MyDir & "\" & "*.csv") 'set current directoy ChDir MyDir Application.ScreenUpdating = 0 Application.DisplayAlerts = 0 Do While MyFile <> "" Workbooks.Open (MyFile) 'Parse it using semicolon as delimiters Range(Range("A1"), Range("A1").End(xlDown)).TextToColumns _ DataType:=xlDelimited, _ ConsecutiveDelimiter:=False, Tab:=False, _ Semicolon:=True, Comma:=False, Space:=False, Other:=False ' 'next file in directory MyFile = Dir() Loop End Sub
但奇怪的是,它也使用逗号作为分隔符。 我可以看到,如果我debuggingTextToColumns
行。
所以对于一个CSV文件
test;test,test
我会期待一个输出
test test,test
但我真的得到了
test test
为什么? 我的Excel设置有什么问题吗?
谢谢!
问题是这条线
Workbooks.Open (MyFile)
在Excel中打开文件的那一刻,将以这种格式打开,因为它是逗号分隔文件
然后当.TextToColumns
代码运行时,它将使用.TextToColumns
的“testing”replace列B
数据;
在列A
。
尝试这个
假设你的csv文件看起来像这样
现在试试这个代码。 一旦你明白它是如何工作的,只需在你的代码中调整它。 我已经评论了代码,以便您不会理解它。
Sub Sample() Dim wb As Workbook, ws As Worksheet Dim MyData As String, strData() As String Dim myFile As String Dim lRow As Long '~~> Replace this with your actual file myFile = "C:\Users\Siddharth\Desktop\test.csv" '~~> open text file in memory and read it in one go Open myFile For Binary As #1 MyData = Space$(LOF(1)) Get #1, , MyData Close #1 strData() = Split(MyData, vbCrLf) '~~> Add a new workbook Set wb = Workbooks.Add '~~> Work with the 1st sheet Set ws = wb.Sheets(1) With ws '~~> Copy the array to worksheet .Range("A1").Resize(UBound(strData), 1).Value = strData '~~> get the last row of the data lRow = .Range("A" & .Rows.Count).End(xlUp).Row '~~> Use text To columns now .Range("A1:A" & lRow).TextToColumns DataType:=xlDelimited, _ ConsecutiveDelimiter:=False, _ Tab:=False, _ Semicolon:=True, _ Comma:=False, _ Space:=False, _ Other:=False ' End With End Sub
这就是你得到的
编辑 :你有另一个选项是重命名CSV文件,然后打开build议打开CSV文件由pipe道字符“|”分隔或不是通用的分隔符