正如标题所说,我正在寻找一种方法来改变某个范围内的细胞颜色,具体取决于它们是否低于或高于阈值标准。由于我希望每次更改阈值时都会重新着色,这是我的代码到目前为止,但我在根据rgb值定义颜色代码的行上不断出现溢出异常
Option Explicit ' Force explicit variable declaration
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim thresholdValue As Double
Dim resetColumnStart As Integer
Dim resetRowStart As Integer
Dim resetRowEnd As Integer
Dim ii, kk As Integer
Dim lightColor As Integer
Dim darkColor As Integer
Dim cellInRange As Excel.Range
thresholdValue = Sheets("ThresholdValues").Range(Cells(Target.Row, Target.Column), Cells(Target.Row, Target.Column))
If Target.Column = 2 Then
If Target.Row = 3 Then
resetColumnStart = 11
lightColor = RGB(242, 221, 220)
darkColor = RGB(217, 151, 149)
ElseIf Target.Row = 4 Then
resetColumnStart = 18
lightColor = RGB(219, 229, 241)
darkColor = RGB(149, 179, 215)
Else
Exit Sub
End If
Else
Exit Sub
End If
resetRowStart = 3
For ii = 2 To 4 Step 1
Sheets(ii).Activate
resetRowEnd = Range("A65536").End(xlUp).Row
For kk = 1 To 7 Step 2
'reset the background colour for each data sheet
With Range(Cells(resetRowStart, resetColumnStart + kk), Cells(resetRowEnd, kk))
.Interior.Color = lightColor
.Font.Color = RGB(0, 0, 0)
End With
With Range(Cells(resetRowStart, kk + 1), Cells(resetRowEnd, kk + 1))
.Interior.Color = darkColor
.Font.Color = RGB(255, 255, 255)
End With
Next kk
Next ii
'color the values that are below the threshold for each data sheet
For ii = 2 To 4 Step 1
Sheets(ii).Activate
resetRowEnd = Range("A65536").End(xlUp).Row
currentRange = Range(Cells(resetRowStart, resetColumnStart), Cells(resetRowEnd, resetColumnStart + 6))
For Each cellInRange In currentRange
If cellInRange.Value < thresholdValue Then
cellInRange.Interior.Color = RGB(0, 255, 255)
cellInRange.Font.Color = RGB(255, 0, 0)
End If
Next cellInRange
Next ii
End Sub
我对VBA编码完全不熟悉,所以我似乎缺少一些必要的东西,我希望你可以帮助我,因为编码应该很容易,而且在没有做实际工作的情况下我花了很多时间花在花哨的东西上
答案 0 :(得分:2)
您的代码无法工作的一个原因是,Integer类型无法保存您尝试传递的高值。整数具有16位边界,意味着最高和最低值为-32,768到32,767。现在RGB(242,221,220)的实际值是14,474,738,超出了16位边界。
您可以做的是更改以下内容
Dim lightColor As Integer -> ... as Long
Dim darkColor As Integer -> ... as Long
长变量的边界为-2,147,483,648到2,147,483,647,应满足您的需要。