Excel数据源按组别sorting

为了这个问题,比方说,我有一个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是另一个类别。

我如何将我的数据源(第一个例子)转换成第二个例子?

这不是最优雅的,也不是最有效的方法,但是如果你急着要用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上,但它需要resize,这是一个麻烦。 由于字典能够转置所有的键或项目,所以我select将键项对(技术上现在的顺序)转储到另一个字典中,但作为项目而不是键,所以我可以保持愚蠢。 它也让你做最后的数据按摩,如uCase的类别和添加分隔符等,然后我只是转置的结果。

非常规,也许,但有趣和有效!