View Single Post
 
Old 02-19-2020, 12:00 PM
Jennifer Murphy's Avatar
Jennifer Murphy Jennifer Murphy is offline Windows XP Office 2007
Competent Performer
 
Join Date: Aug 2011
Location: Silicon Valley
Posts: 234
Jennifer Murphy is on a distinguished road
Default

I tweaked the code a bit. Here is a working macro. The target text must be in column 1 and the first row is assumed to be a header.

Code:
Sub TblHiLite()

Const MyName As String = "TblHiLite"
'Const Blue As Long = 15849926   'Light blue (198,217,241)
Const Blue As Long = 15853019   'Light blue (219,229,241)
Const White As Long = 16777215  'No highlighting

'Abort if the cursor is not in a table
If Selection.Information(wdWithInTable) <> True Then
  MsgBox "The cursor is not in a table", vbOKOnly, MyName
  Exit Sub
End If

Application.ScreenUpdating = False
Dim Row As Long           'Row number (loop index)
Dim HiLiteColor As Long   'The ?????
Dim TgtTextNew As String  'The target text string
Dim TgtTextOld As String  'The previous target text string

HiLiteColor = Blue                'Initialize color
With Selection.Tables(1)          'Focus the selection on the table
  For Row = 2 To .Rows.Count         'Loop through all row but the header
    TgtTextNew = Split(.Cell(Row, 1).Range.Text, vbCr)(0) 'Get next text string
    If TgtTextNew <> TgtTextOld Then  'If it's a new section
      TgtTextOld = TgtTextNew           'Save the text
                                        'Switch colors
      If HiLiteColor = White Then HiLiteColor = Blue Else HiLiteColor = White
    End If
    .Rows(Row).Shading.BackgroundPatternColor = HiLiteColor 'Apply highlighting
  Next Row
End With
  
Application.ScreenUpdating = True

End Sub
Reply With Quote