Tuesday, December 25, 2012

VBA String Manipulations - Replace LineFeeds With Carriage Returns In Flat Text Files


Sub ReplaceLineFeedsWithCarriageReturnsInFlatTextFiles()

'_______________________________________________
'
' This macro for either Word or Excel replaces the linefeeds of a
' flat text file by carriage returns and line feeds recognized by Word
'_______________________________________________
'
Const ForReading = 1, ForWriting = 2, ForAppending = 8

Set fso = CreateObject("Scripting.FileSystemObject")
Set Readfile = fso.OpenTextFile("C:\myDirtyFileWithLineFeeds.txt", ForReading)
thisTxt = Readfile.ReadAll
Readfile.Close
 
thisTxt = Replace(thisTxt, vbCr, vbCrLf)
thisTxt = Replace(thisTxt, vbLf, vbCrLf)

Set WriteFile = fso.CreateTextFile("C:\myCleanFileWithCarriageReturnsAndLineFeeds.txt", ForWriting, True)
WriteFile.Write (thisTxt)
WriteFile.Close
MsgBox "Job done"

End Sub

No comments:

Post a Comment

You may comment or show me other VBA tricks, but don't rest assured I'll always reply because I only have 24 hours in a day's hard work, and only a few minutes a week to update this blog... I'll try my best though...