基于单元格背景颜色的“清洁单元格内容”

问题描述 投票:0回答:2

我正在尝试从 Word 文档中具有“白色背景色”的表格单元格中“删除任何文本”

以下代码适用于 Excel,但不适用于 WORD

Sub colorbasedclearcontent()
    Range("C2:M11").Select
    For Each Cell In Selection
        If Cell.Interior.Color = Excel.XlRgbColor.rgbWhite Then
            Cell.ClearContents
        End If
    Next
End Sub

任何人都可以(帮助我)将其翻译成在 Word 文档中工作吗?

vba ms-word
2个回答
0
投票

您正在尝试获取单元格的对象,该对象位于表格的集合中,表格是文档对象的一部分。 Microsoft 有说明各种对象的文档

在 Excel 中,情况有所不同。单元格是范围的一部分或整个工作表是工作簿对象的一部分。

这将循环遍历所有文档表、行,然后是单元格。

Sub testTable()
Const colorCode = -603914241  ''depending on your version of white it could be a couple options.
'might also be -16777216  or 16777215


Dim t As Table, aRow As Row, aCell As Cell
For Each t In ThisDocument.Tables
    For Each aRow In t.Rows
        For Each aCell In aRow.Cells
            
            If aCell.Shading.BackgroundPatternColor = colorCode Then
                aCell.Range.Text = ""
            End If
            
        Next aCell
    Next aRow
Next t

End Sub

0
投票

假设目标表是文档中的第一个表

Sub Example()
    Dim Target As Table
    Set Target = ThisDocument.Tables(1)

    Dim c As Cell
    For Each c In Target.Range.Cells
        If c.Shading.Texture = 0 Then c.Range.Text = ""
    Next
End Sub

这将清除表格中没有阴影颜色的任何单元格。

© www.soinside.com 2019 - 2024. All rights reserved.