Monday, October 30, 2017

To delete specified variable content from the text file

Function fnDelete_Value_From_TextFile(varName,strFilePath)
   'Function to delete specified content from the text file
   On Error Resume Next 'Error Handling
'Constants for Reading and Tristate Use Default
Const ForReading = 1,ForWriting= 2,ForAppending = 8
    'Path of the file to be modified
        '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 delete specified content from text file")
fnDelete_Value_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)
    Flag = 0
Dim var_SplitData()
Counter = 0
'This code will read all the lines in the Config file
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
ReDim Preserve var_SplitData(Counter)
var_found = Instr(1,strNextLine,varName,1)
If var_found > 0 Then
Flag = 1
Else
var_SplitData(Counter) = strNextLine
Counter = Counter + 1
End If
Loop
'This code will close the file after reading
objTextFile.Close
'Write data into the file
Set objTextFile = objGetFile.OpenAsTextStream(ForWriting,False)
For var_Loop = 0 to UBound(var_SplitData)
objTextFile.WriteLine var_SplitData(var_Loop)
Next
objTextFile.Close
If Flag = 0 Then
Call DoneResult("Specified content: '" & varName & "' does not exist in the test data text file","Not able delete the specified content from text file")
fnDelete_Value_From_TextFile = ""
End If
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 deleting the value from Text file", "Deleting the value from text file is failed")
fnGet_Value_From_TextFile = ""
End If
End Function

No comments:

Post a Comment