【问题标题】:Sum up specific entries of an array under condition in VBA在VBA中总结条件下数组的特定条目
【发布时间】:2016-02-25 12:57:35
【问题描述】:

我在总结 VBA 中数组的特定条目时遇到问题。我举个例子说明我的矩阵是什么样的(我们称矩阵为“startMatrix”)

Date      ticker      value
2005.01   200         1000
2005.01   300         2222
2005.01   400         2000
2005.02   200         1100
2005.02   300         3000
2005.02   400         5555

在 VBA 中,矩阵的读取方式如下:

startMatrix(1,1) = 2005.01
startMatrix(1,2) = 200
startMatrix(1,3) = 1000
startMatrix(2,1) = 2005.01
startMatrix(2,2) = 300
....
startMatrix(6,3) = 5555

所以如果代码是 200 或 300,我想总结每个日期的值并保存这个新数组(我们称之为 finalMatrix)。那么 finalMatrix 应该是这样的:

Date      Value
2005.01   3222
2005.02   4100

finalMatrix 最后在 VBA 中应如下所示:

finalMatrix(1,1) = 2005.01
finalMatrix(1,2) = 3222
finalMatrix(2,1) = 2005.01
finalMatrix(2,2) = 4100

我不太习惯这种操作,所以我非常非常感谢您的帮助。 提前谢谢你,祝你有美好的一天 埃利奥

【问题讨论】:

    标签: arrays vba excel if-statement sum


    【解决方案1】:

    最好使用字典而不是数组作为输出。

    启用 Microsoft 脚本运行时参考

    使用字典时,您可以输入日期作为键。然后,您可以评估 startMatrix 数组的每次迭代,日期是否已经作为键存在。如果没有,则创建一个新键并添加该值。如果确实存在,则获取分配给键的值并从数组中添加附加值。

    Option Explicit
    
    Public Sub sum_values()
    
        Dim wb As Workbook, ws As Worksheet
        Dim dict As Scripting.Dictionary
        Dim startMatrix() As Variant
        Dim i As Long
    
        Set wb = ThisWorkbook
        Set ws = wb.Sheets(1)
    
        startMatrix = ws.Range("A2:C7")
    
        Set dict = New Scripting.Dictionary
    
        For i = LBound(startMatrix, 1) To UBound(startMatrix, 1)
    
            If Not dict.Exists(startMatrix(i, 1)) Then
    
                dict(startMatrix(i, 1)) = startMatrix(i, 3)
    
            Else
    
                dict(startMatrix(i, 1)) = dict(startMatrix(i, 1)) + startMatrix(i, 3)
    
            End If
    
        Next i
    
    End Sub
    

    类似上面的方法对你有用。 Here 是一些字典阅读材料。

    您甚至可以排除 If 语句,只在 For...Next 语句中添加这一行:

    dict(startMatrix(i, 1)) = dict(startMatrix(i, 1)) + startMatrix(i, 3)
    

    【讨论】:

    • 哇,非常感谢您快速而深刻的回应。我会仔细看看字典,似乎很有用。非常感谢您,代码运行完美,祝您有美好的一天!
    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多