使用If语句

时间:2016-12-01 02:56:15

标签: excel vba dictionary

我有这段代码在字典的列中打印值:

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
    Const COL_RT As Long = 16

    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:Q" & 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
        If d(r, 20) = 1 Then
        dBT(k) = dBT(k) + IIf(d(r, COL_AOI) = "AOI Entry", 1, 0)    'get count
        Else: dBT(k) = ""
        End If
    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

当定义用于计算AOI条目的密钥时,我只想要在T列中具有值1的试验密钥。所以我在这里插入了一个If语句:

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

但是我不认为我已经正确定义了单元格地址,因为我得到了超出范围的&#34;下标&#34;错误&#34;如果&#34;线。

我尝试将Col T定义为COL_AOI或COL_RT之类的常量,但它也不起作用。我不知道问题还有什么。

1 个答案:

答案 0 :(得分:0)

您的数组中无法访问列T的原因是您正在创建数组:

Set rng = sht.Range("B7:Q" & lastrow)
d = rng.Value

这只会复制列B和Q之间的值。为了访问列T,请将该语句更改为:

Set rng = sht.Range("B7:T" & lastrow)
d = rng.Value

(或者,更简单地说,只需使用d = sht.Range("B7:T" & lastrow).Value

然后,您应该能够使用以下语句访问T列中的值:

If d(r, 19) = 1 Then

(使用19,而不是20,因为列B将位于数组的r, 1位置,列C将位于数组的位置r, 2,等等。)