2013-03-02 62 views
3

如何使用不同顏色突出顯示excel 2010中的多個單元格跨多個列。 我發現這個代碼,但它適用於一列。excel 2010 vba使用不同顏色突出顯示不同顏色的單元格橫跨多個列的不同重複值

Sub Highlight_Duplicate_Entry() 
     Dim cel As Variant 
     Dim myrng As Range 
     Dim clr As Long 

     Set myrng = Range("A2:A" & Range("A65536").End(xlUp).Row) 
     myrng.Interior.ColorIndex = xlNone 
     clr = 3 

     For Each cel In myrng 
      If Application.WorksheetFunction.CountIf(myrng, cel) > 1 Then 
       If WorksheetFunction.CountIf(Range("A2:A" & cel.Row), cel) = 1 Then 
       cel.Interior.ColorIndex = clr 
       clr = clr + 1 
       Else 
       cel.Interior.ColorIndex = myrng.Cells(WorksheetFunction.Match(cel.Value, myrng, False), 1).Interior.ColorIndex 
       End If 
      End If 
     Next 
    End Sub 
+0

請在Excel中使用條件格式 – 2013-03-02 18:18:22

+0

條件格式將突出顯示具有相同顏色的所有重複項。 OP希望以不同顏色突出顯示每組副本。 – 2013-06-25 13:25:40

回答

4

您需要更改範圍覆蓋多個列,這會導致您的Match功能失效。將其替換爲Find。下面的子文件將找到指定範圍內的任何重複項,並用不同的顏色突出顯示它們。

改爲如下代碼:

Sub Highlight_Duplicate_Entry() 
    Dim ws As Worksheet 
    Dim cell As Range 
    Dim myrng As Range 
    Dim clr As Long 
    Dim lastCell As Range 

    Set ws = ThisWorkbook.Sheets("Sheet1") 
    Set myrng = ws.Range("A2:d" & Range("A" & ws.Rows.Count).End(xlUp).Row) 
    With myrng 
     Set lastCell = .Cells(.Cells.Count) 
    End With 
    myrng.Interior.ColorIndex = xlNone 
    clr = 3 

    For Each cell In myrng 
     If Application.WorksheetFunction.CountIf(myrng, cell) > 1 Then 
      ' addresses will match for first instance of value in range 
      If myrng.Find(what:=cell, lookat:=xlWhole, MatchCase:=False, after:=lastCell).Address = cell.Address Then 
       ' set the color for this value (will be used throughout the range) 
       cell.Interior.ColorIndex = clr 
       clr = clr + 1 
      Else 
       ' if not the first instance, set color to match the first instance 
       cell.Interior.ColorIndex = myrng.Find(what:=cell, lookat:=xlWhole, MatchCase:=False, after:=lastCell).Interior.ColorIndex 
      End If 
     End If 
    Next 
End Sub 

添加基於註釋的結果的屏幕截圖如下,以幫助闡明如何工作的。每組副本都以單獨的顏色突出顯示。不重複的值不是彩色的: enter image description here

+0

嗨,非常感謝您的幫助,但代碼可以解決一些未突出顯示的數字。你能否提供更多幫助來解決我的問題? – 2013-03-03 11:40:07

+0

非常感謝您,但對於同一行中的重複數字,代碼沒有得到。我的數據範圍(只有數字輸入)在列中有唯一的數字,但不在行中。 – 2013-03-03 21:59:48

+0

立即嘗試。它現在應該適用於所有您需要的情況。 – 2013-03-03 22:52:46

相關問題