Home » excel » What VBA string object can you use to modify paragraph

What VBA string object can you use to modify paragraph

Posted by: admin May 14, 2020 Leave a comment


I am looking for a string object which i can declare within Excel VBA, which I can manipulate the paragraph style.
I know you can do this with the Range object, however I am actually building a rich text string pro grammatically, then allocating that text to the result of a function.

see here.

Function makestring(char As String) As String
    Dim myString As String
    myString = "hello world" & char
    myString = myString & "this is the second line"
    myString.Characters(1.11).Font.color = Red ' this line is not valid
    makestring = myString
End Function
How to&Answers:

You cannot assign a font color to a string the way you propose in your pseudo code. The proper way to do this would be to assign the font color to a range object when you insert the string into the document.

The following line of pseudo code suggests to me, that you only want a portion of the string to be in a certain color:

myString.Characters(1.11).Font.color = Red ' this line is not valid

For example, insert the string “Red and blue” in cell A1. The following code will change the font color of the subString “Red” in the string in cell A1 to red:

With Range("A1").Characters(Start:=1, Length:=3).Font
    .Color = RGB(255, 0, 0) 'red
End With

When inserting the string returned by your function, simply split it up by carriage return and then assign the appropriate font colors. The following subroutine takes as parameters the range in which your string is to be inserted and the string itself and then alternates between red and black font color for each line of text:

Sub ChangeLineFontColors(myString As String, rng As Range)

    Dim i As Integer, j As Integer, sLen As Integer
    Dim vItem As Variant

    If rng Is Nothing Then Exit Sub
    If myString <> vbNullString Then

        Application.ScreenUpdating = False

        rng.Value = myString

        If InStr(1, myString, Chr(10)) > 0 Then
            vItem = Split(myString, Chr(10)) ' change delimiter to Chr(13) or 'vbNewline', if required
            j = 1
            For i = LBound(vItem) To UBound(vItem)
                sLen = Len(vItem(i))
                With rng.Characters(Start:=j, Length:=sLen).Font
                    If i Mod 2 = 0 Then
                        .Color = RGB(255, 0, 0) 'red
                        .Color = RGB(0, 0, 0) 'black
                    End If
                    j = j + sLen + 1
                End With
            Next i
        End If

        Application.ScreenUpdating = True

    End If

End Sub