开发者

Excel Data Source Sort By Group Other Page

For the sake of this question, let's say I have an Excel data source spreadsheet with various liquor types.

(Cell A) | (Cell B)
Bacardi | Rum
Smirnoff | Vodka
Another Vodka | Vodka
Yet Another Vodka | Vodka
Malibu | Rum
Meyers | Rum

etc.

On a separate sheet within the document I want to list it as follows:

RUM
Bacardi
Malibu
Meyers
----------
VODKA
Smirnoff
Another Vodka
Yet Another Vodka

... where RUM is one categor开发者_Go百科y and VODKA is another.

How would I convert my data source (first example) into the second example?


It's not the most elegant, and by far not the most efficient way, but here's how to do it using 2 dictionaries in case you're in a rush!

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

How it works: Using a dictionary to separate main categories and sub items (by concatenating them as the item for that key) is very convenient. You could work out ways to slap that back onto Excel but it requires resizing and It's a hassle. Since the dictionary comes with the ability to transpose all keys or items, I opted to dump the key-item pairs (technically in order now) into another dictionary, but as items instead of keys, so I can keep dupes. It also let's you do final data massaging like uCase the categories and add seperators, etc. Then I just transpose the result.

Unconventional, maybe, but fun and works!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜