查询:我想计算某个单词在一系列excel单元格中出现的次数
如果可能,与其查找某个单词,不如编写一个脚本,该脚本总结了 excel 单元格范围内每个单词出现的次数。即按照频率从高到低的顺序总结,每个词出现的次数。
Excel 文件:
谢谢!
答案 0 :(得分:0)
首先你需要一个函数来删除你从单元格中得到的字符串中的所有特殊字符。
Function without_special_chars(text As String) As String
Dim i As Integer
Const special_chars As String = "-.,:;#+ß'*?=)(/&%$§!~\}][{"
For i = 1 To Len(special_chars)
text = Replace(text, Mid(special_chars, i, 1), "")
Next i
without_special_chars = text
End Function
这只是一个查看字符串是否已经在数组中的函数。
Function IsInArray(stringToBeFound, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
然后你可以遍历所有的单元格。
Sub query()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Tabelle1")
Dim wordlist()
Dim nList()
Dim word As String
For i = 1 To ws.Cells(1048576, 11).End(xlUp).Row
text = without_special_chars(ws.Cells(i, 11).Value)
cell_words = Split(text, " ")
For j = 0 To UBound(cell_words)
the_word = cell_words(j)
If j = 0 And i = 1 Then
ReDim wordlist(0)
ReDim nList(0)
wordlist(UBound(wordlist)) = the_word
nList(UBound(nList)) = 1
Else
If IsInArray(the_word, wordlist) = True Then
For n = 0 To UBound(wordlist)
If wordlist(n) = the_word Then
nList(n) = nList(n) + 1
Exit For
End If
Next
Else
ReDim Preserve wordlist(UBound(wordlist) + 1)
ReDim Preserve nList(UBound(nList) + 1)
wordlist(UBound(wordlist)) = the_word
nList(UBound(wordlist)) = 1
End If
End If
Next
Next
For m = 0 To UBound(wordlist)
ws.Cells(m + 1, 1).Value = wordlist(m)
ws.Cells(m + 1, 2).Value = nList(m)
Next
End Sub
对于 ws,您必须输入工作表的名称。 最后一个带有 m 的 for 循环是输出,我只是为了测试目的而制作它,最后你将有两个数组。存储所有单词的 wordlist 和存储数量的 nList。我没有考虑大写和小写,所以“I”和“i”可能有两个条目。
您只需将此代码放在 VBA 编辑器中并运行查询子。 (打开Excel,按ALT+F11,把它放到ThisWorkbook,点击sub的一行并点击运行)
VBA 的速度不是很快,所以我不知道需要多长时间,但我用几个 hundret 单元格和一些句子对其进行了测试,大约需要 1.5 分钟。