2014-06-06 45 views
0

我有一個來自en SQL服務器的記錄集。我不知道我需要檢索的確切數據量,因此我創建了一個動態數組。 我需要做的是將數據放入數組中時分離和排序數據。但我不知道最佳做法是什麼。VBA數組確定下一個值的位置

E.g.我有一組數據,其中一列中的客戶ID和第二個中的收入。可以說,我只有2個客戶和有類似下面的列表:

Customer ID  Revenue 
1    604 
2    669 
2    732 
2    629 
1    897 
2    530 

然後,我會像我的陣列有兩個維度(顧客1和2),並具有與最高金額相匹配的最大lenght一位顧客所購買的商品。在這種情況下,客戶2已經做了四次採購,客戶1已經做了兩次。因此,我理想的數組就是這樣的:myArray(1到2,4)。

我該如何做到最好?

然後,我定義了我的數組後,我想用我的數據填充它,但數據沒有排序,那麼我怎麼能確定我應該在什麼地方放置數據呢?如果這使得感知?

比如我最初的想法是通過數據集運行,做這樣的事情:

i = 1 

do until dataset.eof 
if dataset.field("customerid") = 1 then 
    myArray(1, i) = dataset.field("customerid").value 
else if dataset.field("customerid") = 2 then 
    myArray(1, i) = dataset.field("customerid").value 
end if 

i = i + 1 
dataset.movenext 
loop 

這是所有罰款和花花公子,直到客戶ID變化。如果第一行爲客戶1,則數據將被放置在myArray(1,1)和myArray(1,2)中。但是,如果我下一行的客戶ID是客戶2,則客戶2的第一個條目將在myArray(2,3)中,而不是myArray(2,1),這是我所希望的。 此外,如果按照我的第一個問題定義數組,我將超出數組的極限:-)

這是否有意義?

在此先感謝:-)

+0

將它置入某種數組只是故事的一半:你打算如何在那之後做* –

回答

0

您可以使用腳本字典與客戶ID作爲鍵和收入作爲值的數組。

未經測試:

dim dict as object, id, rev, tmp, k 
set dict = createobject("scripting.dictionary") 

do until dataset.eof 
    id = dataset.fields("customerid").Value 
    rev = dataset.fields("revenue").Value 

    if dict.exists(id) then 
     tmp = dict(id) 
     ub = ubound(tmp)+1 
     redim preserve tmp(0 to ub) 
     tmp(ub) = rev 
     dict(id) = tmp 
    else 
     dict(id) = Array(rev) 
    end if 

    dataset.movenext 
loop 

for each k in dict 
    debug.print k, join(dict(k),", ") 
next k 
+0

如何比較使用類和集合對象? –

+0

我會說它或多或少相似。什麼是「最好的」真的取決於OP想要做什麼。我傾向於傾向字典而不是集合,因爲我經常希望快速基於密鑰訪問項目,但對於課程的馬總是適用... –

+0

感謝您的信息 –

0

我相信數組是不是這一目標的最佳數據結構。我會使用一組類。這爲存儲和排序數據提供了極大的靈活性。作爲一個例子,我創建了下面的:

工作表-in(作爲數據源,來取代記錄集):

data_source

-Code模塊模塊1:

Option Explicit 

Sub jzz() 

Dim Customers As Collection 
Dim cust As cls_customer 
Dim i As Long 
Dim arr() As Long 

Set Customers = New Collection 
i = 1 
Do Until Cells(i, 1) = vbNullString 
    'check if the customer is already in the collection:' 
    For Each cust In Customers 
     If cust.id = Cells(i, 1) Then Exit For 
    Next cust 
    'check if the customer was found; if not, create new and add to collection' 
    If cust Is Nothing Then 
     Set cust = New cls_customer 
     cust.id = Cells(i, 1) 
     Customers.Add cust 
    End If 
    cust.Revenue = Cells(i, 2) 
    i = i + 1 
Loop 

For Each cust In Customers 
    Debug.Print cust.id, cust.Revenue_count 
Next cust 

Set Customers = Nothing 

End Sub 

- 班級模塊cls_customer:

Option Explicit 


Public id As Long 
Private p_revenue_collection As Collection 

Public Property Let Revenue(value As Long) 
    'accepts a long (value) and adds it to the collection' 
    p_revenue_collection.Add value 
End Property 

Public Property Get Revenue_count() As Long 
    Revenue_count = p_revenue_collection.Count 
End Property 

Private Sub Class_Initialize() 
    Set p_revenue_collection = New Collection 
End Sub 

該課程只保留revenue_count屬性,用於返回集合中的條目數量,但您可以隨意添加自己的屬性以返回排序後的數據等。

相關問題