Visual basic macro- changing the colour of specific text

烈酒焚心 提交于 2019-12-24 18:19:04

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/16627054/visual-basic-macro-changing-the-colour-of-specific-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!