VBA – Reverse colors in MS Excel

Today I was working with the Excel color styles and I tought that they are actually pretty well made. But for some reason I wanted to have a reverse of the styles and I did not want to waste time to define a custom style for the reverse styles. Thus, I tought of writing a simple macro and I managed to write it pretty fast.

ExcelStyles

 

Actually the code is trivial – it takes in a loop each cell of the selected area and assigns its font color to its background and vice versa. Here is how it works:

ReverseColors

And last but not least – here comes the code:

Public Sub Reverse()

    Dim rSelectedRange  As Range
    Dim lColorBack      As Long
    Dim lColorFont      As Long
    
    'Dim DefinedRange    As Range
    'Set DefinedRange = Range("L56:U82")
    
    For Each rSelectedRange In Selection 'DefinedRange
        lColorBack = rSelectedRange.Interior.Color
        lColorFont = rSelectedRange.Font.Color
        
        rSelectedRange.Interior.Color = lColorFont
        rSelectedRange.Font.Color = lColorBack
    Next rSelectedRange

End Sub

Enjoy it! 🙂