Monday, October 30, 2017

To search value from text file

Function fnSearchString_From_TextFile(strFilePath,varValue,NoOfOccurances)
   'function to search value from text file
   On Error Resume Next 'Error Handling
'Constants for Reading and Tristate Use Default
Const ForReading = 1,ForWriting= 2,ForAppending = 8
    'Create FSO Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(strFilePath) Then
Call DoneResult("Specified file: '" & strFilePath & "' does not exist", "Not able to search the data from specified text file")
fnSearchString_From_TextFile = ""
Exit Function
End If
'Get the file to be read.
Set objGetFile = objFSO.GetFile(strFilePath)
'This code will read the file as Text Stream
Set objTextFile = objGetFile.OpenAsTextStream(ForReading,-2)
'This code will read all the lines in the Config file
var_Position = 1
var_Count = 0
Do Until objTextFile.AtEndOfStream
        strNextLine = objTextFile.Readline
var_Position = Instr(var_Position,strNextLine,varValue,1)
If var_Position > 0 Then
var_Count = var_Count + 1 'retrieving the no of occurances
Else
var_Position = 1
End If
Loop
    If var_Count  = NoOfOccurances Then 'if matched
        Call DoneResult("Number of Occurances "& NoOfOccurances & " for the value '" & varValue & "' in the text file '" & strFilePath & "' is passed", "Search is passed")
fnSearchString_From_TextFile = True
ElseIf var_Count > 0 Then 'if no of occurances are failed, but atleast one match found
Call DoneResult("'" & varValue & "' exists in the text file '" & strFilePath & "' for '" & var_Count & "' times, but not for the specified number of Occurances '" & NoOfOccurances & "'", "Search is failed")
fnSearchString_From_TextFile = ""
Else 'no match found
Call DoneResult("Search for Number of Occurances of the value '" & varValue & "' in the text file '" & strFilePath & "' is failed", "Search is failed")
fnSearchString_From_TextFile = ""
End If
'This code will close the file after reading
objTextFile.Close
Set objTextFile = Nothing
Set objGetFile = Nothing
Set objFSO = Nothing
If Err.Number <> 0  Then
Call DoneResult("Exception error " & Err.Number & " with the description " & Err.Description & " occured while searching the value from Text file", "Search failed")
fnSearchString_From_TextFile = ""
End If
End Function

No comments:

Post a Comment