我对VBA还是很陌生,但是我现在是从零开始,但是,我一直在寻找一种代码,该代码可以使用随机分配的颜色自动填充单元格。
我需要编写代码以应用于一列数据,并让它在填充值时为每个单元格提供不同的颜色,但具有相同条目的颜色单元格则相同...
希望这有意义吗?一个例子是:
谢谢。
答案 0 :(得分:3)
尝试以下操作。
它使用字典来收集唯一的“单词”,并在字典项数之间插入以生成关联的颜色。条件格式设置规则使用不同的“单词”来应用
注释:
代码:
Option Explicit
Public Sub FormatMatchingNames()
Dim wb As Workbook, wsTarget As Worksheet, lastRow As Long, formatRange As Range
Set wb = ThisWorkbook
Set wsTarget = wb.Worksheets("Sheet7") 'change as appropriate
Application.ScreenUpdating = False
lastRow = GetLastRow(wsTarget)
If Not lastRow <= 2 Then
Set formatRange = wsTarget.Range("A2:A" & lastRow) 'Adjust as required
Else
MsgBox "End row is before start row"
Exit Sub
End If
Dim codeColoursDictionary As Dictionary
Set codeColoursDictionary = GetDistinctCodeCount(formatRange.Value2)
wsTarget.Cells.FormatConditions.Delete
AddFormatting formatRange, codeColoursDictionary
Application.ScreenUpdating = True
End Sub
Public Function GetDistinctCodeCount(ByVal sourceData As Variant) As Dictionary 'as object if latebound
''LATE binding
' Dim distinctDict As Object
' Set distinctDict = CreateObject("Scripting.Dictionary")
''Early binding add reference to VBE > tools > references > Microsoft scripting runtime
Dim distinctDict As Scripting.Dictionary
Set distinctDict = New Scripting.Dictionary
Dim currentCode As Long
For currentCode = LBound(sourceData, 1) To UBound(sourceData, 1)
If Not distinctDict.Exists(sourceData(currentCode, 1)) Then
distinctDict.Add sourceData(currentCode, 1), Application.WorksheetFunction.RandBetween(13434828, 17777777) + distinctDict.Count
End If
Next currentCode
Set GetDistinctCodeCount = distinctDict
End Function
Public Function GetLastRow(ByVal wsTarget As Worksheet) As Long
With wsTarget
GetLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'change to column containing last row up to which you want to format
End With
End Function
Public Sub AddFormatting(ByVal formatRange As Range, ByVal codeColoursDictionary As Dictionary) 'note pass as object if late binding
Dim key As Variant, counter As Long
For Each key In codeColoursDictionary.keys
counter = counter + 1
With formatRange
.FormatConditions.Add Type:=xlExpression, Formula1:="=$A2=""" & key & """"
.FormatConditions(counter).StopIfTrue = False
With .FormatConditions(counter).Interior
.PatternColorIndex = xlAutomatic
.Color = codeColoursDictionary(key)
End With
End With
Next key
End Sub
表格: