PDA

View Full Version : [SOLVED:] Find and Replace Colors



Obini
09-23-2013, 04:27 AM
I have a Word document where some of the words have different Background pattern colors. Now I want to replace one of the colors used to another color, using RGB.

I hoped this macro could help me, but it does not work, and obviously something is wrong:

Sub test()
' test Makro
With ActiveDocument.Range.Find
.Format = True
.Text = ""
.BackgroundPatternColor = RGB(255, 255, 0)
.Replacement.Text = ""
.Replacement.BackgroundPatternColor = RGB(255, 0, 0)
.Execute Replace:=wdReplaceAll
End With
End Sub

Can anybody help me correct the code?

Regards

Obini

SamT
09-23-2013, 08:00 PM
Obini, I changed the Title to be more Representative of your problem

Obini
09-23-2013, 10:09 PM
Thank you very much!

Jay Freedman
09-24-2013, 07:01 PM
The .Find.Execute for ReplaceAll doesn't work properly to replace background shading. This variation works:


Sub test()
Dim rg As Range
Set rg = ActiveDocument.Range
With rg.Find
.Format = True
.Text = ""
.Font.Shading.BackgroundPatternColor = wdColorYellow
.Replacement.Text = ""
While .Execute
rg.Font.Shading.BackgroundPatternColor = wdColorRed
rg.Collapse wdCollapseEnd
Wend
End With
End Sub

A secondary problem is that the .Find object doesn't have a .BackgroundPatternColor member; you have to drill down through .Find.Font.Shading to get there. And one more thing: you can use the named colors in the WdColors enumeration, like wdColorYellow, instead of having to figure out the RGB data (unless you have to deal with a custom color that isn't named).

Obini
09-24-2013, 10:49 PM
The .Find.Execute for ReplaceAll doesn't work properly to replace background shading. This variation works:


Sub test()
Dim rg As Range
Set rg = ActiveDocument.Range
With rg.Find
.Format = True
.Text = ""
.Font.Shading.BackgroundPatternColor = wdColorYellow
.Replacement.Text = ""
While .Execute
rg.Font.Shading.BackgroundPatternColor = wdColorRed
rg.Collapse wdCollapseEnd
Wend
End With
End Sub

A secondary problem is that the .Find object doesn't have a .BackgroundPatternColor member; you have to drill down through .Find.Font.Shading to get there. And one more thing: you can use the named colors in the WdColors enumeration, like wdColorYellow, instead of having to figure out the RGB data (unless you have to deal with a custom color that isn't named).

That worked. Thank you so much. I use customized colours, so I’ve replaced wdColorxxx with RGB(xxx, yyy, zzz). And that works too.