简体   繁体   中英

vba FOR to validate color of cells in a range

I am doing a macro to check and validate all cells by colorindex. kindly help me if there is wrong in my code. Many Thanks.

    Sub Validate()
Dim rng As Range: Set rng = Application.Range("CATALOG!B2:F98")
Dim cel As Range
Dim i As Boolean

i = False

For Each cel In rng
With cel
    If .Interior.ColorIndex = 6 Then
        If .EntireRow.Hidden = False Then
            i = True
        End If
    End If
   End With
   Next cel

 If i = True Then
  MsgBox "yellow"
Else
  MsgBox "none"
End If

End Sub

It's pretty unclear what you're asking, but there are two ways:

1) first, when you want to check if every cell in range has .Interior.ColorIndex = 6 . Then your code should look like:

Sub Validate()
Dim rng As Range: Set rng = Application.Range("CATALOG!B2:F98")
Dim cel As Range
Dim i As Boolean

i = True
For Each cel In rng.Cells
    If Not cel.Interior.ColorIndex = 6 Then
        i = False
        Exit For 'we found cell with different color, so we can exit loop
    End If
Next cel

If i = True Then
    MsgBox "yellow"
Else
    MsgBox "none"
End If

End Sub

2) you want to check if any cell has .Interior.ColorIndex = 6 . Then it should look like:

Sub Validate()
Dim rng As Range: Set rng = Application.Range("CATALOG!B2:F98")
Dim cel As Range
Dim i As Boolean

i = False
For Each cel In rng.Cells
    If cel.Interior.ColorIndex = 6 Then
        i = True
        Exit For 'we found cell with the color, so we can exit loop
    End If
Next cel

If i = True Then
    MsgBox "yellow"
Else
    MsgBox "none"
End If

End Sub

Of what I've gatered you are trying to loop through all non hidden cells and see if they have a yellow background color, and if they are yellow they need to change based on a input.

Sub Validate()

Dim rng As Range: Set rng = Application.Range("CATALOG!B1:F98")
Dim cel As Range

For Each cel In rng
    With cel
        If .Interior.ColorIndex = 6 Then
            If .EntireRow.Hidden = False Then
                .Interior.ColorIndex = InputBox("please input new colorIndex", "SetColorIndex")
            End If
        End If
   End With
Next cel

End Sub

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM