查找类vba中的值的百分比/计数

时间:2013-08-22 21:25:12

标签: excel vba excel-vba

我这个班有很多集合

    'class properties
     public a as collection
     public b as collection
     public c as collection

a,b,c包含例如“a,a,a,a,b,b,b,b,c,c,c,c,c,c,c”的值,因此b
和c,更可能。这些值可以是我们可以假设的任何字母。为了得到每个班级每个属性的百分比,我想这样做 (骨架,因为我不确定如何做到这一点)

     for each class in collectionOfclassobjects
       for each ca in class.a
       'here am supposed to count all a's and b's divide by class.a.count but am not sure how to do this, I have an idea of adding the first item, and everytime it occurs i add it or add a count, when it's a create collection when its a, add it, when its b create new collection, and so on i have a collection of each value and i can easily print the count/total count and the name
       next ca
       for each cb in class.b

       next cb
       for each cc in class.c

       next cc
     next class

任何建议都表示赞赏,我是新的,到目前为止我有两个noobie问题:)既没有解决也不确定原因:P

1 个答案:

答案 0 :(得分:0)

运行以下过程并等待消息框最后弹出。它会显示详细信息

result

Sub Percentage()

    Dim a As Collection
    Set a = New Collection

    a.Add "a"
    a.Add "a"
    a.Add "a"
    a.Add "a"
    a.Add "b"
    a.Add "b"
    a.Add "b"
    a.Add "b"
    a.Add "c"
    a.Add "c"
    a.Add "c"
    a.Add "c"
    a.Add "c"
    a.Add "c"
    a.Add "c"

    Dim i As Long, cnt As Long
    cnt = 0
    ' checking the percentage of occurance of letter 'a'
    For i = 1 To a.Count
        If a.Item(i) = "a" Then cnt = cnt + 1
    Next i

    MsgBox "'a' occurs " & cnt & " times in collection A" & _
    vbCrLf & vbCrLf & " which is " & Format((cnt / a.Count), "0.0%") & " of the entire collection"

End Sub