简体   繁体   English

使用多数组计数? (Excel,VBA)

[英]Counting using a multi-array? (Excel, VBA)

I have a relatively simple task and have already found a few solutions, but I have an idea that would be far more efficient, I just don't know if it's possible to code.我有一个相对简单的任务并且已经找到了一些解决方案,但是我有一个效率更高的想法,我只是不知道是否可以编码。 Basically, I need to count animals, and their physical traits, then report on that data.基本上,我需要计算动物及其身体特征,然后报告这些数据。 Perhaps column A is for the species, B is for their hair color, and C is their age.也许 A 列代表物种,B 列代表他们的头发颜色,C 是他们的年龄。 I can solve this using a loop and nested if/else statements, but it balloons in size and looks very sloppy.我可以使用循环和嵌套的 if/else 语句来解决这个问题,但它的大小会膨胀并且看起来很草率。 What I had hoped to do was something more like:我希望做的更像是:

Loop
    Array(species, color, age) = Array(species, color, age) + 1
End loop

This turns out to be very difficult though, as some of the values I'm getting are strings (species and color) and the array function only seems to accept numbers.但这变得非常困难,因为我得到的一些值是字符串(物种和颜色),而数组 function 似乎只接受数字。 Does anyone know of a way to count information like this in a very efficient manner?有谁知道一种以非常有效的方式计算此类信息的方法? If I was able to store it in an array I could have been able to print all of the results at once, which was part of my goal.如果我能够将它存储在一个数组中,我就可以一次打印所有结果,这是我目标的一部分。

You could use a Dictonary to tally up the occurrences of each combination.您可以使用字典来计算每个组合的出现次数。 The Key would be a concatenated string of the species & color & age, and the item would be the count.键是物种、颜色和年龄的串联字符串,项目是计数。 You would code it very similarly to your idea:您将对其进行编码,与您的想法非常相似:

Sub Example(ItemCollection As Variant)
    Dim Counts As Object
    Set Counts = CreateObject("Scripting.Dictionary")
    
    'Loop through your data set
    Dim Item As Variant
    For Each Item In ItemCollection
        Dim species As String, color As String, age As String
        'Define species, color and age based on each item from your data set
        'Maybe they are object members, or cells in a worksheet row
        'I don't know what your data looks like.
        
        Dim Key As String
        Key = species & "|" & color & "|" & age
        
        Counts(Key) = CLng(Counts(Key) + 1)
    Next
    
    'After the data has been tallied up, the dictionary "Counts", now contains the count of occurences of each combination.
    'You can see the full list of combinations by looking at the array Counts.Keys
    'You can return a specific count from the dictionary using the key: Counts(Key) where the Key is species & color & age
    'You can get the full list of counts from the dictionary by looking at the array Counts.Items
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM