简体   繁体   中英

VBA - Getting unique values from a column without using a split string

I'm using the following code to save all unique values in a column of strings into an array, and then I get the amount of unique values by counting the length of the array.

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

However, when I run this code, arrLen is a number smaller than the actual amount of unique entries in the column (I know this by doing a manual data check for unique entries.) Data in the column does not contain any "|" characters, only numbers.

What could the problem be? And is there an alternative way of getting the amount of unique entries into an array and determining its length?

This check probably is the problem:

(InStr(tmp, cell) = 0)

If eg a cell is hello , and a later cell is ello , it won't be included because ello is part of hello and thus the tmp string.

To go with your current method, change it to

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

and start with an initial tmp = "|" .

So if the current tmp is |foo|hello|bar| , you search it for |ello| , and get a 0.


A more straightforward way would be to use eg a collection, checking each new cell if it's already contained in the collection.

See http://www.cpearson.com/Excel/CollectionsAndDictionaries.htm --> KeyExistsInCollection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM