user1058322
user1058322

Reputation: 189

Different styles within the same Word Table cell using VBA

I have a XLS to Word document automation project where 2 strings String1 and String2 needs to be assigned to a Word table cell. The challenge is to have String1 in red italics font style and String2 in black normal font style. How do i achieve this ?

My present code makes all text to red itallic, which is the default table font style.

With wdoc.Tables(pos)
     .Rows(1).Cells(1).Range.Text = String1
     wapp.Selection.Font.Italic = False
     wapp.Selection.Font.Color = wdColorAutomatic
     .Rows(1).Cells(1).Range.Text = .Rows(1).Cells(1).Range.Text & String2
End with

Upvotes: 0

Views: 3344

Answers (1)

Kazimierz Jawor
Kazimierz Jawor

Reputation: 19077

The first idea I could think of is to use references to the range based on the position of your text within the whole document. The below code find values of two properties: .Start and .End of your cell text, check length of both String1 and String2 texts. All are used as Document.Range(Start,End) parameters. So, the code will look as follows (add it after your code:

With wdoc.Tables(pos).Rows(1).Cells(1).Range
        With wdoc.Range(.Start, .Start + Len(String1)).Font
            .Italic = True
            .Color = vbRed
        End With
        With wdoc.Range(.End - Len(String2), .End).Font
            'do nothing assuming text is black/standard
            'or change to black if necessary
        End With
End With

Upvotes: 1

Related Questions