【高分求代码!】用vba,如何检索一个文件夹里所有txt文件中,包含某一文字,并显示结果呢

来源:百度知道 编辑:UC知道 时间:2024/05/02 18:15:13
比如文件夹下有50个txt文件
从其中检索包含“苹果”的文件,并显示文件名至excel

求代码,紧急,先付30分,若有回答继续送分,多谢!

Sub t()
Dim fso, f, f1, fc, s, r
Const ForReading = 1, ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")
'Set fc = fso.GetFile(WScript.ScriptFullName).ParentFolder.Files
Set fc = fso.GetFolder("c:\windows").Files '使用时把c:\windows改成实际的文件夹
L = 1
For Each f1 In fc
EXTName = UCase(fso.GetExtensionName(f1.Name))
If EXTName = "TXT" Then
Set fs = fso.OpenTextFile(f1, ForReading)
fb = fs.ReadAll
If InStr(1, fb, "苹果") > 0 Then
Cells(L, 1) = f1.Name

Cells(L, 2) = f1.Path
L = L + 1
End If
End If
Next
End Sub

用VBA显然太麻烦了,也不必生成.xls。 用批处理十分方便。
将下面的内容另存为一个.bat文件,放在要处理的文件夹下。结果放在list.cvs。

==========第1个:不包含子目录和完整文件路径=======
set str=苹果
set file=list.cvs

for %%x in (*.txt) do (
find "%str%" "%%x"
if %errorlevel% == 0 echo %%~nxx >>%file%