Consulting

Results 1 to 2 of 2

Thread: [VBA] de-highlight the highlighted color

  1. #1

    [VBA] de-highlight the highlighted color

    The following code is attached on a Userform.
    On the UF, 3 color option buttons are available for choice, named respectively oRed, oGreen, oYellow.
    Once user click on any option button, a click even is triggered with the following sub-procedure.
    Basically the code aims to remove any one of the highlighted background colors, as selected by user.

    However, it does not work well and I am confused which part goes wrong.
    This is my another attempt in learning Word VBA. Hope also to receive some advice on improving the coding.
    Thanks very much!

    Sub Dehighlight()
    Dim rng As Range
    Set rng = Selection.Range
       With Selection.Range
                    '-------------------
                    '   f
                    .Find.ClearFormatting
                    .Find.Highlight = True
                    '-------------------
                    While .Find.Execute(Wrap:=wdFindContinue, Forward:=True) And .InRange(rng)
                        If .HighlightColorIndex = Switch(oRed.Value = True, wdRed, _
                                                         oYellow.Value = True, wdYellow, _
                                                         oGreen.Value = True, wdGreen) Then
                            .HighlightColorIndex = wdNoHighlight
                        End If
                    Wend
    
    
                End With
    Unload Me
    End Sub

  2. #2
    Microsoft Word MVP 2003-2009 VBAX Guru gmaxey's Avatar
    Joined
    Sep 2005
    Posts
    3,334
    Location
    What part doesn't work well? I wouldn't have coded it that way (have never used the Switch function in over 20 years) but as best I could tell it worked.

    Here is another way:

    Private Sub oYellow_Click()
      Dehighlight wdYellow
    End Sub
    Sub Dehighlight(lngColorIndex)
    Dim oRng As Range
      Set oRng = Selection.Range
      With oRng.Find
        .ClearFormatting
        .Highlight = True
        .Wrap = wdFindStop
        .Forward = True
        Do While .Execute
          If oRng.HighlightColorIndex = lngColorIndex Then
              If oRng.InRange(Selection.Range) Then
                oRng.HighlightColorIndex = wdNoHighlight
              Else
                Exit Do
              End If
            End If
          oRng.Collapse wdCollapseEnd
        Loop
      End With
    End Sub
    Greg

    Visit my website: http://gregmaxey.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •