Avatar of Andreas Hermle
Andreas Hermle
Flag for Germany asked on

Conditionally apply blue font color to table rows using VBA

Dear Experts:

The following macro (courtesy of the MS Word 'Sage' Graham Skan from EE) applies a blue font color on all table rows where the text entry in the 8th column of the tables is 'blue'

I got a a new requirement:

It is always the last column where this text entry is found. Hence instead of hard coding the 8th column, Line 6 and Line 7 should be tweaked to accomodate the new requirement.

Sub BlueRow()
    Dim tbl As Table
    Dim rw As row
    For Each tbl In ActiveDocument.Tables
        For Each rw In tbl.Rows
            If Len(rw.Cells(8).Range.Text) = 6 Then
                If InStr(1, rw.Cells(8).Range.Text, "blue", vbTextCompare) Then
                    rw.Range.Font.Color = wdColorBlue
                End If
            End If
        Next rw
    Next tbl
End Sub

Open in new window


Help is very much appreciated. Thank you very much in advance.

Regards, Andreas
VBAMicrosoft Word

Avatar of undefined
Last Comment
Andreas Hermle

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Ryan Chong

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Ryan Chong

not too sure about the condition:

If Len(rw.Cells(8).Range.Text) = 6 Then

Open in new window

which you may simply remove it.

to become:

Sub BlueRow()
    Dim tbl As Table
    Dim rw As Row
    For Each tbl In ActiveDocument.Tables
        For Each rw In tbl.Rows
            If InStr(1, rw.Cells(rw.Cells.Count).Range.Text, "blue", vbTextCompare) Then
                rw.Range.Font.Color = wdColorBlue
            End If
        Next rw
    Next tbl
End Sub

Open in new window

Andreas Hermle

ASKER
Great Ryan, this did the trick, thank you very much for your swift help.

Regards, Andreas
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes