vba条件格式与Worksheet_SelectionChange

我试图有条件地使用VBA格式化单元格。 我的目标是每次select一个单元格时,每个包含相同文本的单元格将被格式化。

我的代码:

Private Sub Worksheet_SelectionChange(ByVal t As Range) Cells.FormatConditions.Delete Range("B2:K29").Select Selection.FormatConditions.Add Type:=xlTextString, String:=t.Value, _ TextOperator:=xlContains With Selection.FormatConditions(1).Font .Bold = True .Italic = False .TintAndShade = 0 End With End Sub 

问题是,每次我select一个单元格时,范围内的所有单元格将被格式化(而不仅仅是与所选单元格中文本相同的单元格)。

这适用于我:

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim c As Range Set c = Target.Cells(1) Me.Cells.FormatConditions.Delete If Len(c.Value) > 0 Then With Me.Range("B2:K29").FormatConditions.Add(Type:=xlTextString, _ String:=c.Value, TextOperator:=xlContains) With .Font .Bold = True .Italic = False .TintAndShade = 0 End With End With End If End Sub 

你想做的事情已经由Tim提供了,所以select他的答案。
对于任何可能在这个问题上磕磕绊绊的人来说,

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) On Error GoTo halt Application.EnableEvents = False Me.Cells.FormatConditions.Delete If Target.Cells.Count = 1 And Not IsEmpty(Target) Then With Me.Range("A1").FormatConditions.Add(Type:=xlTextString, _ String:=Target.Value, TextOperator:=xlContains) With .Font .Bold = True .Italic = False .TintAndShade = 0 End With .ModifyAppliesToRange Me.Range("B2:K29") End With End If forward: Application.EnableEvents = True Exit Sub halt: MsgBox Err.Description Resume forward End Sub