【问题标题】:Conditional Formatting in MS Word using VBA使用 VBA 在 MS Word 中进行条件格式设置
【发布时间】:2021-03-27 08:24:55
【问题描述】:

早安,

我正在尝试使用 VBA 在 Microsoft Word 中进行有效的条件格式设置,这与 Excel 中已知的格式非常相似。

我目前的解决方案

我在第 4 列的字段中有一个 IF 语句,用于检查第 2 列中的值是否小于或高于第 3 列中的值,并结合此 VBA 进行条件格式设置:

Sub UBC()
    color "No", wdRed
    color "Yes", wdBrightGreen
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
            If r.Cells(1).ColumnIndex = 4 Then
                r.Cells(1).Shading.BackgroundPatternColorIndex = backgroundColor
            End If
          End If
       Loop
    End With
End Function

我想要达到的结果

我想删除第 4 列并使用 VBA 来检查 IF 语句现在处理的内容。最重要的是,我还想使用 RGB 或 HEX 颜色代码而不是 wdColorIndex 库。

有人可以帮我修改当前代码吗?

【问题讨论】:

  • 似乎您需要首先确定需要应用格式的表,然后遍历每个表的行并检查第二个和第三个单元格的值每一行,并根据结果应用格式。你有没有尝试过?
  • 参见,例如:msofficeforums.com/word-vba/…Mailmerge 提示和技巧线程中的有条件地为表格单元格着色msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html
  • @macropod 我在互联网上分析了很多你的优秀代码,但我还没有找到一个适合这个特殊场合(不使用 IF 在现场)的比较值两列。我担心我的帖子中介绍的 VBA 需要从头开始完全重写
  • @TimWilliams 此文件中只有一个表。你提到的其他事情是我一直在寻找如何做的事情,但从未找到适用于这种情况的任何事情

标签: vba if-statement ms-word conditional-statements conditional-formatting


【解决方案1】:

试试这个

Sub Tester()
    Dim tbl As Table, rw As Row, v1, v2
    Set tbl = ActiveDocument.Tables(1)
    
    For Each rw In tbl.Rows
        v1 = CellValue(rw.Cells(2))
        v2 = CellValue(rw.Cells(3))
        If IsNumeric(v1) And IsNumeric(v2) Then
            v1 = CDbl(v1)
            v2 = CDbl(v2)
            Debug.Print v1, v2
            rw.Cells(2).Shading.BackgroundPatternColor = _
                     IIf(v1 <= v2, RGB(100, 250, 100), RGB(250, 100, 100))
        End If
    Next rw
End Sub

Function CellValue(c As Cell)
    Dim rv
    rv = c.Range.Text
    CellValue = Left(rv, Len(rv) - 2) 'remove "end of cell" marker
End Function

【讨论】:

  • 非常棒,完全符合预期,还为我解释了很多未来的编码。谢谢
猜你喜欢
  • 2018-05-28
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
相关资源
最近更新 更多