【问题标题】:Set the color of a table cell depending on the content根据内容设置表格单元格的颜色
【发布时间】:2021-09-23 05:52:42
【问题描述】:

我正在尝试在 MS Word 2016 中编写 VBA 代码,以填充包含某个字符串的单元格(在我的情况下为 "–")。我尝试过这样的事情:

Sub CellsColorFill()
    Dim tTable As Table
    Dim cCell As Cell

    For Each tTable In ActiveDocument.Range.Tables
        For Each cCell In tTable.Range.Cells
            If cCell.Range = "-" Then
                Selection.Shading.Texture = wdTextureNone
                Selection.Shading.ForegroundPatternColor = wdColorAutomatic
                Selection.Shading.BackgroundPatternColor = -603923969
            End If
        Next
    Next
    Set oCell = Nothing
    Set tTable = Nothing
End Sub

但是,由于某种原因,它在执行时没有效果。这个任务怎么做?

【问题讨论】:

  • 请注意,"it doesn't work." 是完全无用的错误描述。请描述会发生什么与您预期会发生什么。或者告诉你卡在哪里或错误。
  • 问题是执行的时候没有效果。我怀疑不满足 if 中的条件,尽管我不确定为什么(我是 VBA 新手)。
  • 您的代码不起作用的原因是因为您正在使用两个不相关的对象,SelectioncCell。您的代码循环通过表格中的单元格,但应用更改,而不是单元格,而是在代码运行之前选择的任何内容(或者可能只是插入点的位置)。

标签: vba ms-word word-2010


【解决方案1】:

注意 - 最好在模块顶部添加 Option Explicit 以帮助您指出未声明的变量。 oCell 未声明,我认为这是 cCell 的错字

要检查一个字符串是否包含某个字符串,可以使用InStr检查是否返回非0值(0表示未找到)

Option Explicit

Sub CellsColorFill()
    Dim tTable As Table
    Dim cCell As Cell

    For Each tTable In ActiveDocument.Range.Tables
        For Each cCell In tTable.Range.Cells
            If InStr(cCell.Range.Text, "-") <> 0 Then
                cCell.Shading.Texture = wdTextureNone
                cCell.Shading.ForegroundPatternColor = wdColorAutomatic
                cCell.Shading.BackgroundPatternColor = -603923969
            End If
        Next
    Next
End Sub

【讨论】:

  • 完美运行,正是我想要达到的效果!
  • @User1234321 - 我忘了提到你在这一点上犯的一个错误,蒂莫西关于SelectionoCell的评论中指出了这一点,请阅读他的评论。
猜你喜欢
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
  • 2014-03-17
  • 2019-09-30
  • 2013-01-03
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
相关资源
最近更新 更多