Coloring Identical Company Names

by Allen Wyatt
(last updated May 19, 2016)

11

Connie has a worksheet that has company names in each cell of column B. They are grouped under a region heading (Northeast, West, etc.) in column A. She would like to apply conditional formatting to the company names so that if a name appears in more than one region, it shows up using a background or text color that makes the matching companies easy to find. This means that if one company is formatted as red, no other company should appear as red (it should appear as a different color, such as blue or green). Connie isn't sure how to set this up or if it can even be done with conditional formatting.

There is a way to mark duplicates using conditional formatting; just follow these general steps:

  1. Select the cells that contain your company names.
  2. Display the Home tab of the ribbon and click the Conditional Formatting tool in the Styles group.
  3. Select New Rule. Excel displays the New Formatting Rule dialog box.
  4. Click the Format Only Unique or Duplicate Values option at the top of the dialog box.
  5. Make sure that Duplicate is selected in the drop-down list in the bottom half of the dialog box. (See Figure 1.)
  6. Figure 1. The New Formatting Rule dialog box.

  7. Click the Format button and change the formatting to reflect how you want duplicate company names to appear.
  8. Click OK to close the New Formatting Rule dialog box.

At this point all your duplicates should match whatever formatting you selected in step 6. The only problem is that all duplicates are formatted the same way. In other words, if you have two companies (ABC Company and DEF Company) and there are duplicates for those companies, they are all formatted the same way—you won't see different formatting for the two companies.

Of course, you could easily use Excel's filtering capabilities to single out duplicate companies, non-duplicate companies, or individual company names. This might be the easiest way to "zero in" on the companies you want to locate.

The only way to use conditional formatting to apply different colors to different groups of duplicate company names requires that you identify, up front, the actual duplicates. With that list in hand, you could create a series of conditional formatting rules that use formulas similar to the following:

=AND(ISNUMBER(FIND("ABC Company",B1)),COUNTIF($B$1:$B$99,"ABC Company")>1)

In this formula "ABC Company" is the company name, B1 is the first cell of the range, and B1:B99 is the full range of cells. For each formatting rule you could apply different formatting appropriate to that particular company. That means that if you knew, up front, that there were 24 different company names that had duplicates, you would need to set up 24 conditional formatting rules to handle those 24 names.

Complex, indeed. Unfortunately, there is not an easier way using conditional formatting. You could, however, forego the conditional formatting and use a macro to make your duplicates stand out. The simplest "automatic" macro we could come up with (where you don't need to know the duplicate names ahead of time) is one that examines a range of cells and sets the internal cell color based on duplicate company names.

Sub ColorCompanyDuplicates()
    Dim x As Integer
    Dim y As Integer
    Dim lRows As Long
    Dim lColNum As Long
    Dim iColor As Integer
    Dim iDupes As Integer
    Dim bFlag As Boolean

    lRows = Selection.Rows.Count
    lColNum = Selection.Column
    iColor = 2

    For x = 2 To lRows
        bFlag = False
        For y = 2 To x - 1
            If Cells(y, lColNum) = Cells(x, lColNum) Then
                bFlag = True
                Exit For
            End If
        Next y
        If Not bFlag Then
            iDupes = 0
            For y = x + 1 To lRows
                If Cells(y, lColNum) = Cells(x, lColNum) Then
                    iDupes = iDupes + 1
                End If
            Next y
            If iDupes > 0 Then
                iColor = iColor + 1
                If iColor > 56 Then
                    MsgBox "Too many duplicate companies!", vbCritical
                    Exit Sub
                End If
                Cells(x, lColNum).Interior.ColorIndex = iColor
                For y = x + 1 To lRows
                    If Cells(y, lColNum) = Cells(x, lColNum) Then
                        Cells(y, lColNum).Interior.ColorIndex = iColor
                    End If
                Next y
            End If
        End If
    Next x
End Sub

To use the macro, simply select the cells that contain the company names and then run it. The macro makes three passes through the cells. The first pass looks backward through the cells from the current one being examined; it is used to determine if there are any "backward" duplicates, because if there are than no further processing on that particular cell is needed. The second pass looks forward through the cells to determine if there are any duplicates to the current company name. If there are, then a third pass increments the cell color value and then applies it to the duplicates.

Note that the macro sets the ColorIndex property of any duplicates it finds, and it increments the variable used to set the property when it finds a new set of duplicate company names. For all those company names for which there are no duplicates, the ColorIndex property of the cell is not changed. This means there is a limit on how many companies can be marked, however—the ColorIndex can only range between 0 and 56. The values actually assigned by the macro range from 3 to 56, so it is only possible to format 54 groupings of companies.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (12673) applies to Microsoft Excel 2007, 2010, and 2013.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Preventing Straggling Heads

Undoubtedly you will want to format your document so that headings stay with the paragraph that follows the heading. Here's ...

Discover More

Using Macros in Protected Workbooks

Having problems with using macros in a protected workbook? There could be any number of causes (and solutions) as described ...

Discover More

Jumping to an Endnote

Endnotes are often used in documents to document citations and sources. You can jump from endnote to endnote using the ...

Discover More

Professional Development Guidance! Four world-class developers offer start-to-finish guidance for building powerful, robust, and secure applications with Excel. The authors show how to consistently make the right design decisions and make the most of Excel's powerful features. Check out Professional Excel Development today!

More ExcelTips (ribbon)

Defining a Single Condition

Conditional formatting is a powerful tool you can use to dynamically adjust the formatting of your worksheet. This tip ...

Discover More

Highlighting Values that are 10x a Baseline Value

Sometimes the hardest part of getting your conditional formatting rules to work properly is figuring out the proper way to ...

Discover More

Shading Based on Odds and Evens

You can use conditional formatting to add shading to various cells in your worksheet. This tip shows how you can shade cells ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 8Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 7 - 0?

2016-07-21 19:14:46

Thomson

Change

if iColor > 56 then

to

if iColor > 80 then

Assume you want 79 colors


2016-07-21 00:58:22

CTSJ

someone help please, if I want more colors, how I do it ?

iColor = iColor + 1
If iColor > 56 Then
MsgBox "Too many duplicate companies!", vbCritical
Exit Sub

Thanks,


2016-05-19 19:06:12

Thomson

If you can add another custom column, there is another way you can do conditional formatting.

Just put this formula in C1 and copy it down.

=IF(COUNTIF(B:B,B1)=1,0,MATCH(B1,B:B,0))

This will give an unique value for any duplicate name, than just apply condition formatting with colour scale.


2016-05-19 17:40:23

Dave Unger

Interesting macro Allen, here's my approach to it.

Sub ColorCompanyDuplicates2()
Dim Col As Collection
Dim Clr As Long
Dim r As Range
Dim c As Range
Dim cP As Range

On Error GoTo errTrap

Set r = Selection
' assume 1st row is heading, ignore
Set r = r.Offset(1).Resize(r.Rows.Count - 1)
Clr = 2

Set Col = New Collection

For Each c In r
Col.Add c, c.Text
nextX:
Next c

Exit Sub

errTrap:
Select Case Err.Number
Case 457
Clr = Clr + 1
' 1st cell with same value
Set cP = Col(c.Text)
' color 1st cell if not already done
If cP.Interior.ColorIndex = xlNone Then cP.Interior.ColorIndex = Clr
' color current cell same
c.Interior.ColorIndex = cP.Interior.ColorIndex
Resume nextX
Case 9
MsgBox "Too many duplicate companies!", vbCritical
End Select
End Sub


2015-04-07 11:12:43

Kate

Hi,

I have an excel sheet where costumers populate entries time by time based on general rules, so the entry is fixed. I have a mapping table about 20 countries. I would like to colour only these countries on my main sheet with conditional formatting or a rule-set but without an additional column where I use vlookup. I can set up 20 different rules with conditional formatting, but maybe you have a more professional idea as well.

To summarize: I would like to colour those countries on my main excel sheet which are listed on my mapping table.

Many thanks for your kind help in advance, Kate


2013-06-30 19:33:20

Charlie Waldron

I copied this macro to an existing spreadsheet with known duplicates in a column. I highlighted the column and got an error. The debug tool highlighted the following line:

For x = 2 To lRows

I don't understand VB, so I cannot make a correction. Can you help me with it?

Thanks,

Charlie


2013-06-09 10:05:52

MDC

@Steve: No... you're not archaic! I'm not a VBA or macro wiz (or even an apprentice!), so the information on this site is not the easiest for me to digest, especially since I don't program.

Allen makes it look so easy, coming up with a macro for this, that and the other thing, seemingly at a moment's notice. I'm very much a step by step person, and mostly self taught, so what you've described is more my style. Until I'm a pro, I need to 'see' the effect the formulas have.

My take? I take and learn what I can, and what I cannot will be there later when I'm a little more schooled!

Cheers!


2013-06-08 07:26:24

Steve Nadel

The Conditional formatting is a great tool and I use it often.

I might be archaic, but for years I would sort and then use a simple formulas to produce true/false. (i.e. A1=A2) and copy it down the column. Find the error(s) and them resort the list in the original order.


2013-06-07 04:31:45

Peter Johnson

I have used this code with Excel 2010 to scan a long list – with more duplicates than the scheme will handle. The problem I found was that the subroutine coloured some different lines the same. Looking more closely at this the problem lies in the use of.Interior.ColorIndex as described the useful range is 3 to 55. However, unfortunately within that range there are 10 pairs that result in identical colours. (e.g. 5 & 32 are both blue, 6 & 27 are both yellow, etc). To produce truly unique colours for duplicate values the way that iColor is incremented has to be modified.
.
Select Case iColor
Case 24
iColor = 33
Case 33
iColor = 35
Case 53
iColor = 55
Case Else
iColor = iColor + 1
End Select
If iColor > 56 Then
MsgBox "Too many duplicate files!", vbCritical
Exit Sub
End If
.
This reduces the number of sets of uniquely coloured multiple occurrences to 44.


2013-06-07 04:20:44

Peter Johnson

There is a flaw in the logic. The code assumes that the selection is the first lRows of the spreadsheet. This is not normally the case (e.g. if you have header rows. So you the code needs to be altered by adding two extra Dim statements
Dim lLowerBound As Long
Dim lUpperBound As Long
And then after lRows has been calculated setting the upper and lower bounds of the selection (range).
lLowerBound = Selection.Row + 1
lUpperBound = Selection.Row + lRows - 1
now loop between the lower and upper bounds. Listing just the lines that change.
For x = lLowerBound To lUpperBound

For y = lLowerBound To x - 1

Next y
….
For y = x + 1 To lUpperBound
….
Next y

For y = x + 1 To lUpperBound

Next y
….
Next x
This scans the correct selection.


2013-06-03 16:01:06

Connie

Thank you, I'll give this a try!


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.