简体   繁体   中英

Change text font color in Word document

I wrote a small test word addon and I can't find a way to change the font color of a word. Here's my code:

var wordsList = this.Application.ActiveDocument.Words;
wordsList[i].Font.TextColor = WdColor.wdColorRed;

This won't compile because TextColor Property has no Setter (ReadOnly).

There are two ways to do it. You can either use Font.ColorIndex for simple choices or Font.Fill.ForeColor for more extensive choices. Here's some VBA:

Sub ChangeColorThisWay()
    Dim s As Range: Set s = Selection.Range
    s.Font.Fill.ForeColor = WdColor.wdColorRed
End Sub
Sub ChangeColorThatWay()
    Dim s As Range: Set s = Selection.Range
    s.Font.ColorIndex = WdColorIndex.wdBrightGreen
End Sub

Note on the Font.Fill.ForeColor one, you also have access to the RGB property and can set the font to any non-constant color, like s.Font.Fill.ForeColor.RGB = RGB(255, 255, 0) sets it to yellow.

You need to set Font.ColorIndex = Word.WdColorIndex.wdRed , not the TextColor property. Set the index to what you need and you are set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM