aspire89
aspire89

Reputation: 535

Text with different styles in one paragraph Word VBA

I want to have bold and not bold text in one line.

    With objWrdDoc
        .Styles.Add ("S2")
        .Styles.Add ("S3")
        .Styles("S2").Font.Bold = True
        .Styles("S3").Font.Bold = False
    End With
    With objWrdApp.Selection
        .TypeParagraph
        .Style = objWrdDoc.Styles("S2")
        .TypeText Text:="I want to have bold "
        .Style = objWrdDoc.Styles("S3")
        .TypeText Text:="and not bold text in one line."
    End With

As a result, the entire text is not bold.

Upvotes: 1

Views: 699

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25703

While working with the Selection object feels "intuitive", it's not as accurate for writing code to manipulate Word as using Range objects. You can think about a Range as being an invisible selection, with the important differences that

  • code can work with multiple Range objects
  • the user can't affect where a Range is (clicking on the screen or pressing arrow keys changes a Selection)
  • tracking where a Range is at any given point in the code is reliable

Changing the code in the question to work with a "target" Range could look as follows.

(Note that I've also added Style objects for the styles being defined. It's much more reliable and a lot less typing to work with objects, rather than constructs such as objWrdDoc.Styles("S3").)

   Dim S2 as Word.Style, S3 as Word.Style 'As Object if using late-binding
   With objWrdDoc
        Set S2 = .Styles.Add("S2")
        Set S3 = .Styles.Add("S3")
        S2.Font.Bold = True
        S3.Font.Bold = False
    End With

    Dim objRange as Word.Range 'As Object if using late-binding
    Set objRange = objWrdApp.Selection.Range

    With objRange
        .Text = vbCr 'Chr(13) = paragraph mark
        'The new text should follow the inserted paragraph mark
        'Like pressing right-arrow to "collapse" a selection
        .Collapse wdCollapseEnd

        'When working with ranges, apply the formatting after writing the text
        .Text = "I want to have bold "
        .Style = S2

        .Collapse wdCollapseEnd
        .Text = "and not bold text in one line."
        .Style = S3
    End With

Upvotes: 2

Related Questions