Thomas
Thomas

Reputation: 1208

Visual basic macro- changing the colour of specific text

Im very new to visual basic and macros. what i have been trying to do is create a macro that will look through the whole document and check to see if any of the font is red;if it is red then i want to change the red font to a white font.

I know my code is wrong but can anyone tell me what i am doing wrong?

Sub red()

  If Font.Color =wdColorRed Then
  Font.Color = -603914241
End Sub

Upvotes: 1

Views: 18773

Answers (2)

jhoe
jhoe

Reputation: 346

You can use the following which is fairly quick (no looping required for each sheet).

Sub Macro1()
Application.ScreenUpdating = False 'disable the screen from updating, i.e, avoid excel redrawing the screen after each color change we make
Application.FindFormat.Font.Color = 255
Application.ReplaceFormat.Font.Color = 16777215
Cells.Select
Selection.Replace What:="", Replacement:="", MatchCase:=False, SearchFormat:=True, ReplaceFormat:=True
Application.ScreenUpdating = True 'enable screen updating
End Sub

Font colors can be a little tricky. So to find out what color you want, select a cell and change the color to a color you need to know the number for. Then go to your developer screen and View -> Immediate Window (or hit Ctrl+G). Then in the Immediate window (should now be at the bottom of your screen, with the cell that has you color you want to know still selected, type

? Selection.Font.Color

and this will give you the color you are interested in. Then put those numbers in Application.Find/ReplaceFormat.Font.Color above.

This will work for the sheet selected, you can simply throw this in a loop and iterate over all the sheets in a workbook to change them all.

Upvotes: 3

Santosh
Santosh

Reputation: 12353

Is it what you are looking for ?

Copied from here @Todd Main Answer.

Sub ChangeColorWithReplace()
    Selection.Find.ClearFormatting
    Selection.Find.Font.Color = wdColorRed
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Font.Color = -603914241
    With Selection.Find
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchByte = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Upvotes: 1

Related Questions