Search for a string on all text files in a directory
Posted on October 28, 2011
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 'File/Folder Handling - Search for a string on all text files in a directory ' For each TXT file that contains the search string, the function ' returns a Variant element that contains a 3-item array that holds ' the filename, the line number, and the column number. ' NOTE: all searches are case insensitive. Function SearchTextFiles(path As String, search As String) As Variant() Dim fso As New Scripting.FileSystemObject Dim fil As Scripting.File, ts As Scripting.TextStream Dim pos As Long, count As Long ReDim result(50) As Variant ' Search for all the TXT files in the directory. For Each fil In fso.GetFolder(path).Files If UCase$(fso.GetExtensionName(fil.path)) = "TXT" Then ' Get the corresponding TextStream object. Set ts = fil.OpenAsTextStream(ForReading) ' Read its contents, search the string, close it. pos = InStr(1, ts.ReadAll, search, vbTextCompare) ts.Close If pos > 0 Then ' If the string has been found, reopen the file ' to determine string position in terms of (line,column). Set ts = fil.OpenAsTextStream(ForReading) ' Skip all preceding characters to get where ' the search string is. ts.Skip pos - 1 ' Fill the result array, make room if necessary. count = count + 1 If count > UBound(result) Then ReDim Preserve result(UBound(result) + 50) As Variant End If ' Each result item is a 3-element array. result(count) = Array(fil.path, ts.Line, ts.Column) ' Now we can close the TextStream. ts.Close End If End If Next ' Resize the result array to indicate number of matches. ReDim Preserve result(0 To count) As Variant SearchTextFiles = result End Function ' An example that uses the above routine: search for a name in all ' the TXT files in E:\DOCS directory, show the results in ' the lstResults ListBox, in the format "filename [line, column]". 'Dim v() As Variant, i As Long 'v() = SearchTextFiles("E:\docs", "Francesco Balena") 'For i = 1 To UBound(v) ' lstResults.AddItem v(i)(0) & " [" & v(i)(1) & "," & v(i)(2) & "]" 'Next |