编辑重读这个问题,我看到整行不仅要着色,还要着色。我还决定,如果一个被认可的名字被一个无法识别的名字取代,那么该颜色应该从该行中删除。原代码已被替换以解决这些问题。
我决定我不关心我的问题的答案,因为下面的解决方案似乎是我可以识别的任何场景的最简单的方法。
首先,您需要一些方法来识别“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
有多少不同的名字,你呢?如果只有少数人,我不会考虑条件格式。名称改变是否需要新的颜色?颜色变化是否必须是瞬间的,或者编辑完成后列表是否可以重新着色?新名字是否被添加到列表中? – 2012-04-07 09:51:06
@TonyDallimore并不多。不到10,他们是常量 – sandalone 2012-04-07 12:06:56