为了这个问题,假设我有一个包含各种酒类型的Excel数据源电子表格。
(Cell A) | (Cell B)
Bacardi | Rum
Smirnoff | Vodka
Another Vodka | Vodka
Yet Another Vodka | Vodka
Malibu | Rum
Meyers | Rum
等。
在文档中的单独工作表中,我想按如下方式列出:
RUM
Bacardi
Malibu
Meyers
----------
VODKA
Smirnoff
Another Vodka
Yet Another Vodka
......其中RUM是一个类别,VODKA是另一个类别。
如何将我的数据源(第一个示例)转换为第二个示例?
答案 0 :(得分:2)
这不是最优雅的,也不是最有效的方式,但是如果你匆忙的话,这里是如何使用2个词典做的!
Sub test()
Dim varray As Variant, v As Variant
Dim lastRow As Long, i As Long
Dim results() As String
Dim dict As Object, dict2 As Object
Set dict = CreateObject("scripting.dictionary")
Set dict2 = CreateObject("scripting.dictionary")
lastRow = Sheet1.range("B" & Rows.count).End(xlUp).Row
varray = Sheet1.range("A1:B" & lastRow).Value
On Error Resume Next
'Make the liquer dictionary
For i = 1 To UBound(varray, 1)
If dict.exists(varray(i, 2)) Then
dict(varray(i, 2)) = dict(varray(i, 2)) & _
vbLf & varray(i, 1)
Else
dict.Add varray(i, 2), (varray(i, 1))
End If
Next
i = 1
For Each v In dict
dict2.Add i, UCase(v)
i = i + 1
results() = Split(dict.Item(v), vbLf)
For j = 0 To UBound(results())
dict2.Add i, results(j)
i = i + 1
Next
dict2.Add i, "----------"
i = i + 1
Next
Sheet2.range("A1").Resize(dict2.count).Value = _
Application.Transpose(dict2.items)
End Sub
工作原理:使用字典分隔主要类别和子项目(通过将它们连接为该键的项目)非常方便。 您可以找到将其重新打印到Excel上的方法,但它需要调整大小并且这很麻烦。由于字典具有转置所有键或项目的能力,我选择将关键项对(现在技术上按顺序)转储到另一个字典中,但作为项而不是键,所以我可以保持欺骗。它还允许你像uCase那样进行最终数据按摩,并添加分隔符等。然后我只是转置结果。
非常规,也许,但有趣且有效!