Samples of VBA code I'm using in my daily tasks.

Wednesday, March 10, 2010

Mass replace characters in a text file

'--------------------------------------------------------------------
' sFile - path and file name of your file
' sNewFile - new file name, can be same like old file name
' sFind - text you want to replace (can be special character like: vbCrLf)
' sReplace - new text
'
Public Sub TextFileReplace(ByVal sFile As String, ByVal sNewFile As String, ByVal sFind As String, ByVal sReplace As String)
Dim iFile As Integer
Dim sTextBuffer As String
'
' Get the next available file handle
iFile = FreeFile
' Open the source file (sFile) for read access
Open sFile For Binary Access Read As iFile
' Create a buffer that will hold the contents of the file
sTextBuffer = Space(LOF(iFile))
' Read the contents of the file into the buffer
Get #iFile, , sTextBuffer
' Close the file
Close iFile

' Use the "Replace" function to replace all instances of
' (sFind) in the buffer with the value in (sReplace)
sTextBuffer = Replace(sTextBuffer, sFind, sReplace)

' Get the next available file handle
iFile = FreeFile
' Open/Create the new file for write access
Open sNewFile For Binary Access Write As iFile
' Write the modified buffer contents to the file
Put #iFile, , sTextBuffer
' Close the file
Close iFile
End Sub
'--------------------------------------------------------------------

Example Usage:
'--------------------------------------------------------------------
Call TextFileReplace("C:\MyFile.csv", "C:\NewFileName.txt", "IT_Number", "IT_Nbr")
'--------------------------------------------------------------------

No comments:

Post a Comment