搜索特定列后,如何使用 MS Word VBA 代码为具有特定文本的单元格着色?

问题描述

我正在用 word 处理一个表格,并使用以下代码查找带有“是”和“否”字样的单元格并为其着色。在第 3 列和第 4 列中,我使用什么代码专门执行此操作?

Dim r As Range

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

    Function color(text As String,backgroundColor As WdColorIndex)
        Set r = ActiveDocument.Range
           With r.Find
           do while .Execute(FindText:=text,MatchWholeWord:=True,Forward:=True) = True
        r.Cells(1).Shading.BackgroundPatternColorIndex = backgroundColor
           Loop
        End With
    End Function

解决方法

您需要使用 Range.Information 属性来确定匹配项是否在表中。然后,您将使用单元格的 ColumnIndex 属性来确定它是否在所需的列中。

Function color(text As String,backgroundColor As WdColorIndex)
   Dim r As Range
   Set r = ActiveDocument.Content
   With r.Find
      Do While .Execute(FindText:=text,MatchWholeWord:=True,Forward:=True) = True
         If r.Information(wdWithInTable) Then
            With r.Cells(1)
               If .ColumnIndex = 3 Or .ColumnIndex = 4 Then .Shading.BackgroundPatternColorIndex = backgroundColor
            End With
         End If
      Loop
   End With
End Function