I've been building some interesting visualizations that rely on VBA code's ability to set different colours for substrings in Excel. For a cell containing a string the syntax works like this rCell.Characters(start,end).Font.Color=SomeColour
My application builds the strings and sets the colour values in one step by appending new strings onto the existing values and then setting the colour of the new string. This didn't work. Starting with a complete string and then colouring multiple sub-strings does work.
Two simple routines illustrate the difference:
Sub TestColourString1()
'designed to show that substring colour can be done to preexisting string
Dim rngTestString As Range
Set rngTestString = Range("colour_string")
rngTestString.Value = "red green blue"
rngTestString.Characters(1, 4).Font.Color = RGB(255, 0, 0)
rngTestString.Characters(5, 10).Font.Color = RGB(0, 255, 0)
rngTestString.Characters(11, 14).Font.Color = RGB(0, 0, 255)
End Sub
Sub TestColourString2()
'designed to show that setting colour while building string doesn't work
Dim rngTestString As Range
Set rngTestString = Range("colour_string")
rngTestString.Value = "red "
rngTestString.Characters(1, 4).Font.Color = RGB(255, 0, 0)
rngTestString.Value = rngTestString.Value & "green "
rngTestString.Characters(5, 10).Font.Color = RGB(0, 255, 0)
rngTestString.Value = rngTestString.Value & "blue"
rngTestString.Characters(11, 14).Font.Color = RGB(0, 0, 255)
End Sub
The two routines result in the two different results shown below:
For longer strings with more subsegments it is even worse. I'm using Excel 2010.
So is this my fault or is it a bug? Is there a better way to create and colour strings from VBA?
Assigning the .Value
does not magically figure how to append to the existing data. It erases the old data and puts in the new data.
If the characters had colouring, the colour of the first character is used to colour the new string.
If you want the actual appending, same as if you manually used the formula bar in Excel, then append using .Characters
:
Dim rngTestString As Range
Set rngTestString = Range("colour_string")
Range("colour_string").Characters(Len(Range("colour_string").Value) + 1).Text = "red "
rngTestString.Characters(1, 4).Font.Color = RGB(255, 0, 0)
Range("colour_string").Characters(Len(Range("colour_string").Value) + 1).Text = "green "
rngTestString.Characters(5, 10).Font.Color = RGB(0, 255, 0)
Range("colour_string").Characters(Len(Range("colour_string").Value) + 1).Text = "blue"
rngTestString.Characters(11, 14).Font.Color = RGB(0, 0, 255)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With