If statement vb脚本if语句

If statement vb脚本if语句,if-statement,vbscript,If Statement,Vbscript,如果文件中必须包含的单词不存在,我想用VB编辑一个文件。 当执行这个文件时,如果条件为真,我想什么都不做,但所有的文件内容都被删除了 Const ForReading = 1 Const ForWriting = 2 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForReading) strText = obj

如果文件中必须包含的单词不存在,我想用VB编辑一个文件。 当执行这个文件时,如果条件为真,我想什么都不做,但所有的文件内容都被删除了

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

这是因为当您的条件为true时,strNewText将为null。并且仍然用空的
strNewText
替换
strText
。 将您的作品放在
if()
一侧。因此,它将解决问题

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