How to modify VBA code to stop returning duplicate values

Shivi0189

New Member
Joined
Apr 1, 2019
Messages
8
The data is in the form:

1 a
1 b
1 c
2 d
3 e
1 f
2 g
3 h
2 i

For grouping all the values against unique entries, a,b,c,f in front of 1, d,g,i, in front of i and so on, i have following VBA code:

Function MYVLOOKUP(lookupval, lookuprange As Range, indexcol As Long)
Dim r As Range
Dim Result As String
Result = ""
For Each r In lookuprange
If r = lookupval Then
Result = Result & " " & r.Offset(0, indexcol - 1)
End If
Next r
MYVLOOKUP = Result
End Function

then type: ==MYVLOOKUP(A2,A2:A521,2)

The above is returning duplicate values, how to avoid that? And how to place , between entries?
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
Try:

Code:
Public Function MYVLOOKUP(lookupval, lookuprange As Range, indexcol As Long)
Dim r As Range, MyDict As Object, i As Variant


    Set MyDict = CreateObject("Scripting.Dictionary")
    For Each r In lookuprange
        If r = lookupval Then MyDict(CStr(r.Offset(, indexcol - 1))) = 1
    Next r
    For Each i In MyDict
        MYVLOOKUP = MYVLOOKUP & ", " & i
    Next i
    MYVLOOKUP = Mid(MYVLOOKUP, 3)
        
End Function
You may want to add the

Code:
Application.Volatile

line as well if you want it to update if the table changes.
 
Upvote 0

Forum statistics

Threads
1,224,829
Messages
6,181,218
Members
453,024
Latest member
Wingit77

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top