2013-08-22 20 views
1

我有這個類的一些藏品查找值的百分比/計數類VBA

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

A,B的,4c含有例如值「A,A,A,A,B, b,b,b,c,c,c,c,c,c,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

+0

可以使用'Scripting.Dictionary'對象這種類型的任務:如果 「鍵」(A,B,C等)不存在然後添加它並將相應的「值」設置爲1.如果已經添加了該鍵,則將該「值」增加1.例如:第一個答案在這裏 - http://stackoverflow.com/questions/9663200/excel-vba -to-count-and-print-distinct-values –

+0

我會試試,謝謝! – trackmeifUcan

+0

@TimWilliams我不確定他想刪除重複項。我想他想要在每個集合中出現一個角色的百分比。 – 2013-08-23 08:10:09

回答

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 
+0

在excel中我一直對vba感到困惑,不確定它是從記錄集中檢索還是從記錄集中檢索後更好或更容易處理數據,或者直接記錄到工作表,並從工作表中處理數據,我開始感覺它更容易在工作表上工作,速度方面沒有什麼區別,對嗎? – trackmeifUcan

+0

我認爲這取決於你對VBA的感覺如何。我更喜歡VBA而不是Spreadsheeet工具來進行任何類型的自動化。使用VBA解決問題需要花費更少的時間和精力。通常,使用對象(數組,字典,集合)進行任何計算然後手動處理電子表格會更快更高效。我不熟悉你的情況。有幾個基本問​​題需要你們整理,以便我提供一個很好的答案。考慮開始一個新問題,解釋你如何獲取數據以及你想要如何處理數據並尋求一種方法 – 2013-08-23 09:41:42