Excel VBA:Scripting.Dictionary计算

时间:2013-06-20 06:08:28

标签: excel vba scripting.dictionary

我在电子表格中有以下值:

Printer Name | Pages | Copies
HP2300       | 2     | 1
HP2300       | 5     | 1
Laser1       | 2     | 2
Laser1       | 3     | 4
HP2300       | 1     | 1

如何在每台打印机上获得打印的总页数(页数*副本),如下所示:

Printer Name | TotalPages |
HP2300       | 8          |
Laser1       | 16         |

我设法创建一个列表,计算打印机用于打印的次数:

Sub UniquePrints()

Application.ScreenUpdating = False
Dim Dict As Object
Set Dict = CreateObject("scripting.dictionary")
Dim varray As Variant, element As Variant

varray = Sheets("Prints").Range("E:E").Value
For Each element In varray
    If Dict.exists(element) Then
        Dict.Item(element) = Dict.Item(element) + 1
    Else
        Dict.Add element, 1
    End If
Next

Sheets("Stats").Range("D6").Resize(Dict.Count, 1).Value = _
    WorksheetFunction.Transpose(Dict.keys)
Sheets("Stats").Range("E6").Resize(Dict.Count, 1).Value = _
    WorksheetFunction.Transpose(Dict.items)

Application.ScreenUpdating = True
End Sub

如何计算每个打印(行)(页面*副本)的总页数并将其保存在字典中而不是仅添加1?

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

可以使用数组公式来填充单元格:

={SUMPRODUCT(IF($A$2:$A$6=$F2;1;0);$B$2:$B$6;$C$2:$C$6)}

使用Ctrl-Shift-Enter从公式窗口插入公式。卷曲括号由excel插入,而不是由用户插入。该公式可以复制到别处。

enter image description here

答案 1 :(得分:1)

读入E:G列,而不只是E,并使用该数组的第二维添加页面*副本,而不是添加1。

Sub UniquePrints()

    Dim Dict As Object
    Dim vaPrinters As Variant
    Dim i As Long

    Set Dict = CreateObject("scripting.dictionary")

    vaPrinters = Sheets("Prints").Range("E2:G6").Value

    For i = LBound(vaPrinters, 1) To UBound(vaPrinters, 1)
        If Dict.exists(vaPrinters(i, 1)) Then
            Dict.Item(vaPrinters(i, 1)) = Dict.Item(vaPrinters(i, 1)) + (vaPrinters(i, 2) * vaPrinters(i, 3))
        Else
            Dict.Add vaPrinters(i, 1), vaPrinters(i, 2) * vaPrinters(i, 3)
        End If
    Next i

    Sheets("Stats").Range("D6").Resize(Dict.Count, 1).Value = _
        WorksheetFunction.Transpose(Dict.keys)
    Sheets("Stats").Range("E6").Resize(Dict.Count, 1).Value = _
        WorksheetFunction.Transpose(Dict.items)

End Sub