【问题标题】:Is it possible to color every group of duplicate values in a unique color?是否可以用唯一的颜色为每组重复值着色?
【发布时间】:2019-10-22 03:36:47
【问题描述】:

我有一个 Excel 表,在 C 列中有大量条目,其中有一些是重复值。 我有这段代码,它基本上遍历整个 C 列,检查每组重复值并用特定颜色为它们着色。

Sub ColorCompanyDuplicates()

Worksheets("Master Filtered").Activate

    Dim xRg As Range
    Dim xTxt As String
    Dim xCell As Range
    Dim xChar As String
    Dim xCellPre As Range
    Dim xCIndex As Long
    Dim xCol As Collection
    Dim I As Long

    Dim lastrow As Long
lastrow = Cells(Rows.Count, 1).End(xlUp).Row


    On Error Resume Next
    If ActiveWindow.RangeSelection.Count > 1 Then
      xTxt = ActiveWindow.RangeSelection.AddressLocal
    Else
      xTxt = ActiveSheet.UsedRange.AddressLocal
    End If
    Set xRg = ThisWorkbook.Worksheets("Master Filtered").Range("C4:C" & lastrow)

    If xRg Is Nothing Then Exit Sub
    xCIndex = 2
    Set xCol = New Collection
    For Each xCell In xRg
      On Error Resume Next
      xCol.Add xCell, xCell.Text
      If Err.Number = 457 Then
        xCIndex = xCIndex + 1
        Set xCellPre = xCol(xCell.Text)
        If xCellPre.Interior.ColorIndex = xlNone Then xCellPre.Interior.ColorIndex = xCIndex
        xCell.Interior.ColorIndex = xCellPre.Interior.ColorIndex
      ElseIf Err.Number = 9 Then
        MsgBox "Too many duplicate companies!", vbCritical, "Kutools for Excel"
        Exit Sub
      End If
      On Error GoTo 0
    Next
End Sub

从某种意义上说,它实际上是在用相同的颜色为 C 列中的相同值着色。

但是,我的问题是我实际上希望这段代码用 UNIQUE 颜色为每组重复值着色。我的代码没有这样做。它为不同的重复值组重复相同的颜色。

您是否知道如何修改此代码以使 C 列中的每组重复值具有唯一的不同颜色?

谢谢你:)

【问题讨论】:

  • 一种 unique 颜色可能与现有颜色非常相似(例如,比较 rgb(255,254,253)rgb(256,255,254))... 想到一件事:使用 RGB并递增rgb(x,y,z),您可以在其中递增 x、y 或 z,从属(每个为 0-256)。请注意,StackOverflow 的目标是objective 问题,这些问题是单一答案,而不是主观答案或讨论。就目前而言,这个问题对于接近Too Broad 是可行的。请更新您的帖子以更客观。
  • 你做到了吗?

标签: excel vba colors duplicates


【解决方案1】:

不使用 colorIndex,而是按照 Cyril 在 cmets 中的建议旋转 RGB 值。

if If xCellPre.Interior.Pattern = xlNone then xcell.interior.color = RGB((xCIndex * 159) Mod 256, (xCIndex * 68) Mod 256, (xCIndex * 47) Mod 256)

值 159、68 和 47 会给你一个很好的随机感觉,让你在一段时间内不会看到相似的颜色。 mod 256 部分确保值在允许的 0-255 范围内。

【讨论】:

  • 感谢您的帮助@GregViers。我将此行“If xCellPre.Interior.ColorIndex = xlNone Then xCellPre.Interior.ColorIndex = xCIndex”更改为这一行“If xCellPre.Interior.ColorIndex = xlNone Then xCell.Interior.Color = RGB((xCIndex * 159) Mod 256 , (xCIndex * 68) Mod 256, (xCIndex * 47) Mod 256)" 但是当我运行宏时它不再为单元格着色
  • 尝试将条件更改为If xCellPre.Interior.Pattern = xlNone
  • 我尝试这样做,但没有任何改变。单元格没有被填充不同的颜色。 @GregViers
猜你喜欢
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 2022-01-24
  • 2017-02-08
  • 2020-08-25
  • 2013-09-08
相关资源
最近更新 更多