- Home
·
- Miscellaneous
·
- Replace any Text Inside any File and save the new text to new file or overwrite the old file
Replace any Text Inside any File and save the new text to new file or overwrite the old file
Replace any Text Inside any File and save the new text to new file or overwrite the old file
Rate Replace any Text Inside any File and save the new text to new file or overwrite the old file
(1(1 Vote))
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
Replace any Text Inside any File and save the new text to new file or overwrite the old file Comments
No comments yet — be the first to post one!
Post a Comment