根据Excel使用宏在Word中创建条件格式 [英] Using a macro to create conditional formatting in Word as per Excel

查看:161
本文介绍了根据Excel使用宏在Word中创建条件格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Excel文档,该文档的条件格式会根据所选的特定[下拉]文本更改单元格的背景颜色.例如:是,将单元格背景更改为绿色,否更改为红色,未知更改为黄色以及不适用于灰色.

I have an Excel doc that has conditional formatting that changes the background colour of a cell, dependant upon the specific [dropdown] text that is selected. E.g Yes, changes cell background to Green, No to Red, Unknown to Yellow and Not applicable to Grey.

所有简单的东西.

然后我需要邮件合并到Word文档,以用Excel表填充Word文档-Word文档还具有其他与Excel无关的文本.

I then need to mailmerge to a Word doc to populate the Word doc with the Excel table - the Word doc also has other non-excel related text.

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

As conditional formatting of the cells does not come across, I have used the under noted code in a macro to change the background colour in Word. It runs, but seems after the first loop, it seems to crash with the error - Runtime error 5907 - there is no table at this location.

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

the line in the code r.Cells(1).Shading.BackgroundPatternColorIndex = backgroundColor is highlighted yellow.

我的编码水平是基本的,所以我不知道出了什么问题.

My level of coding is basic so I don't know what's going wrong.

如果任何人都能够提供对简单解决方案的见解,我将不胜感激.

If anyone is able to offer an insight to a simple solution, I would appreciate it.

谢谢

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可能(很可能)在表单元格之外找到一个字符组合.最安全的方法是测试找到的术语是否实际上在表中. (注意:我也将变量声明Dim r放在了函数中...)

It's possible (likely) that Word is finding a character combination outside a table cell. Safest is to test whether the found term is actually in a table. (Note: I've also put the variable declaration Dim r inside the Function...)

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使用宏在Word中创建条件格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆