请写一段VBA代码,帮我解决以下问题:我在桌面有一个文件夹名为“新建文件夹检索”,这个文件夹中有多个exl表格,每个表格中有多个sheet。请在所有sheet中检索文本“特瑞普利单抗”,并统计文本“特瑞普利单抗”出现的次数,将结果写入到一个新的exl文档中,该文档创建在桌面,命名为“新建文件夹检索结果”。注意,“特瑞普利单抗”可能是单元格中数据的一部分片段,这样也计入次数。结果的书写方式是每个sheet分别列出。
时间: 2024-02-11 13:05:02 浏览: 120
以下是用VBA实现你需要的功能的代码:
```
Sub SearchAndCount()
Dim fileSys As Object
Dim topFolder As Object
Dim folder As Object
Dim file As Object
Dim book As Workbook
Dim sheet As Worksheet
Dim searchStr As String
Dim count As Long
Dim resultBook As Workbook
Dim resultSheet As Worksheet
Dim i As Integer, j As Integer
'设置搜索字符串
searchStr = "特瑞普利单抗"
'创建结果文档
Set resultBook = Workbooks.Add
Set resultSheet = resultBook.Sheets(1)
'遍历文件夹中的所有文件
Set fileSys = CreateObject("Scripting.FileSystemObject")
Set topFolder = fileSys.GetFolder(Environ("USERPROFILE") & "\Desktop\新建文件夹检索\")
For Each folder In topFolder.SubFolders
For Each file In folder.Files
'如果是excel文件,则打开并搜索
If fileSys.GetExtensionName(file) = "xls" Or fileSys.GetExtensionName(file) = "xlsx" Then
Set book = Workbooks.Open(file.Path)
For Each sheet In book.Sheets
count = 0
'在当前sheet中搜索
For i = 1 To sheet.UsedRange.Rows.Count
For j = 1 To sheet.UsedRange.Columns.Count
If InStr(1, sheet.Cells(i, j).Value, searchStr) > 0 Then
count = count + 1
End If
Next j
Next i
'将结果写入到结果文档中
resultSheet.Cells(resultSheet.UsedRange.Rows.Count + 2, 1).Value = file.Name & " - " & sheet.Name
resultSheet.Cells(resultSheet.UsedRange.Rows.Count + 1, 2).Value = count
Next sheet
book.Close False
End If
Next file
Next folder
'保存结果文档
resultBook.SaveAs Environ("USERPROFILE") & "\Desktop\新建文件夹检索结果.xlsx"
resultBook.Close
Set resultBook = Nothing
MsgBox "搜索完成!结果保存在桌面的“新建文件夹检索结果.xlsx”文件中。"
End Sub
```
请将以上代码复制到Excel VBA编辑器中,然后运行即可。注意,运行前请先将文件夹名和搜索字符串根据实际情况进行修改。
阅读全文