1

Need to create text files from excel rows. Column 1 should include the file names and column 2 the content of the text files. Each row will have either new file name or new content for that new text file. Also, the content of the text should be split into several lines. How to accomplish this? Thank you.

1
  • 2
    So - what you have you tried so far? Commented Jan 18, 2013 at 9:05

1 Answer 1

2

Edited solution with text separation to lines.

For the sample the following chars are used:

;:,/|

Add new separators to RegEx pattern as required. Full code is below:

Sub Text2Files()

Dim FileStream As Object
Dim FileContent As String
Dim i As Long
Dim SavePath As String
Dim RegX_Split As Object

Set RegX_Split = CreateObject("VBScript.RegExp")
RegX_Split.Pattern = "[\;\:\,\\\/\|]" 'List of used line seperators as \X
RegX_Split.IgnoreCase = True
RegX_Split.Global = True

Set FileStream = CreateObject("ADODB.Stream")
SavePath = "D:\DOCUMENTS\" 'Set existing folder with trailing "\"

For i = 1 To ThisWorkbook.ActiveSheet.Cells(1, 1).CurrentRegion.Rows.Count

    FileContent = RegX_Split.Replace(ThisWorkbook.ActiveSheet.Cells(i, 2).Text, vbNewLine)
    FileStream.Open
    FileStream.Type = 2 'Text
    FileStream.Charset = "UTF-8" 'Change encoding as required
    FileStream.WriteText FileContent
    FileStream.SaveToFile SavePath & ThisWorkbook.ActiveSheet.Cells(i, 1).Text, 2 'Will overwrite the existing file
    FileStream.Close

Next i

End Sub
  1. Read more about ADO Stream Object: http://www.w3schools.com/ado/ado_ref_stream.asp
  2. RegEx for beginners: http://www.jose.it-berater.org/scripting/regexp/regular_expression_syntax.htm

Sample file with the above code is here: https://www.dropbox.com/s/kh9cq1gqmg07j20/Text2Files.xlsm

Sign up to request clarification or add additional context in comments.

7 Comments

About the line separator, i mean the Text Contents 1 may be split in the actual output file into several lines, e.g.: Text Contents 1 How would I add the line breaks here in between the text? Thank you so much!
@HenryTheLeast which character is used as a new line separator? Space? Comma? or a list of chars?
It can be any character. I am willing to punch in any character to separate the lines, except comma, period or space. Thanks.
@HenryTheLeast with your request RegEx expression is the only flexible solution))) But it will cost a bit - not an immediate solution for me. Will get back to that during the weekend. In case some more requests are coming - feel free to post here!
@HenryTheLeast I'm not sure whether you're notified about answer edits, but the updated solution is above.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.