简体   繁体   中英

How can I merge or read csv files with line breaks / carriage return (CR) in Excel VBA?

I used very easy and practical solution from Merge CSV files using macro which reads and merges CSV files with Line command. The problem occurs if some CSV files include break lines (carriage return) then Line command reads this data into separate lines not into one.

CSV data in Excel looks like:

带有断线的CSV数据(回车)

Data in .CSV file looks like:

Name;Surname;Book Title Jan;Zitniak;"Microsoft Excel 2019 for beginners and intermediates" Tiya;Solomon;"Be happy every day in your life!" Ianis;Tillman;"Honor and the Noble Heart"

Notice: In my .CSV I use semicolon instead comma as separator. Please notice double quotes in data with break lines.

.CSV file to download here .

EDIT:

Another .CSV file with updated data to download here . Try this data please.

Thank you for any help.

Change the interim line feeds to a placeholder character and import the text file. Change the placeholder back to a line feed after it has been opened.

Option Explicit

Sub Macro1()
    Dim ff As Integer, str As String, fname As String

    fname = Environ("USERPROFILE") & "\Downloads\csv-with-carriage-return.csv"

    ff = FreeFile
    Open fname For Input As ff
    str = Input(LOF(ff), ff)
    Close ff

    str = Replace(str, Chr(32) & Chr(13) & Chr(10), Chr(124))

    ff = FreeFile
    Open fname For Output As ff
    Print #ff, str
    Close ff

    Workbooks.OpenText Filename:=fname, Origin:=65001, DataType:=xlDelimited, _
                       Semicolon:=True, Tab:=False, Comma:=False, Space:=False, Other:=False, _
                       FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2))

    With ActiveWorkbook

        .Worksheets(1).Columns(3).Cells.Replace what:=Chr(124), replacement:=Chr(32) & Chr(10)

    End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM