Finding Duplicates in VBA Array (1 Viewer)

john843

New member
Local time
Today, 05:34
Joined
Nov 26, 2023
Messages
5
Trying to identify duplicates in an array of numbers. I found some variations of this on the Internet - seems like a practical option.
The value of i and j in line 8 is 0 and 1 respectively - this makes sense with a zero-based array. Unsure what's out of range.

Code:
Public Function GetDuplicate() As Boolean
    Dim arr()
    Dim i As Long
    Dim j As Long
    arr = Array(123, 345, 654, 235, 94, 123)
    For i = LBound(arr) To UBound(arr)
        For j = i + 1 To UBound(arr)
            If arr(i, 1) = arr(j, 1) Then 'error is "Subscript out of range"
                GetDuplicate = True
                Exit Function
            End If
        Next
    Next
    GetDuplicate = False
End Function
 

MajP

You've got your good things, and you've got mine.
Local time
Today, 06:34
Joined
May 21, 2018
Messages
8,529
You only have a one dimensional array not a two dimensional array
Code:
 If arr(i, 1) = arr(j, 1)
If arr(i) = arr(j)
 

john843

New member
Local time
Today, 05:34
Joined
Nov 26, 2023
Messages
5
Outstanding! thanks for the reply. it worked perfectly.
 

gemma-the-husky

Super Moderator
Staff member
Local time
Today, 11:34
Joined
Sep 12, 2006
Messages
15,656
Your code works (after removing the second dimension), but it doesn't report the duplicate. It would be more efficient with a sorted array, assuming you need to re-use the array for some other reason.
 

ebs17

Well-known member
Local time
Today, 12:34
Joined
Feb 7, 2020
Messages
1,946
As a database developer, you can/should work with tables and queries instead of first creating objects like arrays, which are not really suitable for the actual task.
Excel developers also use dictionaries in this context.
 

Users who are viewing this thread

Top Bottom