编辑重新阅读问题,我看到整行都将被着色,而不仅仅是名称。我还决定,如果一个可识别的名称被一个无法识别的名称替换,则应该从该行中删除该颜色。原始代码已被替换以解决这些问题。
我决定不关心我的问题的答案,因为对于我能识别的任何场景来说,下面的解决方案似乎是最简单的。
首先,您需要一些方法来确定“John Tery”将被涂成红色,而“Mary Jane”将被涂成粉红色。我决定最简单的方法是制作一个工作表NameColour
,列出所需颜色的名称。所以例程知道“John Tery”是红色的,因为它在这个列表中是红色的。我在您的列表中添加了更多名称。该例程并不关心名称中有多少个单词。
下面的代码一定要进去ThisWorkbook
。每当更改单元格时都会触发此例程。变量MonitorColNum
并MonitorSheetName
告诉例程要监视哪个表和列。任何其他单元格更改都将被忽略。如果找到匹配项,它会从 NameColour 复制名称的标准形式(如果不需要,请从代码中删除此语句)并根据需要为单元格着色。如果未找到匹配项,则将名称添加到 NameColour 以供以后指定其颜色。
希望这可以帮助。
Option Explicit
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Changed As Range)
Dim CellCrnt As Variant
Dim ColLast As Long
Dim Found As Boolean
Dim MonitorColNum As Long
Dim MonitorSheetName As String
Dim RowNCCrnt As Long
MonitorSheetName = "Sheet2"
MonitorColNum = 2
' So changes to monitored cells do not trigger this routine
Application.EnableEvents = False
If Sh.Name = MonitorSheetName Then
' Use last value in heading row to determine range to colour
ColLast = Sh.Cells(1, Columns.Count).End(xlToLeft).Column
For Each CellCrnt In Changed
If CellCrnt.Column = MonitorColNum Then
With Worksheets("NameColour")
RowNCCrnt = 1
Found = False
Do While .Cells(RowNCCrnt, 1).Value <> ""
If LCase(.Cells(RowNCCrnt, 1).Value) = LCase(CellCrnt.Value) Then
' Ensure standard case
CellCrnt.Value = .Cells(RowNCCrnt, 1).Value
' Set required colour to name
'CellCrnt.Interior.Color = .Cells(RowNCCrnt, 1).Interior.Color
' Set required colour to row
Sh.Range(Sh.Cells(CellCrnt.Row, 1), _
Sh.Cells(CellCrnt.Row, ColLast)).Interior.Color = _
.Cells(RowNCCrnt, 1).Interior.Color
Found = True
Exit Do
End If
RowNCCrnt = RowNCCrnt + 1
Loop
If Not Found Then
' Name not found. Add to list so its colour can be specified later
.Cells(RowNCCrnt, 1).Value = CellCrnt.Value
' Clear any existing colour
Sh.Range(Sh.Cells(CellCrnt.Row, 1), _
Sh.Cells(CellCrnt.Row, ColLast)).Interior.ColorIndex = xlNone
End If
End With
End If
Next
End If
Application.EnableEvents = True
End Sub