我正在尝试创建VBA脚本,以在用户在单元格中输入任何值时突出显示特定范围的单元格。例如,我的单元格范围将为a1:a5,如果用户在该范围内的任何单元格中输入了任何值,则单元格a1至a5将以所需的颜色突出显示。我是VBA的新用户,搜索了一会后,发现下面的代码可能有用。寻求建议。谢谢。
Private Sub Highlight_Condition(ByVal Target As Range)
Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Application.EnableEvents = False
For i = lastRow To 1 Step -1
If .Range("C" & i).Value = "" Then
Debug.Print "Checking Row: " & i
.Range("A" & i).Interior.ColorIndex = 39
.Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
Next i
Application.EnableEvents = True
End With
End Sub
Edit:尝试编辑teylyn给定的代码,以便在删除单元格值的情况下从单元格中删除高亮显示,但是我似乎找不到解决方案。 (原始代码将在单元格中有输入时突出显示单元格,但是,如果删除单元格值,则突出显示将保留在那里。)
If Not Intersect(Target, Range("A12:F12")) Is Nothing Then
With Range("A12:F12").Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ElseIf IsEmpty(Range("A12:F12").Value) = True Then
With Range("A12:F12").Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65536
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
答案 0 :(得分:1)
此代码执行您所描述的操作,即,当编辑该范围内的任何单元格时,为范围A1至A5设置填充颜色。
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:A5")) Is Nothing Then
With Range("A1:A5").Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
End Sub
此代码需要放在工作表模块中。
编辑:如果您希望在五个单元格都没有值的情况下使突出显示消失,则可以尝试以下变体:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim valCount As Long
If Not Intersect(Target, Range("A1:A5")) Is Nothing Then
' a cell in Range A1 to A5 has been edited
' we don't know if that edit was adding or deleting a cell, so ...
' ... we count how many cells in that range contain values
valCount = WorksheetFunction.CountA(Range("A1:A5"))
If valCount > 0 Then
' the range has values, so highlight
With Range("A1:A5").Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Else
' the range has no values, so remove the highlight
With Range("A1:A5").Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
End If
End Sub