ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

Using VBScript To Search Inside Files

Updated on August 6, 2016

Search Inside Files

VBScript has a few powerful methods to search through different types of text files to acquire information. This information can be passed on to other scripts, used to make business decisions or even used to identify problems and come up with a resolution.

Some of the commonly used methods used by a VBScript programmer to search for text in files are instr, readline and .AtEndOfStream. Regardless of what method chosen, there are several ways to search a text file. Many programmers will use combinations of the methods described above, so there is really no right or wrong. What’s important is whether or not it works for the script being developed.

The following code simply searches within a file located at C:\temp\somefile.txt, looks for “User:” within each line in that file and if the “User:” string exists, it reads certain characters within that line and displays them within a messagebox.

The code is functional, full of comments, “’” and is intended to be used as an example. For learning purposes, and to reinforce text search methods, the code can be modified by changing the file being opened and searching for a different string inside the file.

VBScript Code to Search For a String Within a File

Option Explicit

Dim objFSO, strLine, objReadFile

Set objFSO = CreateObject("Scripting.FileSystemObject")

'Identifies the file being read.

Set objReadFile = objFSO.OpenTextFile("C:\temp\somefile.txt", 1, False)

'Reads the file until the end.

Do Until objReadFile.AtEndOfStream

'Sets the line being read to a variable named strLine.

strLine = objReadFile.ReadLine

'Trims the strLine variable to remove any leading or trailing spaces.

strLine = trim(strLine)

'Set the search condition. In this case, we're looking for "User:" in the string

'of text which was set to strLine.

if instr(strLine, "User:") Then

'If "User:" is found in the line of text, we're telling VBScript to move forward 7

'characters, take the next 29 characters and set that string to a variable named strLine.

strLine = Mid(strLine, 7, 29)

'trim the strLine variable to remove any leading or trailing spaces.

strLine = trim(strLine)

End If


wscript.echo strLine

set objFSO = nothing



    0 of 8192 characters used
    Post Comment

    No comments yet.