I am using excel vba to find a record in csv files which matches given string I need help in searching through all csv files in a folder for a particular string and get the file name which contains the search string and from within the file the row itself. The string will always appear in column B of the CSV. Thanks in advance
2 Answers
It might be easier to start a Command Prompt and navigate to your folder containing the CSV files. Then you can do this:
FINDSTR /N /I "something" *.CSV
where "something" is whatever you are looking for.
3 Comments
ichayan
How can i get this into VBA?
Mark Setchell
My point was that this probably easier than loading a load of files in Excel by clicking around all over the place.
user3075740
seriously saved my time, ive been trying to bang head with powershell
This returns the first file it finds the match, found here http://www.ggkf.com/excel/vba-macro-to-search-a-folder-for-keyword
Sub loopThroughFiles()
Dim file As String
file = FindFiles("putyourpathname eg.c:\reports", "search string")
If (file <> "") Then MsgBox file
End Sub
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Shell Command And Get Output
Dim files As String
files = CreateObject("Wscript.Shell").Exec("FINDSTR /M """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
FindFiles = ""
If (files <> "") Then
Dim idx As Integer
idx = InStr(files, vbCrLf)
FindFiles = Left(files, idx - 1)
End If
End Function
Dir(pathToYourFolder & "*.csv")to loop through and open each file in the source folder. Plenty of examples of this here on SO alone.