【发布时间】:2018-12-12 16:07:58
【问题描述】:
我需要在 Excel VBA (2016) 中编写条件格式,而不使用现有的条件格式工具。由于我是新手并且尝试了一段时间以下,我请求你帮助我。
我想写这个,例如在私有子中:对于 E18:G18 和 K1:K10 范围:
如果值 >=1,则颜色 = 绿色
如果值为
对于范围 B1:B10
如果值 >=3,则颜色 = 绿色
如果值为 0,则颜色为黄色
如果值为 0 或 "" 红色
我的代码如下 - 当我保存它时,在我的第二个定义范围 (K1:K10) 内没有任何反应,在重新打开 excel 工作簿之后也是如此。
我的第二个条件格式范围 (B1:B10) 也没有任何反应:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngObserve As Range, rngCell As Range
Set rngObserve = Intersect(Target, Range("E18:G18, K1:K10"))
If rngObserve Is Nothing Then
Exit Sub
End If
For Each rngCell In rngObserve.Cells
If Not Intersect(rngCell, rngObserve) Is Nothing Then
If rngCell.Value = vbNullString Then
rngCell.Interior.Color = xlNone
ElseIf rngCell.Value < 1 Then
rngCell.Interior.ColorIndex = 3 'red
ElseIf rngCell.Value >= 1 Then
rngCell.Interior.ColorIndex = 4 'green
Else
rngCell.Interior.ColorIndex = 3 'red
End If
End If
Next
Dim rngObserve As Range, rngCell As Range
Set rngObserve = Intersect(Target, Range("B1:B10"))
If rngObserve Is Nothing Then
Exit Sub
End If
For Each rngCell In rngObserve.Cells
If Not Intersect(rngCell, rngObserve) Is Nothing Then
If rngCell.Value = vbNullString Then
rngCell.Interior.Color = xlNone
ElseIf rngCell.Value < 3 And rgncell.Value > 0 Then
rngCell.Interior.ColorIndex = 6 'yellow
ElseIf rngCell.Value >= 3 Then
rngCell.Interior.ColorIndex = 4 'green
Else
rngCell.Interior.ColorIndex = 3 'red
End If
End If
Next
End Sub
【问题讨论】:
-
请格式化您的代码...
-
每张表只能有一个更改事件,因此您需要合并到一个子中。可能还有其他问题。你把代码放在相关的sheet模块里了吗?
-
只是好奇,你为什么要这样?
-
因为我在使用条件格式化工具和使用 vba 代码时遇到了一些麻烦。否则无法识别颜色...