Colour by code in Excel with VBA - Part 3
- 0 0
-
shares
Following on from the previous entries ( * see page list ) , in this post, we'll be looking at a few more methods to colour ranges / cells to achieve easy visual categorisation.
Here's a few quick scripts / examples that you can use in your own projects.
These are as usual intended to help learn / use as a basis for your own scripts.
Example 1 - Using the user selected ( Ribbon ) colours in a Sub
You've probably wondered why this isn't exposed as a Variable / Method to be able to access as you would with any other object in Excel, and as yet ( July 2020 ) , I can't find any official documentation a to why.
Up in the 'Home' section of the Ribbon, you have the two handy swatches, Fill Colour and Font Colour respectively.
Wouldn't it be useful to be able to access these, rather than having to use a colour picker on your scripts?
Have a look at the script below - this one method of getting those colours into a usable form.
I just threw in the gradient part there as one method of using the colours.
The useful part is the two lines
Application.CommandBars.ExecuteMso ("CellFillColorPicker")
Application.CommandBars.ExecuteMso ("FontColorPicker")
These methods essentially act like you clicked the swatches and applies the colour ( font or fill ) to the selected cell.
To then capture these, simply access/save the cell colour to a variable.
A simpler example -
Maybe one day, we'll be able to reference it via the Workbook / Application as something like Workbook.Swatch.FillColor or something.
As of now, this is the most reliable method I've found.
Example 2 - Sum or Count by colour in range.
Since this is a user defined function, you may need to hit F9 to get it to update, since Excel won't typically auto-calc.
The code checks for instances in the referenced range that match its cell's colour, and returns either a sum or a count based on that. Years ago I used something similar for tracking holiday in an excel calendar. Again, this may not be that efficient for performance etc, but may be useful to someone somewhere, particularly prototyping or simpler sheets like the above example, where it's only a handful of cells.