Arrays 在公共元素上组合数组

Arrays 在公共元素上组合数组,arrays,excel,vba,Arrays,Excel,Vba,我有两个相同的多维数组,其中包含一系列日期的元素DateHourValue。每个系列中都可能缺少值 我想使用Date和Hour作为键组合成一个数组: 日期小时数组1的值数组2的值 目前,我的方法是基于最早/最晚日期创建一个新数组,然后用每个数组中的值填充,但不知道是否有更好/更简单的方法。请尝试下一种方法。以下代码从Excel工作表加载包含时间、小时和值的数组,涉及的范围如下所示: 两个范围“A2:C6”分别为“F2:F6”,将加载到两个2D阵列中(arr1和arr2)。它们将被处理,处理结果

我有两个相同的多维数组,其中包含一系列日期的元素
Date
Hour
Value
。每个系列中都可能缺少值

我想使用
Date
Hour
作为键组合成一个数组:
日期
小时
数组1的值
数组2的值


目前,我的方法是基于最早/最晚日期创建一个新数组,然后用每个数组中的值填充,但不知道是否有更好/更简单的方法。

请尝试下一种方法。以下代码从Excel工作表加载包含时间、小时和值的数组,涉及的范围如下所示:

两个范围“A2:C6”分别为“F2:F6”,将加载到两个2D阵列中(
arr1
arr2
)。它们将被处理,处理结果将被放入
arrFin
。范围“J2:K8”表示处理结果:

Sub testMatchDayHourValue()
 Dim sh As Worksheet, arr1, arr2, arrFin, i As Long
 Dim dict As New Scripting.Dictionary
 
 Set sh = ActiveSheet      'use here your necessary sheet
 arr1 = sh.Range("A2:C6").Value 'put the range value in an array
 arr2 = sh.Range("F2:H6").Value 'put the range value in an array
 For i = 1 To UBound(arr1) 'iterate through the first array elements and create uniques keys
    If Not dict.Exists(arr1(i, 1) & " " & Format(arr1(i, 2), "hh:mm")) Then
        dict.Add arr1(i, 1) & " " & Format(arr1(i, 2), "hh:mm"), arr1(i, 3) 'the key and its initial value
    Else
        'add to existing value the new one, for the same existing key:
        dict(arr1(i, 1) & " " & Format(arr1(i, 2), "hh:mm")) = _
              dict(arr1(i, 1) & " " & Format(arr1(i, 2), "hh:mm")) + arr1(i, 3)
    End If
 Next
 For i = 1 To UBound(arr2) 'iterate through the second array elements, create uniques keys and add values
    If Not dict.Exists(arr2(i, 1) & " " & Format(arr2(i, 2), "hh:mm")) Then
        dict.Add arr2(i, 1) & " " & Format(arr2(i, 2), "hh:mm"), arr2(i, 3) 'create a key if it not existing
    Else
        'add to existing value the new one, for the same existing key:
        dict(arr2(i, 1) & " " & Format(arr2(i, 2), "hh:mm")) = _
            dict(arr2(i, 1) & " " & Format(arr2(i, 2), "hh:mm")) + arr2(i, 3)
    End If
 Next
 'combining the arrays in the final one, using a not well known method:
 arrFin = Application.Transpose(Array(dict.Keys, dict.Items))

 'drop the created array contents at once:
 sh.Range("J2").Resize(UBound(arrFin), 2).Value = arrFin
End Sub

请按照我的建议进行测试,并发送一些反馈。

这项任务可以使用嵌套脚本以非常简单的方式完成。字典能否向我们展示一个现有阵列的示例以及处理后想要获得的内容?您需要为特定的日期/小时组合汇总两个初始数组的值吗?@freeflow谢谢,我以前没有见过scripting.dictionaries,但它做到了job@cs0679:您是否有时间测试上述解决方案/代码?如果经过测试,它不是解决了你的问题吗?@FanuDuru对此表示感谢,它并没有完全满足我的需要,但它给了我足够的引导,让我可以使用字典和日期/小时键,这很有效。Thanks@cs0679:但是我发布的代码和您需要的代码有什么不同?我问你看起来怎么样,但你什么也没回答。我想象上面的代码只是为了直观地向您展示数组是如何构建的,以及如何使用它们来获得我理解的您需要的东西。为了回答你的问题,我还应该展示什么?这个问题没有提供任何关于要使用的真实数组的信息?@cs0679:当然,我只能向你展示一种继续的方式…@FanuDuru我最初的问题措辞不太好-我想按时/小时对齐数据集,并将两个数组的值分开(而不是求和)。根据你的建议,我使用了带有日期/小时键方法的字典和项目数组。