Home » excel » excel – Convert to text using VB-macro (including line breaks within cells)

excel – Convert to text using VB-macro (including line breaks within cells)

Posted by: admin April 23, 2020 Leave a comment

Questions:

I would like to convert an Excel sheet into several text files. The sheet contains two columns:

  • Column A gives the names for the generated text files
  • Column B provides content – contains line breaks within cells

The conversion works using the following code, but line breaks are not imported to the text file – all text is in one line:

Private Sub CommandButton1_Click()
    Dim oTxt As Object

    For Each cell In Ark1.Range("A1:A" & Ark1.UsedRange.Rows.Count)
        ' you can change the sheet1 to your own choice    
        saveText = cell.Text
        Open "H:\Webshop_Zpider\S-solutions" & saveText & ".txt" For Output As #1
        Print #1, cell.Offset(0, 1).Text
        Close #1
    Next cell
End Sub

Can anybody help me with that?

Hi, the result of using Siddharths suggestions: line breaks are included! But all generated files are not named and saved as I wanted. All files get the name S-solutions plus content of colum A (e.g. S-solutionsS-4001-K-T.txt) and are saved in folder H:\Webshop_Zpider. However, what I want is: Filename: content of colum A (e.g.S-4001-K-T.txt) and folder H:\Webshop_Zpider\S-solutions. How can I change that? Thanks.

How to&Answers:

Replace this

Print #1, cell.Offset(0, 1).Text

with

Print #1, Replace(cell.Offset(0, 1).Value, vbLf, vbCrLf)

Also one Tip! Do not use .Text. Use .Value

Answer:

First you should Open the Textfile only ONCE and not for every Cell
Then you can do

Print #1, cell.Offset(0, 1).Text & vbnewline

For the celltext and a new line.