MICROSOFT

EP05. “Count Words 统计字数”

首页 Microsoft 工具 Excel · VBA · String Manipulation · EP05
约 5 分钟· #EP05#Excel#String Manipulation
🔒 登录后可标记已读
  • 写一个宏,统计选中范围里所有单元格加起来总共有几个单词(用空格判断分词)
  • 核心思路是不断找空格、切掉已数过的部分,直到字符串里再也找不到空格
  • 前置知识:EP04 的 InStr、Trim 函数,以及 Do While 循环
  • 学完能自己写「逐格拆解、逐个累加」这种统计类宏

重点内容


适用版本

桌面版通用(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 清除字符串前后多余的空格
  • ✅ 用 Do While...Loop 搭配 InStr 反复搜索,直到条件不成立才停
  • ✅ 把单格的统计逻辑累加成整个选中范围的总计

常见错误

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

Sources

Blog / Website:

  1. Count Words