VBA – 从列中获取唯一值,而不使用拆分string

我正在使用下面的代码将一列string中的所有唯一值保存到一个数组中,然后通过计算数组的长度来获取唯一值的数量。

Dim tmp As String Dim prNumbers() As String Dim arrLen As Integer Dim lastRow As Integer Dim txt As String lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row Dim rngPR As Range Set rngPR = Range("B2:B" & lastRow) If Not rngPR Is Nothing Then For Each cell In rngPR If (cell <> "") And (InStr(tmp, cell) = 0) Then tmp = tmp & cell & "|" End If Next cell End If If Len(tmp) > 0 Then tmp = Left(tmp, Len(tmp) - 1) prNumbers = Split(tmp, "|") 'Find the array length arrLen = UBound(prNumbers) + 1 

但是,当我运行这个代码时,arrLen是一个小于列中唯一条目的实际数量的数字(我通过对唯一条目进行手动数据检查来了解这一点)。列中的数据不包含任何“|” 字符,只有数字。

问题是什么? 是否有另外一种方法来获得独特的条目进入一个数组,并确定其长度?

这个检查可能是问题所在:

 (InStr(tmp, cell) = 0) 

如果例如一个单元格是hello ,并且稍后的单元格是ello ,它将不被包含,因为ellohello一部分,因此也是tmpstring。

要使用您当前的方法,请将其更改为

 (InStr(tmp, "|" & cell & "|") = 0) 

并从最初的tmp = "|"

所以如果当前的tmp|foo|hello|bar| ,您search它|ello| ,并得到一个0。


更直接的方法是使用例如集合,检查每个新的单元是否已经包含在集合中。

请参阅http://www.cpearson.com/Excel/CollectionsAndDictionaries.htm – > KeyExistsInCollection