PDA

View Full Version : [VBA] de-highlight the highlighted color



smallxyz
07-09-2017, 04:10 AM
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

gmaxey
07-09-2017, 07:25 AM
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