Macro to change text color conditionally in Excel

  Pi Ke        2012-07-07 12:53:28       39,524        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 [Reply]@ 2016-12-22 01:00:58

This tutorial is very helpful..

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

 

Anonymous [Reply]@ 2019-07-17 02:16:09

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

Thank you.



  RANDOM FUN

What happens when using low memory RAM