Reputation: 21
I want to edit a file with VB if the word that must to be in file isn't exist. when execute this file, I want if condition was true do nothing but all file content was erase.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForReading)
strText = objFile.ReadAll
objFile.Close
strSearchFor = "this word must to exist"
If InStr(1, strText, strSearchFor) > 0 then
'do nothing
else
strNewText = Replace(strText,"this word must to delete","this word must to exist" )
End If
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForWriting)
objFile.WriteLine strNewText
objFile.Close
Upvotes: 2
Views: 177
Reputation: 384
that becouse strNewText
will be null when your condition true. and still replace the strText
with your empty strNewText
.
Keep your works in side the if()
. so it will solve the Problem.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForReading)
strText = objFile.ReadAll
objFile.Close
strSearchFor = "this word must to exist"
If InStr(1, strText, strSearchFor) > 0 then
'do nothing
else
strNewText = Replace(strText,"this word must to delete","this word must to exist" )
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForWriting)
objFile.WriteLine strNewText
objFile.Close
End If
Upvotes: 2