Sample Macro to Find Duplicate Entries in a Column (142591)



The information in this article applies to:

  • Microsoft Excel 97 for Windows
  • Microsoft Excel for Windows 95
  • Microsoft Excel for Windows 5.0

This article was previously published under Q142591

SUMMARY

The Microsoft Visual Basic for Applications sample macro in this article finds duplicate cell entries within a column and changes the color of the cell containing the duplicate entry to red.

MORE INFORMATION

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. NOTE: In order for the macro to work correctly, make sure the following conditions are met:
  • The column in which you want to find duplicates must be sorted based on values in that column.

    -and-
  • The first cell in the column in which you want to find duplicates must be selected.

Sample Visual Basic Code

   Sub FindDups ()
      '
      ' NOTE: You must select the first cell in the column and
      ' make sure that the column is sorted before running this macro.
      '
      ScreenUpdating = False
      FirstItem = ActiveCell.Value
      SecondItem = ActiveCell.Offset(1, 0).Value
      Offsetcount = 1
      Do While ActiveCell <> ""
         If FirstItem = SecondItem Then
           ActiveCell.Offset(Offsetcount,0).Interior.Color = RGB(255,0,0)
           Offsetcount = Offsetcount + 1
           SecondItem = ActiveCell.Offset(Offsetcount, 0).Value
         Else
           ActiveCell.Offset(Offsetcount, 0).Select
           FirstItem = ActiveCell.Value
           SecondItem = ActiveCell.Offset(1,0).Value
           Offsetcount = 1
         End If
      Loop
      ScreenUpdating = True
   End Sub
				

Modification Type:MinorLast Reviewed:10/11/2006
Keywords:kbdtacode kbhowto kbProgramming KB142591