vba 如何通过excel vba在文件夹中的csv文件中搜索字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22385248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:20:49  来源:igfitidea点击:

How to search through csv files in a folder for a string through excel vba?

excelvbaexcel-vbacsv

提问by ichayan

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

我正在使用 excel vba 在 csv 文件中查找与给定字符串匹配的记录我需要帮助在文件夹中搜索特定字符串的所有 csv 文件并获取包含搜索字符串的文件名并从文件中获取行本身. 该字符串将始终出现在 CSV 的 B 列中。提前致谢

回答by Mark Setchell

It might be easier to start a Command Prompt and navigate to your folder containing the CSV files. Then you can do this:

启动命令提示符并导航到包含 CSV 文件的文件夹可能会更容易。然后你可以这样做:

FINDSTR /N /I "something" *.CSV

where "something" is whatever you are looking for.

“某物”是您要寻找的任何东西。

回答by ichayan

This returns the first file it finds the match, found here http://www.ggkf.com/excel/vba-macro-to-search-a-folder-for-keyword

这将返回它找到匹配的第一个文件,在这里找到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