You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Excel VBA列表框中统计特定字符串的出现次数?

直接统计ListBox中字母出现次数的VBA实现

我有一个Excel窗体,初始化时通过ListBox1加载Sheet9工作表A2:B10区域的数据,数据如下:

NameLetter
JamesA
MaryA
RobertB
PatriciaC
JohnC
JenniferC
MichaelD
JenniferE
DavidE

已知可以直接对工作表区域使用计数函数,但希望探索直接对ListBox动态数据统计的方法。以下是补全统计逻辑后的完整代码,可实现将各字母的出现次数显示在对应标签(labelA至labelE)中:

Option Explicit
Private Sub UserForm_Initialize()
    With Me.ListBox1
        .ColumnCount = 2
        .ColumnHeads = True
        .ColumnWidths = "80;80"
        .RowSource = "Sheet9!A2:B10"
    End With
    
    Dim i As Integer
    Dim iCountA As Integer, iCountB As Integer, iCountC As Integer, iCountD As Integer, iCountE As Integer
    
    ' 初始化计数变量为0
    iCountA = 0
    iCountB = 0
    iCountC = 0
    iCountD = 0
    iCountE = 0
    
    ' 遍历ListBox的每一行数据
    For i = 0 To ListBox1.ListCount - 1
        ' 获取当前行的Letter列值(ListBox列索引从0开始,Letter是第2列所以用1)
        Select Case ListBox1.List(i, 1)
            Case "A"
                iCountA = iCountA + 1
            Case "B"
                iCountB = iCountB + 1
            Case "C"
                iCountC = iCountC + 1
            Case "D"
                iCountD = iCountD + 1
            Case "E"
                iCountE = iCountE + 1
        End Select
    Next
    
    ' 将计数结果赋值给对应标签
    Me.labelA.Caption = iCountA
    Me.labelB.Caption = iCountB
    Me.labelC.Caption = iCountC
    Me.labelD.Caption = iCountD
    Me.labelE.Caption = iCountE
End Sub

关键说明

  • 遍历ListBox时,通过ListBox1.List(i, 1)定位到每行的Letter列(ListBox的列索引从0开始,因此第二列用索引1)
  • 使用Select Case替代多条件If判断,代码更简洁易读
  • 提前初始化计数变量为0,避免因变量默认值问题导致统计错误

内容的提问来源于stack exchange,提问作者Shiela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 06:43:13