I created some interesting visualizations that rely on the ability of VBA code to set different color substrings in Excel. For a cell containing a row, the syntax works as follows: rCell.Characters(start,end).Font.Color=SomeColour
My application builds lines and sets color values ββin one step, adding new lines to existing values ββand then setting the color of a new line. This did not work. Starting with a full line and then coloring several substrings works .
Two simple procedures 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
Two subprograms provide two different results, shown below:
For longer lines with more sub-segments, this is even worse. I am using Excel 2010.
So is it my fault or is it a mistake? Is there a better way to create and color strings from VBA?