使用字典和数组来计算单元格值

时间:2016-10-20 07:01:43

标签: arrays excel vba dictionary count

这是this question.的扩展我想做类似的事情,但我对字典对象不太熟悉,答案中提供的代码非常先进,所以我无法理解它。例如,一些语法不是很清楚,变量名称不是很明显/直观。我正在创建一个新问题,因为原来的问题已经解决了。

我想做与链接问题完全相同的事情,但是我不想计算H列中的单元格值,而是计算每个试验的AOI条目(并忽略退出)并在第I列中阻止,并打印数字在U栏中。

如果您还可以提供解决方案的解释(以便我了解正在发生的事情),那将不胜感激。或者至少解释前一个解决方案中发生了什么。

Here is a link to my most up to date sample data and code.

And here is a screenshot of my data

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了。这是代码:

Dim dBT As Object 'global dictionary

Sub buttonpresscount()

    'constants for column positions
    Const COL_BLOCK As Long = 1
    Const COL_TRIAL As Long = 2
    Const COL_ACT As Long = 7
    Const COL_AOI As Long = 8

    Dim rng As Range, lastrow As Long, sht As Worksheet
    Dim d, r As Long, k, resBT()

    Set sht = Worksheets("full test")
    lastrow = Cells(Rows.Count, 3).End(xlUp).Row
    Set dBT = CreateObject("scripting.dictionary")

    Set rng = sht.Range("B7:I" & lastrow)

    d = rng.Value  'get the data into an array

    ReDim resBT(1 To UBound(d), 1 To 1) 'resize the array which will
                                        '  be placed in ColT

    'get unique combinations of Block and Trial and pressedcounts for each
    For r = 1 To UBound(d, 1)
        k = d(r, COL_BLOCK) & "|" & d(r, COL_TRIAL) 'create key
        dBT(k) = dBT(k) + IIf(d(r, COL_ACT) <> "", 1, 0)
    Next r

    'populate array with appropriate counts for each row
    For r = 1 To UBound(d, 1)
        k = d(r, 1) & "|" & d(r, 2)   'create key
        resBT(r, 1) = dBT(k)          'get the count
    Next r

    'place array to sheet
    sht.Range("T7").Resize(UBound(resBT, 1), 1) = resBT

    'clear dictionary
    dBT.RemoveAll

'count AOI entries
 For r = 1 To UBound(d, 1)
        k = d(r, COL_BLOCK) & "|" & d(r, COL_TRIAL) 'create key
        dBT(k) = dBT(k) + IIf(d(r, COL_AOI) = "AOI Entry", 1, 0)
    Next r

    'populate array with appropriate counts for each row
    For r = 1 To UBound(d, 1)
        k = d(r, 1) & "|" & d(r, 2)   'create key
        resBT(r, 1) = dBT(k)          'get the count
    Next r

    'place array to sheet
    sht.Range("U7").Resize(UBound(resBT, 1), 1) = resBT


End Sub

我基本上复制了以前的代码,为相关列添加了另一个常量并更改了对列的相关引用,并确保在计算任务之间清除字典。