Check if text exists in file and if not append it with VBScript

VB Script

 

Let’s say, for example, that you have a file with multiple lines in the form of:

 


MyText1

MyText2

MyText3

 

And let’s say you have a variable in the form of:

 


MyStr="MyText1,MyText2,MyText3,MyText4,MyText5"

 

What if you want to add only MyText4 and MyText5 into the file?

The solution is simple, we split MyStr, open up the text file, and for each line we check if MyStr is present in the text file, if not, we write it.

 

The code for this is:

 


Dim objFSO, objFolder, objShell, objTextFile, objFile
Dim strDirectory, strFile, strText
Set WshShell = CreateObject("WScript.Shell")
strDirectory = "C:\test"
strFile = "\MyFile.txt"

MyStr="MyText1,MyText2,MyText3,MyText4,MyText5"

MyStr=Split (MyStr,",")

Mynewstr= MyStr(0) & vbNewline

Set objFSO = CreateObject("Scripting.FileSystemObject")

set objFile = nothing
set objFolder = nothing

Const ForAppending = 8
Const ForReading = 1
Const ForWriting = 2

Set objTextFile = objFSO.OpenTextFile _
(strDirectory & strFile, ForReading, True)

Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
test = Test & strNextLine

Loop
objTextFile.Close
For Each field In MyStr
strText = field

Set TxtFile = objFSO.OpenTextFile(strDirectory & strFile,ForReading)

If Not TxtFile.AtEndOfStream Then sContent = sContent & TxtFile.ReadAll

If InStr(test,strText) > 0 Then

Set TxtFile = Nothing
Else
Set TxtFile = objFSO.OpenTextFile _
(strDirectory & strFile, ForAppending, True)
TxtFile.WriteLine vbNewline & strText
TxtFile.Close
End If
Next
Set objFile = objFSO.OpenTextFile(strDirectory & strFile,ForReading)

Do Until objFile.AtEndOfStream

strLine = objFile.Readline

strLine = Trim(strLine)

If Len(strLine) > 0 Then

strNewContents = strNewContents & strLine & vbCrLf

End If

Loop
objFile.Close
Set objFile = objFSO.OpenTextFile(strDirectory & strFile, ForWriting)

objFile.Write strNewContents

objFile.Close

 

Hope this helps you out.

Sharing is caring!

Leave a comment

Your email address will not be published. Required fields are marked *

10 + 16 =