Search code examples
excelvbafor-loopmsgbox

For each Loop but Without Looping in Message Box


Below code simply states that for my range, if it contains a value of 1 (or 100%) or greater then highlight it in red.

But I want to know respond (in case conditional is met) a message box without having to go through the next procedure, which will pop the message box as many times as there are red cells (for how many cells meet the condition x >= 1)

Is there a way to do this, to have just one message box pop up if condition is met; if condition is not met, another message box will pop up, like MsgBox("good to process")

I've tried looping out the message box but doesn't appear to work

 Sub myCode()

    Dim iRow As Range, cell As Range

    Set iRow = Range("J16:M43")

    For Each cell In iRow

        If cell.Value >= 1 Then            'message box here will repeat

            cell.Interior.Color = 255

        End If

    Next

End Sub

Solution

  • Essentially you need to set a variable to 'remember' if the condition is met.

    Sub myCode()
        Dim iRow As Range, cell As Range, conditionMet as Boolean
        conditionMet=False
        Set iRow = Range("J16:M43")
        For Each cell In iRow
            If cell.Value >= 1 Then            
                cell.Interior.Color = 255
                conditionMet = True
            End If
        Next
        If conditionMet Then
            'Message for condition met
        Else 
            'Message for condition not met
        End if
    End Sub