我有VBA代码,将用户输入的日期与当前日期进行比较,并以适当的颜色填充背景。一切都很好。
现在我需要使系统检查所选行的F列中的单元格是否为空,我需要将列D、E、F着色为灰色。
代码:
Private Sub CommandButton1_Click()
Dim i As Integer
For i = Range("C5000").End(xlUp).Row To 2 Step -1 'Range upto 5000, chnge this as per your requirment'
If IsEmpty(Cells(i, 3)) Then
Cells(i, 3).Interior.Color = xlNone
ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) < 0 Then
Cells(i, 3).Interior.Color = vbGreen
ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) = 0 Then
Cells(i, 3).Interior.Color = vbYellow
ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) >= 1 And (VBA.CDate(Cells(i, 3)) - VBA.Date()) <= 4 Then
Cells(i, 3).Interior.Color = vbRed
ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) >= 5 And (VBA.CDate(Cells(i, 3)) - VBA.Date()) <= 10 Then
Cells(i, 3).Interior.Color = vbCyan
Else
Cells(i, 3).Interior.ColorIndex = xlNone
End If
Next
End Sub我会感谢你的帮助
发布于 2017-10-18 10:35:49
您还需要检查相关标准中是否存在Trim(Range("F" & i).Value) <> ""。
我还修改了当前代码的逻辑,使其能够更短更快地运行(切换到Select Case等)。
码
Private Sub CommandButton1_Click()
Dim i As Long
Dim NumofDays As Long
For i = Range("C5000").End(xlUp).Row To 2 Step -1 'Range upto 5000, chnge this as per your requirment'
Cells(i, 3).Interior.Color = xlNone ' set as inital color, only change if all criterias are met
NumofDays = CDate(Cells(i, 3)) - Date
Select Case NumofDays
Case Is < 0
Cells(i, 3).Interior.Color = vbGreen
Case 0
Cells(i, 3).Interior.Color = vbYellow
Case 1 To 4
Cells(i, 3).Interior.Color = vbRed
Case 5 To 10
Cells(i, 3).Interior.Color = vbCyan
End Select
' your 2nd criteria to color the entire row if "F" is not empty
If Trim(Range("F" & i).Value) <> "" Then Range("D" & i & ":F" & i).Interior.Color = ... ' selectyourcolor
Next i
End Sub发布于 2017-10-18 10:51:54
条件格式是最简单的,只有点击几下。
https://stackoverflow.com/questions/46807896
复制相似问题