Colour Functions in Excel
Colour Functions in Excel
Excelprovidesessentiallynosupportinworksheetfunctionsforworkingwithcellcolors.
However,colorsareoftenusedinspreadsheetstoindicatesomesortofvalueor
category.Thuscomestheneedforfunctionsthatcanworkwithcolorsonthe
worksheet.ThispagedescribesanumberoffunctionsforVBAthatcanbecalledfrom
worksheetcellsorotherVBAprocedures.
AQuickIntroductionToColors
Likeeverythingelseincomputers,acolorisreallyjustanumber.Anycolorthatcanbe
displayedonthecomputerscreenisdefinedintermsofthreeprimarycomponents:a
redcomponent,agreencomponent,andabluecomponent.Collectively,theseare
knownasRGBvalues.TheRGBcolormodeliscalledan"additive"modelbecauseother,
nonprimarycolors,suchasviolet,arecreatedbycombiningthered,green,andblue
primarycolorsinvaryingdegrees.Violet,forexample,isroughlyahalfintensityredplus
ahalfintesityblue.Eachprimarycolorcomponentisstoredasanumberbetween0and
255(or,inhex,&H00to&HFF).Acolorisa4bytenumberoftheformat00BBGGRR,
whereRR,GG,andBBvaluesaretheRed,Green,andBluevalues,eachofwhichis
between0and255(&HFF).Ifallcomponentvaluesare0,theRGBcoloris0,whichis
black.Ifallcomponentvaluesare255(&HFF),theRGBcoloris16,777,215(&H00
FFFFFF),orwhite.Allothercolorscombinationsofvaluesforthered,green,andblue
components.TheVBARGBfunctioncanbeusedtocombinered,green,andbluevalues
toasingleRGBcolorvalue.
USAGENOTE:Thispagewillusethetermsbackground,fill,andinteriorinterchangably
torefertothebackgroundofacell.ThepropertermistheInteriorPropertyofaRange
object.
ItisworthdrawingattentiontothecomponentvaluesinanLongRGBvalue.Theleftto
rightorderofcolorsasstoredinanRGBvalueisBlue,Green,Red.Thisistheoppositeof
thelettersinthenameRGB.Keepthisinmindwhenusinghexliteralstospecifyacolor.
(Fortunately,theorderofparameterstotheRGBfunctionisRed,Green,Blue.)
TheColorpalette
ExcelsupportscolorsforfontsandbackgroundfillsthroughwhatiscalledtheColor
palette.Thepaletteisanarrayorseriesof56RGBcolors.Thevalueofeachofthose56
colorsmaybeanyofthe16millionavailablecolors,butthepalette,andthusthe
numberofdistinctcolorsinaworkbook,islimitedto56colors.TheRGBvaluesinthe
paletteareaccessedbytheColorIndexpropertyofaFontobject(forthefontcolor)or
theInteriorobject(forthebackgroundcolor).TheColorIndexisanoffsetorindexinto
thepaletteandthushasavaluebetweeen1and56.Inthedefault,unmodifiedpalette,
the3rdelementinthepaletteistheRGBvalue255(&HFF),whichisred.
Whenyouformatacell'sbackgroundtored,forexample,youareactuallyassigningto
theColorIndexpropertyoftheInterioravalueof3.Excelreadsthe3intheColorIndex
property,goestothe3rdelementofthepalettetogettheactualRGBcolor.Ifyou
modifythepalette,saybychangingthe3rdelementfromred(255=&HFF)toblue
(16,711,680=&HFF0000),allitemsthatwereonceredarenowblue.Thisisbecausethe
ColorIndexpropertyremainsequalto3,butvalueofthe3rdelementinthepalettewas
changedfromredtoblue.
YouchangethevaluesinthedefaultpalettebymodifyingtheColorsarrayofthe
Workbookobject.Forexample,tochangethecolorreferencedbyColorIndexvalue3to
blue,use
Workbooks("SomeBook.xls").Colors(3)=RGB(0,0,255)
Inadditiontothe56colorsinthepalette,therearetwospecialvaluesusedwithcolors,
whichwewillencounterlater.ThesearexlColorIndexNone,whichspecifiesthatno
colorhasbeenassigned,andxlColorIndexAutomatic,whichspecifiesthatasystem
defaultcolor(typicallyblack)shouldbeused.
NOTE:Thesefunctionswork
onlywithExcel's56color
pallet.Theydonotsupport
themecolorsorcolorsnotin
the56colorpallet,orcolors
thataretheresultof
ConditionalFormatting..
DisplayingTheCurrentWorkbookpalette
Youcanusesomeverysimplecodetodisplaythecurrentsettingsofthecolorpalette.
Thefollowingcodewillchangethecolorofthefirst56cellsintheactiveworksheetto
thepalettecolors.Therownumberisthesameasthecolorindexnumber.So,cellA3,
whichisinrow3,willbethecolorassignedtocolorindex3.
SubDisplaypalette()
DimNAsLong
ForN=1To56
Cells(N,1).Interior.ColorIndex=N
NextN
EndSub
Ifyouhavemodifiedasworkbook'spalettebyusingWorkbook.Colors,youcanresetthe
palettebacktothedefaultvalueswithWorkbooks("SomeBook.xls").ResetColors.
ColorsInACellOrRange
Thisdiscussionofcolors,theColorpalette,andtheColorIndexpropertyleadsustothe
fundamentalFunctionofmostofthecodedescribedonthispage.The
ColorIndexOfOneCellfunctionreturnsthecolorindexofeitherthebackgroundorthe
fontofacell.Theproceduredeclarationisshownbelow.
FunctionColorIndexOfOneCell(CellAsRange,OfTextAsBoolean,_
DefaultColorIndexAsLong)AsLong
Youcandownloadamodulefilethatcontainsallthecodeonthis
page.ThevariousprocedureswithinthemodColorFunctions.bas
modulecallupononeanother,soyoushouldimporttheentire
moduleintoyourproject,ratherthancopyingsingleprocedures.
Here,Cellisthecellwhosecoloristoberead.OfTextiseitherTrueorFalseindicating
whethertoreturnthecolorindexoftheFont(OfText=True)orthebackground(OfText
=False).TheDefaultColorIndexparameterisacolorindexvalue(1to56)thatistobe
returnedifnospecificcolorhasbeenassignedtotheFont(xlColorIndexAutomatic)or
thebackgroundfill(xlColorIndexNone).IfyousetOfTexttoTrue,youshouldmostlikely
setDefaultColorIndexto1(black).IfyousetOfTexttoFalse,youshouldset
DefaultColorIndexto2(white).Forexample,ifrangeA1hasabackgroundfillequalto
red(ColorIndex=3),thecode:
DimResultAsLong
Result=ColorIndexOfOneCell(Cell:=Range("A1"),OfText:=False,DefaultColorIndex:=1)
willreturn3.Thiscanbecalleddirectlyfromaworksheetcellwithaformulalike:
=COLORINDEXOFONECELL(A1,FALSE,1)
ThecompleteColorIndexOfOneCellfunctionfollows:
FunctionColorIndexOfOneCell(CellAsRange,OfTextAsBoolean,_
DefaultColorIndexAsLong)AsLong
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'ColorIndexOfOneCell
'ThisreturnstheColorIndexofthecellreferencedbyCell.
'IfCellreferstomorethanonecell,onlyCell(1,1)is
'tested.IfOfTextTrue,theColorIndexoftheFontpropertyis
'returned.IfOfTextisFalse,theColorIndexoftheInterior
'propertyisreturned.IfDefaultColorIndexis>=0,this
'valueisreturnediftheColorIndexiseitherxlColorIndexNone
'orxlColorIndexAutomatic.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
DimCIAsLong
Application.VolatileTrue
IfOfText=TrueThen
CI=Cell(1,1).Font.ColorIndex
Else
CI=Cell(1,1).Interior.ColorIndex
EndIf
IfCI<0Then
IfIsValidColorIndex(ColorIndex:=DefaultColorIndex)=TrueThen
CI=DefaultColorIndex
Else
CI=1
EndIf
EndIf
ColorIndexOfOneCell=CI
EndFunction
PrivateFunctionIsValidColorIndex(ColorIndexAsLong)AsBoolean
SelectCaseColorIndex
Case1To56
IsValidColorIndex=True
CasexlColorIndexAutomatic,xlColorIndexNone
IsValidColorIndex=True
CaseElse
IsValidColorIndex=False
EndSelect
EndFunction
Byitself,theColorIndexOfOneCellfunctionisoflimitedutility.However,itisusedby
anotherfunction,ColorIndexOfRange,whichreturnsanarrayofcolorindexvaluesfora
rangeofcells.Thedeclarationforthisfunctionisshownbelow:
FunctionColorIndexOfRange(InRangeAsRange,_
OptionalOfTextAsBoolean=False,_
OptionalDefaultColorIndexAsLong=1)AsVariant
Here,InRangeistherangewhosecolorvaluesaretobereturned.OfTextiseitherTrue
orFalseindicatingwhethertoexaminethecolorindexoftheFont(OfText=True)orthe
backgroundfill(OfText=Falseoromitted)ofthecellsinInRange.TheDefaultColorIndex
valuespecifiesacolorindextobereturnediftheactualcolorindexvalueiseither
xlColorIndexNoneorxlColorIndexAutomatic.Thisfunctionreturnsasitsresultanarray
ofcolorindexvalues(1to56)ofeachcellinInRange.
YoucancallColorIndexOfRangeasanarrayformulafromarangeofcellstoreturnthe
colorindexsofanotherrangeofcells.Forexample,ifyouarrayenter
=ColorIndexOfRange(A1:A10,FALSE,1)
intocellsB1:B10,B1:B10willlistthecolorindexesofthecellsinA1:A10.
ThecompletecodeforColorIndexOfRangeisshownbelow:
FunctionColorIndexOfRange(InRangeAsRange,_
OptionalOfTextAsBoolean=False,_
OptionalDefaultColorIndexAsLong=1)AsVariant
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'ColorIndexFromRange
'Thisfunctionreturnsanarrayofvalues,eachofwhichis
'theColorIndexofacellinInRange.IfInRangecontainsboth
'multiplerowsandmultiplecolumns,thearrayistwodimensional,
'numberofrowsxnumberofcolumns.IfInRangeiseitherasingle
'roworasinglecolumn,thearrayissingledimensional.If
'InRangehasmultiplerows,thearrayistransposedbefore
'returningit.TheDefaultColorIndexindicateswhatcolor
'indextovaluetosubstituteforxlColorIndexNoneand
'xlColorIndexAutomatic.IfOfTextisTrue,theColorIndex
'ofthecell'sFontpropertyisreturned.IfOfTextisFalse
'oromitted,theColorIndexofthecell'sInteriorproperty
'isreturned.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
DimArr()AsLong
DimNumRowsAsLong
DimNumColsAsLong
DimRowNdxAsLong
DimColNdxAsLong
DimCIAsLong
DimTransAsBoolean
Application.VolatileTrue
IfInRangeIsNothingThen
ColorIndexOfRange=CVErr(xlErrRef)
ExitFunction
EndIf
IfInRange.Areas.Count>1Then
ColorIndexOfRange=CVErr(xlErrRef)
ExitFunction
EndIf
If(DefaultColorIndex<1)Or(DefaultColorIndex>56)Then
ColorIndexOfRange=CVErr(xlErrValue)
ExitFunction
EndIf
NumRows=InRange.Rows.Count
NumCols=InRange.Columns.Count
If(NumRows>1)And(NumCols>1)Then
ReDimArr(1ToNumRows,1ToNumCols)
ForRowNdx=1ToNumRows
ForColNdx=1ToNumCols
CI=ColorIndexOfOneCell(Cell:=InRange(RowNdx,ColNdx),_
OfText:=OfText,DefaultColorIndex:=DefaultColorIndex)
Arr(RowNdx,ColNdx)=CI
NextColNdx
NextRowNdx
Trans=False
ElseIfNumRows>1Then
ReDimArr(1ToNumRows)
ForRowNdx=1ToNumRows
CI=ColorIndexOfOneCell(Cell:=InRange.Cells(RowNdx,1),_
OfText:=OfText,DefaultColorIndex:=DefaultColorIndex)
Arr(RowNdx)=CI
NextRowNdx
Trans=True
Else
ReDimArr(1ToNumCols)
ForColNdx=1ToNumCols
CI=ColorIndexOfOneCell(Cell:=InRange.Cells(1,ColNdx),_
OfText:=OfText,DefaultColorIndex:=DefaultColorIndex)
Arr(ColNdx)=CI
NextColNdx
Trans=False
EndIf
IfIsObject(Application.Caller)=FalseThen
Trans=False
EndIf
IfTrans=FalseThen
ColorIndexOfRange=Arr
Else
ColorIndexOfRange=Application.Transpose(Arr)
EndIf
EndFunction
YoucanusetheColorIndexOfRangefunctioninothercode,as:
SubAAA()
DimVAsVariant
DimNAsLong
DimRRAsRange
SetRR=Range("ColorCells")
V=ColorIndexOfRange(InRange:=RR,OfText:=False,DefaultColorIndex:=1)
IfIsError(V)=TrueThen
Debug.Print"***ERROR:"&CStr(V)
ExitSub
EndIf
IfIsArray(V)=TrueThen
ForN=LBound(V)ToUBound(V)
Debug.PrintRR(N).Address,V(N)
NextN
EndIf
EndSub