I want to write a bit of code that changes the interior color of a cell if a condition is met. This condition is: if a value (date) of a given cell like today's date < 20 then the interior color of that cell is changed.
I want these changes to be applied to four cells to the right (4 columns). The sub only works for one cell. Any ideas what is wrong? Is there something wrong with the loop?
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
If Target.Column = 8 Then
For i = 2 To i = 6
If Target.Offset(0, i).Value - Date < 20 Then
Target.Offset(0, i).Interior.Color = rgbRed
Else: Target.Offset(0, i).Interior.Color = rgbWhite
End If
Next i
End If
End Sub
For i = 2 To i = 6
Change it to
For i = 2 To 5
To 5 because you want to change only four cells, with the offset 2, 3, 4 & 5.
Update
If you want to stop the formatting if a cell value is empty, then exit from the loop when this condition is met:
For i = 2 To 5
If Trim(Target.Offset(0, i).Value) = "" Then
Exit For
End If
...
Next i
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.