搜索文本,在多个单元格中应用背景色

时间:2019-01-29 11:05:08

标签: vba ms-word

任何人都可以向我解释我如何修改此工作代码,以便它可以完成以下两项操作: 1)还要选择带有找到的文本的单元格下方的单元格,并将相同的背景色也应用于新单元格。 2)还要选择包含找到的文本的单元格下面的单元格,然后将颜色应用于字体。

Sub ScratchMacro()
Dim r As Range
Dim oRng As Word.Range
Dim wdOrange As Long
Red = 255
Purple = 16711875
Black = 0
Pink = 11796735
Blue = 16711680
Orange = 41215
Green = 1954333
Yellow = 60671
Set r = ActiveDocument.Range
With r.Find
    Do While .Execute(FindText:="The Text You are Searching For", MatchWholeWord:=True, Forward:=True)
      If r.Information(wdWithInTable) Then
        If r.InRange(r.Cells(1).Range) Then
        r.Cells(1).Shading.BackgroundPatternColor = Yellow
        End If
      End If
    Loop
End With
End Sub

非常感谢!

1 个答案:

答案 0 :(得分:0)

诀窍是从“找到的”单元格中获取行和列的索引,将行索引增加1,然后使用该索引来标识表中的单元格。

请注意,最好将Option Explicit放在所有代码“页面”的顶部,这意味着需要声明所有变量名。我使用了它,因此所有这些颜色在下面的代码示例中都“变暗了”。

Sub ScratchMacro()
    Dim r As Range
    Dim tbl As word.Table
    Dim rIndex As Long, cIndex As Long, r2Index as Long
    Dim cel As word.Cell, cel2 as Word.Cell
    Dim Red As Long, Purple As Long, Black As Long, _
         Pink As Long, Blue As Long, Green As Long, Yellow As Long

    Red = 255
    Purple = 16711875
    Black = 0
    Pink = 11796735
    Blue = 16711680
    Green = 1954333
    Yellow = 60671
    Set r = ActiveDocument.content
    With r.Find
        Do While .Execute(findText:="The Text You are Searching For", MatchWholeWord:=True, Forward:=True)
          If r.Information(wdWithInTable) Then
            Set tbl = r.Tables(1)
            rIndex = r.Cells(1).RowIndex
            r2Index = r.Cells(1).RowIndex + 1
            cIndex = r.Cells(1).ColumnIndex
            Set cel = tbl.Cell(rIndex, cIndex)
            Set cel2 = tbl.Cell(r2Index, cIndex)
            cel.Range.Shading.BackgroundPatternColor = Blue
            cel2.Range.Shading.BackgroundPatternColor = Blue
            cel.Range.Font.ColorIndex = wdGreen
          End If
        Loop
    End With
End Sub