2011-06-23 379 views
0

我創建了一個搜索功能,允許用戶在數據庫中同時搜索3個不同的屬性(prop1,2和3),並且我已經在VBA中創建了這個子類,將搜索到的道具放入數組中。但是,現在我有多達3個數組,我需要合併這些數組,以便只有數組中重複的數據纔會顯示在結果中。有沒有關於如何1)只查看用戶正在搜索的屬性的數組以及2)僅將重複到最終數組中的數據的任何建議,以便我可以將其顯示在結果範圍內?任何幫助是極大的讚賞!謝謝!VBA ::合併陣列

+0

你能告訴我們一些你的代碼的一部分,你試過了嗎?也許你可以在你的代碼結束之前合併你的數組 – JMax

回答

0

假設你的項目是直接從數據庫中,因此是一個性質獨特,我覺得下面的步驟進行一個簡單的解決方案:

  1. 合併陣列一起(PROP1PROP2prop3>臨時
  2. 計數出現的每個元素(在本例中代碼tempCount
  3. 基於對事件的知識,創建最終的陣列(這裏稱爲結果

    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 
    

要檢查一些樣品我已將此添加代碼。它簡單地打印出陣列溫度結果tempCount到列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只是保持出現的累積數量在點該元素正在觀看。