excelvbaselect-case

Why do I get random/wrong output from VBA Select Case?


I have a problem with the code below. I've just started to learn this and when I did a simple exercise, it turned out the code is working really randomly.

Sometime nothing is done, sometime only one case is being selected but never the right formatting is applied. I'm quite confused.

Could you please help on this one? ;)

Sub Colors()

Dim Check As String
Check = ActiveCell.Value
Range("A2").Select

Do While ActiveCell.Value <> ""

    Select Case Check
    Case "Red"
        ActiveCell.EntireRow.Interior.Color = RGB(200, 100, 100)
    Case "Blue"
        ActiveCell.EntireRow.Interior.Color = RGB(100, 100, 200)
    Case "Green"
        ActiveCell.EntireRow.Interior.Color = RGB(100, 200, 100)
    End Select

    ActiveCell.Offset(1, 0).Select

Loop

End Sub

Solution

  • Check in constant for every iteration of the loop, so Select Case Check always evaluates to the same thing, and the outcome of the execution of this procedure depends solely on the value of whatever cell happened to be the ActiveCell when the procedure was invoked.

    Avoid Select and Activate, but to fix your current immediate problem, you'll want to replace Check with ActiveCell here, and maybe explicitly invoke its Value member:

    Select Case ActiveCell.Value
    

    The Check assignment becomes redundant, and now the loop will successively activate a cell starting in A2, evaluate its content, and set the interior color accordingly.

    This could also be achieved without any VBA code, using conditional formatting rules applied to the entire row. Consider using conditional formatting instead.