如何对 Excel VBA 列表框中具有特定字符串的项目进行计数?

问题描述 投票:0回答:1

我这里有一个简单的表单,在初始化期间通过 ListBox1 显示工作表中的项目。

这是原始数据的图像:

这是文本数据:

Name        Letter
James       A
Mary        A
Robert      B
Patricia    C
John        C
Jennifer    C
Michael     D
Jennifer    E
David       E

这是我的整个简单代码。我想要实现的是计算 ListBox1 中显示的字母的实例/出现次数。我知道我们可以对工作表中的范围使用计数函数。但我想探讨一下我们是否可以计算列表框中具有特定字符串的动态数据的实例。在我下面的代码中,我有想法,但我不知道如何完成它。

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
        
        For i = 0 To ListBox1.ListCount - 1
            'if i string in column Color is equal to "A" then show the count as iCountA in labelA of the form
            'if i string in column Color is equal to "B" then show the count as iCountB in labelB of the form
            'if i string in column Color is equal to "C" then show the count as iCountC in labelC of the form
            'if i string in column Color is equal to "D" then show the count as iCountD in labelD of the form
            'if i string in column Color is equal to "E" then show the count as iCountE in labelE of the form
        Next
        Me.labelA.Caption = iCountA
        Me.labelB.Caption = iCountB
        Me.labelC.Caption = iCountC
        Me.labelD.Caption = iCountD
        Me.labelE.Caption = iCountE
End Sub

提前谢谢你..

excel vba count listbox instance
1个回答
0
投票

使用字典对象

Option Explicit

Private Sub UserForm_Initialize()

    Dim dCount As Object, i As Long, sName, ctr
    Set dCount = CreateObject("Scripting.Dictionary")
     
    With Me.ListBox1
        .ColumnCount = 2
        .ColumnHeads = True
        .ColumnWidths = "80;80"
        .RowSource = "Sheet1!A2:B10" 'Sheet9
        For i = 1 To .ListCount
            sName = "label" & Trim(.List(i - 1, 1))
            dCount(sName) = dCount(sName) + 1
        Next
    End With
   
    For Each ctr In Me.Controls
        If dCount.exists(ctr.Name) Then
            ctr.Caption = dCount(ctr.Name)
        End If
    Next
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.