Excel VBA 代码:查找关键词并汇总统计
Excel VBA 代码:查找关键词并汇总统计
本代码使用 VBA 编写,可以在 Excel 中查找指定关键词,并在每个工作表中统计关键词出现的次数。
Sub KeywordSummary()
Dim ws As Worksheet
Dim rng As Range
Dim keyword As String
Dim count As Integer
keyword = InputBox('请输入要查找的关键词:')
For Each ws In Worksheets
Set rng = ws.Cells.Find(keyword)
If Not rng Is Nothing Then
Do
count = count + 1
Set rng = ws.Cells.FindNext(rng)
Loop While Not rng Is Nothing And rng.Address <> ws.Cells.Find(keyword).Address
End If
If count > 0 Then
MsgBox '工作表 ' & ws.Name & ' 中共找到 ' & count & ' 个关键词。'
count = 0
End If
Next ws
End Sub
使用方法:
- 打开 Excel 文件,并按下 Alt + F11 键打开 VBA 编辑器。
- 在 VBA 编辑器中,插入一个新模块 (Insert -> Module)。
- 将代码复制粘贴到新模块中。
- 保存代码并关闭 VBA 编辑器。
- 返回 Excel 工作簿,运行该代码 (按 F5 键或点击运行按钮)。
- 在弹出的输入框中输入要查找的关键词,点击“确定”。
- 代码将自动在每个工作表中查找关键词,并在每个工作表中统计关键词出现的次数,并弹出消息框显示结果。
代码说明:
keyword变量存储用户输入的关键词。ws变量循环遍历每个工作表。rng变量存储找到的关键词所在的单元格。count变量记录每个工作表中关键词出现的次数。Find方法用于查找第一个匹配的关键词。FindNext方法用于查找下一个匹配的关键词。MsgBox用于显示查找结果。
原文地址: https://www.cveoy.top/t/topic/njqs 著作权归作者所有。请勿转载和采集!