TextToColumns function uses wrong delimiter

前端 未结 1 1264
醉梦人生
醉梦人生 2021-01-25 01:00

I am trying to open all csv (separator is semicolon) files in a directory and this is the code that I think should work:

Sub test()
Dim MyFile As String
Dim MyDi         


        
相关标签:
1条回答
  • 2021-01-25 01:12

    The problem is with this line

     Workbooks.Open (MyFile)
    

    The moment you open the file in Excel, it is opened in this format as it is a Comma Delimited File

    enter image description here

    And then when the .TextToColumns code runs it replaces Column B data with the "test" which is after ; in Column A.

    Try this

    Let's say your csv file looks like this

    enter image description here

    Now try this code. Once you understand how it works, simply adapt this in your code. I have commented the code so that you will not have a problem understanding it.

    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
    

    And this is what you get

    enter image description here

    EDIT: The other option that you have is to rename the csv file and then open it as suggested in Open csv file delimited by pipe character “|” or not common delimiter

    0 讨论(0)
提交回复
热议问题