Microsoft Lab
全部软件
Excel字符串处理(String Manipulation)约 4 分钟

Count Words 统计字数

重点内容


适用版本

桌面版通用(Excel 365 / 2021 / 2019 等)。


完整代码

Dim rng As Range, cell As Range
Dim cellWords As Integer, totalWords As Integer, content As String

Set rng = Selection
cellWords = 0
totalWords = 0

For Each cell In rng
    If Not cell.HasFormula Then
        content = cell.Value
        content = Trim(content)

        If content = "" Then
            cellWords = 0
        Else
            cellWords = 1
        End If

        Do While InStr(content, " ") > 0
            content = Mid(content, InStr(content, " "))
            content = Trim(content)
            cellWords = cellWords + 1
        Loop

        totalWords = totalWords + cellWords
    End If
Next cell

MsgBox totalWords & " words found in the selected range."

逻辑说明

  • Trim(content):先清掉字符串前后多余的空格,避免影响判断
  • 空字符串就是 0 个字,否则先算 1 个字(因为「N 个空格」代表「N+1 个字」)
  • Do While InStr(content, " ") > 0:只要字符串里还找得到空格,就代表还有下一个字,每找到一个空格,字数 +1,并用 Mid 把已经数过的部分去掉,Trim 清掉新产生的前导空格,重复判断
  • 每个单元格数完的字数累加进 totalWords

学完你会

常见错误

  • 忘记先 Trim 处理内容,单元格开头/结尾多余的空格会被误判成额外的单词
  • 把「空字符串算 0 个字」和「非空字符串至少算 1 个字」这个初始判断漏掉,字数从一开始就算错
  • 含公式的单元格没有跳过,把公式结果也计入字数统计,可能跟预期的统计范围不一致

Sources

Blog / Website:

  1. Count Words
只记在你的浏览器里,换设备不会同步。