我的工作表中有一张客户发票数据:
Name | Date | OrderID | Item | Price | Email
Anna | 2015-03-10 | ABC123 | Shirt | 5.00 | anna@gmail.com
Bob | 2015-03-11 | ABC124 | Pants | 10.00 | bob@gmail.com
Anna | 2015-03-11 | ABC125 | Pants | 10.00 | anna@gmail.com
之前,我通过利用从第2行到数据区域末尾的for循环来使用集合,以添加到集合中。我创建了两个类模块。一个是交易'和另一个发票'。在'交易'内class module我为每个事务声明了组件的公共变量,即Name,Date,OrderID,Item,Price和Email。发票' class module包含将每个事务添加到集合中的过程。
由于能够使用密钥,我开始将字典作为一种处理数据的方式。我希望密钥是交易人员的姓名。因为安娜做了两笔交易,如果我查看安娜'在字典中键,我将能够检索安娜的交易。
我该怎么做呢?我一直在遇到错误,因为我一直在寻找处理一维数据集的代码示例。
Sub ProcessData()
Dim dict As Dictionary
Dim i As Integer
Dim TargetRow As Integer
Dim Name As String
Dim Date As Date
Dim OrderID As Double
Dim Item As String
Dim Price As Double
Dim Email As string
Dim More As Boolean
Set dict = New Dictionary
More = True
i = 2
While more
Name = Worksheets("Data").Cells(i, 1).Value
Date = Worksheets("Data").Cells(i, 2).Value
OrderID = Worksheets("Data").Cells(i, 3).Value
Item = Worksheets("Data").Cells(i, 4).Value
Price = Worksheets("Data").Cells(i, 5).Value
Email = Worksheets("Data").Cells(i, 6).Value
dict.Item(Name) = ...
Wend
End Sub
答案 0 :(得分:1)
为此,您需要将数组作为Dictionary
项传递
像这样:
Dim c As Range, sh As Worksheet, lr As Long, key
Set sh = Worksheets("Data")
With sh
lr = .Range("A" & .Rows.Count).End(xlUp).Row
End With
With CreateObject("Scripting.Dictionary")
' Pass data from worksheet to Dictionary
For Each c In sh.Range("A2:A" & lr)
.Item(c.Offset(0, 2).Value2) = c.Resize(, 6) ' Passed as array
Next
' Retrieve data from Dictionary to where
For Each key In .Keys
' Access Items as array
Debug.Print .Item(key)(1, 1) 'Name
Debug.Print .Item(key)(1, 2) 'Date
Debug.Print .Item(key)(1, 3) 'OrderID
Debug.Print .Item(key)(1, 4) 'Item
Debug.Print .Item(key)(1, 5) 'Price
Debug.Print .Item(key)(1, 6) 'Email
Next
End With
请注意,您需要使用始终唯一的Key
在示例数据中,由于Ana有重复,因此您无法将Name
用作Key
将第一个数据传递给字典后,第一个数据将被覆盖
在上面的示例中,我使用了OrderID
作为Key,因为它是唯一的
此外,我将所有信息作为2D数组Item
传递,并且可以如上所示进行检索
这没关系,但我认为在你的情况下使用Class Module
要好得多。
答案 1 :(得分:0)
您需要断开ADODB.Recordsets。他们是一个网格。只需要字典来测试唯一键。
这是两个记录集。
Sub Randomise
Randomize
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "RandomNumber", 4
.Fields.Append "Txt", 201, 5000
.Open
Do Until Inp.AtEndOfStream
.AddNew
.Fields("RandomNumber").value = Rnd() * 10000
.Fields("Txt").value = Inp.readline
.UpDate
Loop
.Sort = "RandomNumber"
Do While not .EOF
Outp.writeline .Fields("Txt").Value
.MoveNext
Loop
End With
End Sub
'=============================================
Sub Swap
Dim LineCount
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "LineNumber", 4
.Fields.Append "Txt", 201, 5000
.Open
LineCount = 0
Do Until Inp.AtEndOfStream
LineCount = LineCount + 1
.AddNew
.Fields("LineNumber").value = LineCount
.Fields("Txt").value = Inp.readline
.UpDate
Loop
.Sort = "LineNumber DESC"
Do While not .EOF
Outp.writeline .Fields("Txt").Value
.MoveNext
Loop
End With
End Sub