Mandy
Mandy

Reputation: 3

VBscript to search within files

I am a vbscript newbie and want to search through some files that I have downloaded via ftp. I ran a script that down loaded the files now I am not sure how to run the script to search all the files. This is what I have but I'm thinking that I should use select case statements.

Sorry if this code seems crude

Sub ReadDownloads()

Dim strInput As String
strInput = "file\path\somefile.ftp"

Dim dhigh, dclose, dlow

Close #1
Open strInput For Input As #1

  Input #1, strReadLine
  Input #1, strReadLine


While Not EOF(1)
    Input #1, strReadLine
    'Debug.Print strReadLine
    arrbreakdown = Split(strReadLine, " ")
    'Debug.Print arrbreakdown(1)
    If Left(arrbreakdown(1), 7) = "itemsearchingfor" Then
        If Mid(arrbreakdown(1), 8, 1) = "c" Then
            dclose = arrbreakdown(3)
        ElseIf Mid(arrbreakdown(1), 8, 1) = "h" Then
            dhigh = arrbreakdown(3)
        ElseIf Mid(arrbreakdown(1), 8, 1) = "l" Then
            dlow = arrbreakdown(3)
        End If
    End If


Wend
Close #1

Debug.Print dclose
Debug.Print dhigh
Debug.Print dlow

Range("D2").Value = dclose
Range("E2").Value = dhigh

Upvotes: 0

Views: 290

Answers (1)

Sudhir
Sudhir

Reputation: 1472

If your looking to search for text within a file. The first step is to get the file into a string.

A function as per below will do this for you:

' -----------------------------------------
Private Function getFileAsString(p_strFilePath)
    Dim objFSO, objFile
    Dim strFileContents

    Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Set objFile = objFSO.OpenTextFile(p_strFilePath, 1, false) 
    strFileContents = objFile.ReadAll 

    'clean up
    Set objFSO = Nothing
    Set objFile = Nothing

    getFileAsString = strFileContents
End Function    

The next step is to check if the text exists within the string i.e. the file contents.

A function as per below will do this for you, it makes use of the VB InStr function, which returns an integer of how many times the text appeared.

' ----------------------------------------- 
Public Function isTextPresent(p_strFileContents)
    Dim intTemp, blnTextFound

    'using 'InStr' function to see if a string exists  
    intTemp = InStr (p_strFileContents, "WHATEVER TEXT YOU ARE SEARCHING FOR")

    If intTemp > 0 Then
        blnTextFound = True
    Else
        blnTextFound = False
    End If    

    isTextPresent = blnTextFound
End Function

Upvotes: 1

Related Questions