【问题标题】:Counting using a multi-array? (Excel, VBA)使用多数组计数? (Excel,VBA)
【发布时间】:2022-07-26 23:58:49
【问题描述】:

我有一个相对简单的任务,并且已经找到了一些解决方案,但是我有一个效率更高的想法,我只是不知道是否可以编码。 基本上,我需要计算动物及其身体特征,然后报告这些数据。也许 A 列代表物种,B 列代表他们的头发颜色,C 列代表他们的年龄。我可以使用循环和嵌套的 if/else 语句来解决这个问题,但它的大小会膨胀并且看起来很草率。 我希望做的是一些更像:

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

但事实证明这非常困难,因为我得到的一些值是字符串(物种和颜色),而数组函数似乎只接受数字。 有谁知道一种以非常有效的方式计算此类信息的方法?如果我能够将它存储在一个数组中,我就可以一次打印所有结果,这是我的目标的一部分。

【问题讨论】:

  • 你需要一个变量,而不是Array函数。
  • 如果我使用变量来跟踪这些数据,难道我不需要为报告中的每个值设置一个变量吗?我最终需要几十到几百个,每个报告都非常不切实际。使用多阵列意味着可以将所有数据存储在一起并一次性报告。以有效的方式将数据放入多数组中是困难的部分。
  • 更具体地说:您需要一个数组变量。可能有助于了解Arrays and Ranges
  • 为了意图,你是在统计“species+color+age”这个组合的出现次数,还是对数据做更多的分析?
  • 您可以使用脚本字典和组合键,例如species|color|age

标签: arrays excel vba count


【解决方案1】:

您可以使用Dictonary 来统计每个组合的出现次数。键是物种、颜色和年龄的串联字符串,项目是计数。您将对其进行编码,与您的想法非常相似:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 2016-03-12
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多