我有两列键值对列表。例如:
UICollectionView
我需要将两列列表“展平”为一个数组,71 Archaebacteria
71 Mendosicutes
71 Metabacteria
72 blue green algae
72 blue-green algae
72 Cyanochloronta
72 Cyanophyta
73 CFB group
73 Chloroflecales
73 Chloroflexaceae/Deinococcaceae group
73 Chloroflexus/Deinococcaceae group
73 Chloroflexus/Deinococcus group
73 Cytophaga-Flexibacter-Bacteroides group
73 Fibrobacter-Acidobacteria group
73 Flexistipes group
73 GNS bacteria
73 Green non-sulfur bacteria
73 true bacteria
保留在第1列,key
的所有values
都移到同一行的新单元格
有些key
有20 keys
。对于这种情况,将有21列(密钥为1,密钥值为20)。
我研究过这个question,但未能成功修改它以产生预期效果。
如何将Excel列表转换为数组?
Notes :解决方案可能会在第2列中留下values
并将该值“复制”到数组中的相应行。或者,解决方案可以将value
“移动”到数组中的正确位置,留下具有NULL值的键。这些“清理”条件没问题,因为我将排序/删除以从新阵列中删除碎屑。
公式或VBA解决方案都很好。
答案 0 :(得分:1)
以下代码使用Dictionary
来组织所有唯一键(71,72,73)及其来自A列的值:B。
然后将值粘贴到Columns C:D。
<强>代码强>
Option Explicit
Sub TestDict()
Dim Dic As Object
Dim C As Range, C2 As Range, lRow As Long
Dim Names As String, ID$, Key As Variant, KeyVal As Variant, IDVal As Variant
Set Dic = CreateObject("Scripting.Dictionary")
With Sheets("Sheet2") '<-- modify "Sheet2" with your sheet's name
lRow = .Cells(.Rows.Count, "A").End(xlUp).Row
For Each C In .Range("A1:A" & lRow).Cells
If Not Dic.exists(CStr(C.Value)) Then
ID = C.Value
For Each C2 In .Range("A1:A" & lRow).Cells
If C2.Value = ID Then
If Names = "" Then ' first key value
Names = C2.Offset(, 1).Value
Else ' second and up key value
Names = Names & "," & C2.Offset(, 1).Value
End If
End If
Next C2
Dic.Add ID, Names
End If
ID = Empty: Names = Empty
Next C
End With
lRow = 1
With Sheets("Sheet2") ' <-- paste the organized dictionary key anv values the columns C:D
For Each Key In Dic.Keys
.Range("C" & lRow).Value = Key
' splitting values from "Merged" string Key to array
KeyVal = Split(Dic(Key), ",")
.Range("D" & lRow).Resize(1, UBound(KeyVal) + 1).Value = KeyVal
lRow = lRow + 1
Next Key
End With
End Sub
> Blockquote