Duplicate values in a range

nigelandrewfoster

Well-known Member
Joined
May 27, 2009
Messages
747
Please can you show me the easiest method in VBA to check if there are any duplicate values in a particular range? (eg. B2:B151)
Thanks.
Nigel Foster
 

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
Please can you show me the easiest method in VBA to check if there are any duplicate values in a particular range? (eg. B2:B151)
Thanks.
Nigel Foster

Here is one way to find and flag your duplicates. However, there are many more approaches which can be found in the FAQ on MrExcel and on the web by searching on "Find Duplicates Excel VBA".

Code:
Sub mit()
Dim sh As Worksheet, rng As Range
Set sh = Sheets(1) 'Edid sheet name
Set rng = sh.Range("B2:B151")
For Each c In rng
If WorksheetFunction.CountIf(rng, c.Value) > 1 Then
c.Interior.ColorIndex = 15
x = x + 1
End If
Next
MsgBox "There were " & x & " cells flagged as duplicates"
End Sub
Code:
 
Upvote 0
This can also be done without vba by using conditional formatting.
In B2, conditionally format as Formula Is and use the formula:
Code:
=COUNTIF(B$2:B$151,B2)>1
and then format to suit.
Then use the format painter to copy that format to your entire range B2:B151.

This way the background color doesn't need to be (manually) changed back when there are no more duplicates.

Hope it helps.
 
Upvote 0

Forum statistics

Threads
1,202,965
Messages
6,052,834
Members
444,603
Latest member
dustinjmangum

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