对于这个问题,假设我有一个包含各种酒类的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..。朗姆酒是一种,伏特加是另一种。
如何将我的数据源(第一个示例)转换为第二个示例?
发布于 2011-09-12 16:16:22
这不是最优雅的方式,也不是最有效的方式,但这里有两本字典,以防你着急!
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分类和添加分隔符等,然后我只是转置结果。
非传统的,也许,但有趣和有效!
https://stackoverflow.com/questions/7382679
复制相似问题