请写一段VBA代码,帮我解决以下问题:遍历桌面文件夹名为“新建文件夹检索”中的所有表格的所有sheet,检索字符“特瑞普利单抗”,并统计字符“特瑞普利单抗”出现的次数,将统计结果写入到一个新的exl文档中。注意,“特瑞普利单抗”可能是单元格中数据的一部分字符,这样也计入次数。结果的书写方式是每个sheet分别列出。
时间: 2024-02-11 08:05:41 浏览: 98
以下是代码实现:
```VBA
Sub SearchAndCount()
Dim folderPath As String
Dim fileName As String
Dim sheetName As String
Dim searchText As String
Dim totalCount As Integer
Dim currentCount As Integer
Dim newWorkbook As Workbook
Dim currentWorkbook As Workbook
Dim currentWorksheet As Worksheet
'设置文件夹路径和搜索文本
folderPath = Environ("USERPROFILE") & "\Desktop\新建文件夹检索\"
searchText = "特瑞普利单抗"
'创建新的工作簿
Set newWorkbook = Workbooks.Add
newWorkbook.SaveAs Environ("USERPROFILE") & "\Desktop\搜索结果.xlsx"
'遍历文件夹中的所有Excel文件
fileName = Dir(folderPath & "*.xlsx")
Do While fileName <> ""
'打开当前Excel文件
Set currentWorkbook = Workbooks.Open(folderPath & fileName)
'遍历当前Excel文件中的所有sheet
For Each currentWorksheet In currentWorkbook.Worksheets
currentCount = 0
'在当前sheet中搜索文本
For Each cell In currentWorksheet.UsedRange.Cells
If InStr(1, cell.Value, searchText) > 0 Then
currentCount = currentCount + 1
End If
Next cell
'将搜索结果写入新工作簿
If currentCount > 0 Then
totalCount = totalCount + currentCount
newWorkbook.Worksheets.Add
newWorkbook.ActiveSheet.Name = currentWorkbook.Name & "-" & currentWorksheet.Name
newWorkbook.ActiveSheet.Range("A1") = "搜索结果"
newWorkbook.ActiveSheet.Range("A2") = "文件名"
newWorkbook.ActiveSheet.Range("B2") = "sheet名"
newWorkbook.ActiveSheet.Range("C2") = "出现次数"
newWorkbook.ActiveSheet.Range("A3") = fileName
newWorkbook.ActiveSheet.Range("B3") = currentWorksheet.Name
newWorkbook.ActiveSheet.Range("C3") = currentCount
End If
Next currentWorksheet
'关闭当前Excel文件
currentWorkbook.Close False
'获取下一个Excel文件名
fileName = Dir()
Loop
'将搜索结果写入新工作簿的总表
newWorkbook.Worksheets.Add
newWorkbook.ActiveSheet.Name = "总表"
newWorkbook.ActiveSheet.Range("A1") = "总搜索结果"
newWorkbook.ActiveSheet.Range("A2") = "搜索文本"
newWorkbook.ActiveSheet.Range("B2") = "出现次数"
newWorkbook.ActiveSheet.Range("A3") = searchText
newWorkbook.ActiveSheet.Range("B3") = totalCount
'保存并关闭新工作簿
newWorkbook.Save
newWorkbook.Close
End Sub
```
这段代码会搜索指定文件夹中的所有Excel文件,遍历每个Excel文件中的所有sheet,并在每个sheet中搜索指定文本。如果文本出现在某个单元格中,则计入搜索结果中。搜索结果会被写入一个新的Excel文件中,每个sheet的搜索结果会单独列出。最后,总的搜索结果会被写入新工作簿的总表中。
阅读全文