Macro to change text color conditionally in Excel

  Pi Ke        2012-07-07 12:53:28       39,913        2         

Macros are small but very powerful VBA programs in Microsoft Office software. They can help us complete some repeated tasks automatically. Today, I will show you one macro example which is to change the text color conditionally. The excel file has a work sheet which contains some records of request. I want to check the status of each request, if the status of a request is approved, the text color of the status should be green; if the status of a request is rejected, the text color of the status should be red; otherwise the text color of the status should be black.

Here is the code for the macro.

Sub changeTextColor()

    GreenColor = RGB(0, 255, 0)
    RedColor = RGB(255, 0, 0)
    BlackColor = RGB(0, 0, 0)
   
    'Get number of rows in the specified column
    RowsCount = Range("C2", Range("C2").End(xlDown)).Rows.Count
   
    'Select cell
    Range("C2").Select
   
    'Loop the cells
    For x = 1 To RowsCount
        If ActiveCell.Value = "approved" Then
            'Change the text color
            ActiveCell.Font.Color = GreenColor
        ElseIf ActiveCell.Value = "rejected" Then
            'Change the text color
            ActiveCell.Font.Color = RedColor
        Else
            ActiveCell.Font.Color = BlackColor
        End If
   
        ActiveCell.Offset(1, 0).Select
    Next
   
End Sub

First, we need to define these color using RGC() function. And then we need to get the number of rows we want to check. Here we want to check the cells in column C and rows starting from 2. Finally, we will loop through all rows and use if else statements to check the status of each request and change the text color accordingly.


If later we add more and more rows to the Excel file, we only need to run this macro, the relative cells will change color accordingly.

MACRO  EXCEL  TEXT COLOR  CONDITIONALLY 

           

  RELATED


  2 COMMENTS


makmans
Dec 22, 2016 at 1:00 am

This tutorial is very helpful..

http://tutorialway.com/how-to-change-the-color-of-a-text-and-cell-in-microsoft-excel/

 

Anonymous
Jul 17, 2019 at 2:16 am

The above mentioned URL is not working. Please send the URL again.

Thank you.



  PROGRAMMER HUMOR

What happens to my computer

I have been a cleaner for my whole life. I will clean up everything wchich I don't want. Once upon a time, I was trying to move my computer to trashcan. But...what happened? Where is my computer?

  SUPPORT US