mercredi 16 décembre 2020

Conditional Formatting in MS Word using VBA

Good day,

I'm trying to make an efficient conditional formatting work in Microsoft Word with an VBA, that will be very similar to the formatting known from Excel.

My current solution

enter image description here

I have a 4th column with an IF statement in a field that checks if the value in Column 2 is less equal or higher than in Column 3, combined with this VBA for conditional formatting:

Sub UBC()
    color "No", wdRed
    color "Yes", wdBrightGreen
End Sub

Function color(text As String, backgroundColor As WdColorIndex)
    Dim r As Word.Range

    Set r = ActiveDocument.Content

    With r.Find
       Do While .Execute(findText:=text, MatchWholeWord:=True, Forward:=True) = True
          If r.Tables.Count > 0 Then
            If r.Cells(1).ColumnIndex = 4 Then
                r.Cells(1).Shading.BackgroundPatternColorIndex = backgroundColor
            End If
          End If
       Loop
    End With
End Function

The result I want to achieve

enter image description here

I want to eliminate the 4th column and use the VBA to do the check what's now handled by the IF statement. On top of that, I would also like to use RGB or HEX color codes instead of the wdColorIndex library.

Can somebody help me out modifying the current code?

Aucun commentaire:

Enregistrer un commentaire