根据 Excel 使用宏在 Word 中创建条件格式

Using a macro to create conditional formatting in Word as per Excel

我有一个 Excel 文档,它具有条件格式,可以更改单元格的背景颜色,具体取决于所选的特定 [下拉] 文本。例如,是,将单元格背景更改为绿色,否更改为红色,未知更改为黄色,不适用于灰色。

都是简单的东西。

然后我需要通过邮件合并到 Word 文档,以使用 Excel table 填充 Word 文档 - Word 文档还有其他非 excel 相关文本。

由于没有遇到单元格的条件格式,我在宏中使用了下面提到的代码来更改 Word 中的背景颜色。它运行,但似乎在第一个循环之后,它似乎因错误而崩溃 - Runtime error 5907 - there is no table at this location.

代码 r.Cells(1).Shading.BackgroundPatternColorIndex = backgroundColor 中的行以黄色突出显示。

我的编码水平很基础,所以我不知道出了什么问题。

如果有人能够提供简单解决方案的见解,我将不胜感激。

感谢

Dim r As Range

Sub UBC()
    color "No", wdRed
    color "Yes", wdGreen
    color "Unknown", wdYellow
    color "Not Applicable", wdGray50
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

Word 有可能(很可能)在 table 单元格外找到字符组合。最安全的是测试找到的词是否实际上是 in a table。 (注意:我还将变量声明 Dim r 放在函数中...)

Sub UBC()
    color "No", wdRed
    color "Yes", wdGreen
    color "Unknown", wdYellow
    color "Not Applicable", wdGray50
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
            r.Cells(1).Shading.BackgroundPatternColorIndex = backgroundColor
          End If
       Loop
    End With
End Function