我正在尝试使用VBA有条件地格式化一个范围内的单元格。我的目标是每次选择一个单元格时,每个包含相同文本的单元格都将被格式化。
我的代码:
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
问题在于,每次选择一个单元格时,全部格式化范围内的单元格(而不仅仅是与所选单元格中文本相同的单元格)。
答案 0 :(得分:2)
这对我有用:
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
答案 1 :(得分:0)
蒂姆已经提供了你想做的事情,所以选择他的答案 我会将此作为另一种方法发布给任何可能在这个问题中偶然发现的人。
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