VBA - Replacing commas in CSV not inside quotes

后端 未结 1 1961
生来不讨喜
生来不讨喜 2020-12-11 13:08
  Filename = Dir(Filepath & \"\\\" & \"*.csv\")
    While Filename <> \"\"
        SourceFile = Filepath & \"\\\" & Filename
        TargetFile         


        
相关标签:
1条回答
  • 2020-12-11 13:30

    How about something along the line of:

    objOut.Write Mid(Replace(Replace(arrData,""",""", "#|#"), Chr(34), ""), 2)
    

    Basically, this exchanges now "," for #|#. But that's not enough as the file begins with a ". So, this one is being eliminated using the Mid() function. If the file also ends with a " then you would have to adjust that as well.

    Based on the speed concerns noted in the comments here is the complete code which I used to test this solution:

    Option Explicit
    Option Compare Text
    
    Public Sub ConvertFile()
    Dim lngRowNumber As Long
    Dim strLineFromFile As String
    Dim strSourceFile As String
    Dim strDestinationFile As String
    
    strSourceFile = "C:\tmp\Extract.txt"
    strDestinationFile = "C:\tmp\Extract_b.txt"
    
    Open strSourceFile For Input As #1
    Open strDestinationFile For Output As #2
    
    lngRowNumber = 0
    
    Do Until EOF(1)
        Line Input #1, strLineFromFile
        strLineFromFile = Mid(Replace(strLineFromFile, """,""", "#|#"), 2)
        Write #2, strLineFromFile
        strLineFromFile = vbNullString
    Loop
    
    Close #1
    Close #2
    
    End Sub
    

    The tested file was 350 MB with a bit over 4 million rows. The code completed in less than a minute.

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