【问题标题】:VBA::consolidating arraysVBA::整合数组
【发布时间】:2011-06-23 12:00:39
【问题描述】:

我正在创建一个搜索功能,允许用户在数据库中同时搜索多达 3 个不同的属性(prop1、2 和 3),我通过将搜索到的 prop 的结果放入 VBA 中创建了这个子数组。但是,现在我有多达 3 个数组,我需要合并这些数组,以便只在结果中显示数组中重复的数据。关于如何 1) 仅查看用户正在搜索的属性的数组和 2) 仅将重复的数据放入最终数组中,以便我可以在结果范围中显示它,是否有任何建议?任何帮助是极大的赞赏!谢谢!

【问题讨论】:

  • 您能否向我们展示您的部分代码以及您尝试了什么?也许你可以在代码结束之前合并你的数组

标签: arrays vba consolidation


【解决方案1】:

假设您的条目直接来自数据库,因此对于一个属性是唯一的,我可以考虑以下步骤来获得一个简单的解决方案:

  1. 将数组合并在一起(prop1prop2prop3 > temp
  2. 计算每个元素的出现次数(在本示例代码中为 tempCount
  3. 根据对出现次数的了解,创建最终数组(这里称为result

    Dim prop1() As Variant
    Dim prop2() As Variant
    Dim prop3() As Variant
    Dim temp() As Variant
    Dim tempCount() As Integer
    Dim result() As Variant
    
    ReDim temp(UBound(prop1) + UBound(prop2) + UBound(prop3) + 1)
    
    'merge arrays
    Dim i As Integer
    On Error Resume Next
        For i = 0 To UBound(temp)
        temp(i * 3) = prop1(i)
        temp(i * 3 + 1) = prop2(i)
        temp(i * 3 + 2) = prop3(i)
    Next i
    
    'count occurences
    ReDim tempCount(UBound(temp) + 1)
    Dim j As Integer
    For i = 0 To UBound(temp)
    tempCount(i) = 1
    For j = 0 To i - 1
    
    'comparison of elements
        If temp(i) = temp(j) Then
        tempCount(i) = tempCount(i) + 1
        End If
    Next j
    Next i
    
    ReDim result(UBound(temp) + 1)
    
    'if an element occurs 3 times, add it to result
    Dim count As Integer
    count = 0
    For i = 0 To UBound(tempCount)
        If tempCount(i) = 3 Then
            result(count) = temp(i)
            count = count + 1
        End If
    Next i
    

为了检查一些示例,我将其添加到代码中。它只是将数组 tempresulttempCount 打印到 A、B 和 C 列。

'some sample arrays
prop1 = Array("a", "b", "c", "d", "e")
prop2 = Array("b", "c", "f")
prop3 = Array("b", "c", "d", "g")

'some sample Output

'temp
Cells(1, 1).Value = "temp:"
For i = 0 To UBound(temp)
    Cells(i + 2, 1).Value = temp(i)
Next i

'result
Cells(1, 2).Value = "result:"
For i = 0 To UBound(result)
    Cells(i + 2, 2).Value = result(i)
Next i

'count:
Cells(1, 3).Value = "count:"
For i = 0 To UBound(tempCount)
    Cells(i + 2, 3).Value = tempCount(i)
Next i

注意:tempCount 只保存元素被观看时的累积次数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    相关资源
    最近更新 更多