What I am trying to accomplish
我想从选定的单元格中获取一系列值,然后填充一个新单元格,该单元格仅包含我所做选择中的唯一值。这是我目前的代码:
Const Delimiter = ", "
Dim num As Range
Dim a As Variant
Dim Concat, bucket As New Collection
#to create a collection that contains all the values from my selection
For Each num In Selection
a = Split(num, Delimiter)
Concat.Add (a)
Next num
#to convert multidimensional collection to a single dimensional
For i = 1 To Concat.Count
For j = 1 To Concat(i).Count
bucket.add(Concat(i)(j))
Next i
Next j
#to remove duplicate values
[code]
#to output to excel
[code]
如您所见,代码不完整。我遇到以下代码行的问题
For j = 1 To Concat(i).Count
我收到"运行时错误''':需要对象"错误。
答案 0 :(得分:2)
使用字典可以使它更简单,更容易。见下文。
Sub UniqueValues()
Const Delimiter = ","
Dim num As Range
Dim a As Variant
Dim i As Integer, j As Integer
Dim dctData As New Dictionary
'Loop through all the values in the cells (including splitting into arrays)
For Each num In Selection
a = Split(num, Delimiter)
For j = 0 To UBound(a, 1)
If Not dctData.Exists(Trim(a(j))) Then
dctData.Add Trim(a(j)), ""
End If
Next j
Next num
'#to output to excel
For Each a In dctData
Debug.Print a
Next a
End Sub