I have an array of x elements, & I need to establish whether or not all elements are different from each other.
What is the most efficient way of doing this using VBA ?
Usual thanks for your expert help
Nick
![]() |
Patch reliability is unclear. Unless you have an immediate, pressing need to install a specific patch, don't do it. |
SIGN IN | Not a member? | REGISTER | PLUS MEMBERSHIP |
Home » Forums » AskWoody support » Productivity software by function » MS Excel and spreadsheet help » Array question (Excel 2003 SR2)
For not too large arrays, you can use this function:
Function AllDifferent(arr) As Boolean
Dim i As Integer
Dim j As Integer
For i = LBound(arr) To UBound(arr) – 1
For j = i + 1 To UBound(arr)
If arr(i) = arr(j) Then
AllDifferent = False
Exit Function
End If
Next j
Next i
AllDifferent = True
End Function
Here is an example of its use:
Sub Test()
Dim a, b
a = Array(1, 3, 4, 6)
b = Array(“a”, “c”, “a”, “d”)
Debug.Print AllDifferent(a)
Debug.Print AllDifferent(
End Sub
For large arrays, the function will be very slow.
You could also use something like this, which might be quicker with larger arrays as there’s only one loop:
Function AllDifferent(varData) As Boolean Dim lngindex As Long, coldata As New Collection AllDifferent = True On Error Resume Next For lngindex = LBound(varData) To UBound(varData) coldata.Add varData(lngindex), CStr(varData(lngindex)) If Err.Number 0 Then AllDifferent = False Exit Function End If Next lngindex End Function
Donations from Plus members keep this site going. You can identify the people who support AskWoody by the Plus badge on their avatars.
AskWoody Plus members not only get access to all of the contents of this site -- including Susan Bradley's frequently updated Patch Watch listing -- they also receive weekly AskWoody Plus Newsletters (formerly Windows Secrets Newsletter) and AskWoody Plus Alerts, emails when there are important breaking developments.
Welcome to our unique respite from the madness.
It's easy to post questions about Windows 11, Windows 10, Win8.1, Win7, Surface, Office, or browse through our Forums. Post anonymously or register for greater privileges. Keep it civil, please: Decorous Lounge rules strictly enforced. Questions? Contact Customer Support.
Want to Advertise in the free newsletter? How about a gift subscription in honor of a birthday? Send an email to sb@askwoody.com to ask how.
Mastodon profile for DefConPatch
Mastodon profile for AskWoody
Home • About • FAQ • Posts & Privacy • Forums • My Account
Register • Free Newsletter • Plus Membership • Gift Certificates • MS-DEFCON Alerts
Copyright ©2004-2025 by AskWoody Tech LLC. All Rights Reserved.
Notifications