2014-06-06 34 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属性,用于返回集合中的条目数量,但您可以随意添加自己的属性以返回排序后的数据等。

相关问题