Cell Background and Foreground Color Excel VBA

Cell Background and Foreground Color Excel VBA

Interior

Object offers Color or ColorIndex property which can be set to any color using Excel inbuilt constant or RGB value. Interior object is responsible to decorate a cell background and Font property changes the font color which is known as foreground color or cells in a Range.

Fill Background

Code example

Public Sub FillBackgroundColor()
    'Declare range object
    Dim oRange As Range
    
    'Bind selection
    Set oRange = Selection
    
    'Fill background color
    oRange.Interior.Color = vbRed
    
    'memory cleanup
    Set oRange = Nothing
End Sub

Output

Change Font Color

Public Sub ChangeFontColor()
    'Declare range object
    Dim oRange As Range
    
    'Bind selection
    Set oRange = Selection
    
    'Change Font color
    oRange.Font.Color = vbBlue
    
    'memory cleanup
    Set oRange = Nothing
End Sub

Output

Fill Entire Row

Public Sub FillEntireRowBackgroundColor()
    'Declare range object
    Dim oRange As Range
    
    'Bind selection
    Set oRange = Selection
    
    'Variable to hold row number
    Dim oRowNumber As Integer
    'Get row number
    oRowNumber = oRange.Row
    
    'Rebuild range
    Set oRange = Rows(oRowNumber)
    
    'Fill entire row
    oRange.Rows(oRowNumber).Interior.Color = vbRed
    
    'memory cleanup
    Set oRange = Nothing
End Sub

Output

Next>>Executing Macro from External File

Leave a Reply

Your email address will not be published. Required fields are marked *