2015-03-03 119 views
2

我很抱歉我的英语语言太差
我想用VB编辑文件,如果必须在文件中的单词不存在。 当执行这个文件,我想如果条件是真的什么都不做,但所有的文件内容都被抹掉了。 请帮助我。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 

回答

1

that becouse strNewText将在您的条件为true时为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 
+0

tanx wicky它的真实 – mini323 2015-03-03 07:03:01

+0

@ mini323这个答案可以接受吗? – mhs 2015-03-03 07:30:49

+0

是啊我的代码现在正在工作 – mini323 2015-03-03 10:16:46