代码的作用是如果Col X和Y包含日期,则将整行的颜色标记为黄色 如果只有X包含日期,则整行为红色 但如果X和Y为空,则将其着色为绿色。在最后一个条件。
如果符合条件,我无法让我的代码在整行上着色。
Dim i As Long
Dim lrX As Long 'last row with a filled cell in column X
Dim lrY As Long 'last row with a filled cell in column Y
Dim lr As Long 'max of lrX and lrY
Dim ws As Worksheet
Set ws = ActiveSheet
lrX = Range("X" & Rows.Count).End(xlUp).Row
lrY = Range("Y" & Rows.Count).End(xlUp).Row
lr = Application.WorksheetFunction.Max(lrX, lrY)
For i = 2 To lr 'my data starts in row 1, otherwise change this
If IsDate(ws.Range("X" & i).Value) Then
If IsDate(ws.Range("Y" & i).Value) Then
ws.Range("a" & i).EntireRow.Interior.Color = vbYellow 'both X and Y have a date value, so Yellow
Else
ws.Range("a" & i).EntireRow.Interior.Color = vbRed 'only X has a date
If (.Cells(i, 24).Value = "") And _
(.Cells(i, 25).Value = "") Then
.Rows(i).EntireRow.Interior.ColorIndex = 4 ' 4: Green
End If
End If
Next i
答案 0 :(得分:0)
您的代码无效的几个原因:
If (.Cells(i, 24).Value = "") And (.Cells(i, 25).Value = "") Then
但缺少With
对象的ws
语句。If
且只有2 x End If
。If IsDate(ws.Range("X" & i).Value) Then
作为第一个If
条件,因此如果“X”列中的值不是日期,则会保留所有循环(因为其他2 x If
只有在您首先通过If
)时才会检查您的身份。尝试下面的代码(代码注释中的解释):
Dim i As Long
Dim lrX As Long 'last row with a filled cell in column X
Dim lrY As Long 'last row with a filled cell in column Y
Dim lr As Long 'max of lrX and lrY
Dim ws As Worksheet
Set ws = ActiveSheet
lrX = Range("X" & Rows.Count).End(xlUp).Row
lrY = Range("Y" & Rows.Count).End(xlUp).Row
lr = Application.WorksheetFunction.Max(lrX, lrY)
With ws ' <-- added the with statement
For i = 2 To lr 'my data starts in row 1, otherwise change this
' first check if both cells are empty
If .Range("X" & i).Value = "" And .Range("Y" & i).Value = "" Then
.Rows(i).Interior.ColorIndex = 4 ' 4: Green
ElseIf IsDate(.Range("X" & i).Value) Then
If IsDate(.Range("Y" & i).Value) Then
.Rows(i).Interior.Color = vbYellow 'both X and Y have a date value, so Yellow
Else
.Rows(i).Interior.Color = vbRed 'only X has a date
End If
End If
Next i
End With
答案 1 :(得分:0)
你也可以用公式做这样的事情。您可以修改该函数以处理更多逻辑和颜色。
如果表达式为true,则会将行着色为绿色。您将颜色指定为RGB。
=ColorRowIF(A1=B1, 1, 181, 0)
或者在你的情况下
=ColorRowIF(IsDate(A1), 1, 181, 0)
Public Function ColorRowIF(Condition As Boolean, r As Integer, g As Integer, b As Integer) As String
Dim row As Integer
row = Application.Caller.row
If Condition = True Then
ActiveSheet.Evaluate "ColorRow(" & row & ", " & r & ", " & g & ", " & b & ")"
Else
'ws.Rows(r).Interior.Color = vbRed
End If
ColorRowIF = Condition
End Function
Public Sub ColorRow(row As Integer, r As Integer, g As Integer, b As Integer)
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Rows(row).Interior.Color = RGB(r, g, b)
End Sub
Function IsDate(CellDate As Date) As Boolean
If CellDate >= 1 And CellDate <= #12/31/2199# Then
' 1 is equal to January 1, 1900
IsDate = True
Else
IsDate = False
End If
End Function