【问题标题】:Using a macro to create conditional formatting in Word as per Excel根据 Excel 使用宏在 Word 中创建条件格式
【发布时间】:2019-02-10 19:05:23
【问题描述】:

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

所有简单的东西。

然后我需要将邮件合并到 Word 文档以使用 Excel 表格填充 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

【问题讨论】:

    标签: vba ms-word conditional


    【解决方案1】:

    Word 有可能(很可能)在表格单元格之外找到字符组合。最安全的方法是测试找到的词是否真的在 in 表中。 (注意:我还把变量声明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
    

    【讨论】:

    • 如果您在 Excel 中有一个可以测试着色条件的字段,则不需要宏。相反,请参阅 Mailmerge 提示和技巧线程中的条件着色表格单元格:msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html 或:windowssecrets.com/forums/showthread.php/…
    • @macropod 如果您希望 OP 看到它,您应该评论问题本身,而不是我的回答。或者使用 @ 符号“ping”这个人,就像我为你的名字所做的那样。在这种情况下,我自动收到了“ping”,因为您将评论发布到了答案。
    猜你喜欢
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多