Reputation: 129
I have seen multiple articles about this topic but none of them helped in my case and most of them were for Excel. I want to change the font color using vba
code in word. I have tried Selection.Font.Color
but it didn't work either. I know that vba
needs a variable which have that particular word but I'm failing on doing this.
Does anyone know how to do this?
I used a workaround to replace the font color of a word using this vba
code
With Selection.Find
.ClearFormatting
.Text = "hello"
.Replacement.ClearFormatting
.Replacement.Text = "hi"
.Replacement.Font.Color = wdColorBlack 'I added this line
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
But I was looking to more a specific way to replace the font color of a word in vba.
Upvotes: 0
Views: 3731
Reputation: 166196
If you want a re-usable piece of code then something like this should be close:
Sub Tester()
ActiveDocument.Content.Font.Color = vbBlack
ColorText ActiveDocument.Content, "breaks", vbRed
ColorText ActiveDocument.Content, "it", vbBlue
ColorText ActiveDocument.Content, "with just", vbGreen
End Sub
Sub ColorText(rng As Range, strFind As String, clr As Long)
With rng.Find
.Text = strFind
.Forward = True
.Format = False
.MatchCase = False
.MatchWholeWord = True
Do While .Execute()
rng.Font.Color = clr 'rng is redefined as the found text
Loop
End With
End Sub
Upvotes: 3