I’m new to StackOverflow and VBA. I am an Expert with all aspects of Excel except writing code in VBA from scratch.
What I am trying to do is apply an color from the index to the interior of a cell if it contains a specific term. Here is what I have:
Sub ConditionalFormatting()
Do Until ActiveCell = ""
If ActiveCell = "STAR DISTRICT" Then
ActiveCell.Interior.ColorIndex = 50
ElseIf ActiveCell = "STAR SCHOOL" Then
ActiveCell.Interior.ColorIndex = 50
ElseIf ActiveCell = "HIGH PERFORMING" Then
ActiveCell.Interior.ColorIndex = 43
ElseIf ActiveCell = "SUCCESSFUL" Then
ActiveCell.Interior.ColorIndex = 34
ElseIf ActiveCell = "ACADEMIC WATCH" Then
ActiveCell.Interior.ColorIndex = 38
ElseIf ActiveCell = "LOW PERFORMING" Then
ActiveCell.Interior.ColorIndex = 22
ElseIf ActiveCell = "AT RISK OF FAILING" Then
ActiveCell.Interior.ColorIndex = 18
ElseIf ActiveCell = "FAILING" Then
ActiveCell.Interior.ColorIndex = 3
Else: ActiveCell.Interior.ColorIndex = 1
End If
ActiveCell.Offset(1, 0).Select
Loop
End Sub
The options are:
Star District or School,
High Performing,
Successful,
Academic Watch,
Low Performing,
At Risk of Failing,
Failing
This code works for one column (except for the bottom two terms) but it will not work anywhere else in the worksheet. When I try it anywhere else, all of the Cells turn Black (or ColorIndex = 1) no matter what the cell contains.
Any help would be greatly appreciated.
Trenton
Without seeing your input data in your Excel spreadsheet, it is hard to say exactly why this is true:
This code works for one column (except for the bottom two terms) but it will not work anywhere else in the worksheet. When I try it anywhere else, all of the Cells turn Black (or ColorIndex = 1) no matter what the cell contains.However, String comparison by default in VBA is a binary comparison, meaning it will be case sensitive and you are comparing
ActiveCellto various upper case strings. If your Excel Spreadsheet contains anything but all upper case, all of the tests will fail.You need to do one of 2 things. First, you can add
Option Compare Textto the top of your code sheet. That will change all comparisons toTextinstead ofBinarycomparisons.Or you can wrap each
ActiveCellin aUCASEfunction, that will capitalize any value in the active cell before performing the comparison:EDIT:
As you mentioned in your comments, the problem was trailing spaces in the cell values, the appropriate code fix is to wrap
ActiveCellin aTrimfunction. And you can nest functions inside of each other like:This would trim any trailing and leading spaces from the value in
ActiveCellthen make it upper case to compare to your flagged value.