简体   繁体   English

根据内容设置表格单元格的颜色

[英]Set the color of a table cell depending on the content

I'm trying to write a VBA code in MS Word 2016 in order to fill cells containing a certain string ( "–" in my case).我正在尝试在 MS Word 2016 中编写 VBA 代码,以填充包含特定字符串(在我的情况下为"–" )的单元格。 I have tried something like this:我试过这样的事情:

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

However, for some reason, it has no effect when executed.但是,由于某种原因,它在执行时不起作用。 How could this task be done?这个任务怎么完成?

Note - It is good to have Option Explicit at the top of the module to help you point out undeclared variable.注意 - 最好在模块顶部使用Option Explicit来帮助您指出未声明的变量。 oCell is not declared and I assume it's a typo of cCell oCell未声明,我认为这是cCell的拼写错误

To check if a string contains a certain string, you can use InStr to check if returns a non-0 value (0 means not found)要检查字符串是否包含某个字符串,可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM