by Agron Kovaci (2 Submissions)
Category: Miscellaneous
Compatability: VB 6.0
Difficulty: Unknown Difficulty
Originally Published: Mon 23rd December 2002
Date Added: Mon 8th February 2021
Rating: (1 Votes)
Replace any Text Inside any File and save the new text to new file or overwrite the old file
ByVal sFileName As String, _
ByVal sOldText As String, _
ByVal sNewText As String, _
Optional bOverWriteOldFile As Boolean = False, _
Optional ByRef sSaveToFile As String = "", _
Optional bCompare As VbCompareMethod = 1, _
Optional bEnabledEvent As Boolean = True)
If Len(sFileName) = 0 Or _
Len(sOldText) = 0 Then Exit Sub
Dim FileLength As Long
Dim iFileNumber As Integer
Dim sText As String
Dim sFile As String
Dim lLenAllText As Long
Dim lLenOldText As Long
Dim lStartPos As Long
Dim lEndPos As Long
Dim sLeft As String
Dim sRight As String
iFileNumber = FreeFile
On Error GoTo ErrFileOpen
Open sFileName For Binary As #iFileNumber
FileLength = LOF(iFileNumber)
sText = Input(FileLength, #iFileNumber)
Close #iFileNumber
If FileLength = 0 Or FileLength > 10 ^ 6 Then Exit Sub
lLenOldText = Len(sOldText)
lLenAllText = Len(sText)
lStartPos = InStr(1, sText, sOldText)
Do
If lStartPos = 0 Then Exit Do
lEndPos = lStartPos + lLenOldText - 1
sLeft$ = Left$(sText, lStartPos - 1)
sRight$ = Right$(sText, lLenAllText - lEndPos)
sText = sLeft$ & sNewText & sRight$
lLenAllText = Len(sText)
lStartPos = InStr(1, sText, sOldText)
If bEnabledEvent Then DoEvents
Loop While lStartPos > 0
If Len(sSaveToFile) = 0 Then
If bOverWriteOldFile = True Then
sFile = sFileName
Else
Dim sExt As String
Dim i As Integer
sExt = ""
For i = Len(sFileName) To 1 Step -1
If Mid$(sFileName, i, 1) = "." Then
sExt = Mid$(sFileName, i, 1) & sExt
sFile = Mid$(sFileName, 1, i - 1) & "_Temp" & sExt
Exit For
Else
sExt = Mid$(sFileName, i, 1) & sExt
End If
Next
End If
Else
sFile = sSaveToFile
End If
Open sFile For Output As #iFileNumber
Print #iFileNumber, sText
Close #iFileNumber
Exit Sub
ErrFileOpen:
On Error GoTo 0
End Sub
No comments have been posted about Replace any Text Inside any File and save the new text to new file or overwrite the old file. Why not be the first to post a comment about Replace any Text Inside any File and save the new text to new file or overwrite the old file.