TextToColumns函数使用错误的分隔符

时间:2015-06-09 07:24:12

标签: excel excel-vba csv vba

我正在尝试打开目录中的所有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

但奇怪的是,它也使用逗号作为分隔符。如果我调试TextToColumns行,我可以看到。

所以对于像

这样的csv文件
test;test,test

我希望输出

test    test,test

但实际上我得到了

test    test

为什么呢?我的Excel设置有问题吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

问题在于这一行

 Workbooks.Open (MyFile)

当您在Excel中打开文件时,它将以此格式打开,因为它是逗号分隔文件

enter image description here

然后当.TextToColumns代码运行时,它会使用&#34; test&#34;替换列B数据。在;列中A之后。

试试这个

让我们说你的csv文件看起来像这样

enter image description here

现在试试这段代码。一旦了解了它的工作原理,只需在代码中进行调整即可。我已对代码进行了评论,以便您在理解代码时不会遇到任何问题。

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

这就是你得到的

enter image description here

编辑:您拥有的另一个选项是重命名csv文件,然后按照Open csv file delimited by pipe character “|” or not common delimiter

中的建议打开它