Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring colouring from Excel VBA: why do some obvious methods not work?

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: the image in two cells from excel

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?

like image 394
matt_black Avatar asked Jul 04 '12 14:07

matt_black


1 Answers

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)
like image 128
GSerg Avatar answered Oct 30 '22 15:10

GSerg