Word宏用于仅从某些表格单元格中删除颜色

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

我正在使用以下宏来迭代Word文档并从其中的所有表中删除颜色,除了第一个表。

由于与使用合并字段自动填充这些文档的应用程序的表单保护问题,我们的文档绝对不能与表单字段一起使用。因此,下一个最好的方法是仅使用着色标记仍需要填充的内容,然后在打印文档之前删除着色。当此代码遍历文档时,它会删除某些表的某些边框。

我绝对不想要这个,我只想删除阴影。我不知道为什么会这样做,所以如果有人对此有任何见解,那将是最有帮助的。如果没有,如果我可以调整此宏只更改具有非白色背景颜色的单元格,那也可以。

我已经尝试了嵌套循环的几种变体,但无法让它以这种方式运行。

Sub decolordocument()
    Dim tbl As Table
    Dim first As Boolean

    first = True

    For Each tbl In ActiveDocument.Tables
        If first Then
            first = False
        Else
            tbl.Shading.BackgroundPatternColor = wdColorWhite
        End If
    Next

    MsgBox "Shaded cells in tables have been updated."
End Sub

我也试过这个代码,并删除了相同的边框效果:

Sub decolordocument()

    Dim tbl As Table
    Dim tblCount As Long
    Dim i As Long
    Dim first As Boolean

    tblCount = ActiveDocument.Tables.Count

    For i = 2 To tblCount
        With ActiveDocument.Tables(i).Shading
            .BackgroundPatternColor = wdColorWhite
        End With
    Next
    MsgBox "Shaded cells in tables have been updated."

End Sub

编辑:虽然我仍然看不出具体是什么让这些桌子失去了边界,但我发现以某种方式分割桌子会导致他们不会失去边界。我已经尽力将这一点与运气隔离开来,因为似乎只有某种组合会导致边界丢失。但是,至少我有一些有用的东西。如果任何人都可以提供一个宏,它将按照最初的要求迭代单个单元格,那么在后面的口袋里放置它可能不是一个糟糕的选择。

foreach ms-word word-vba
2个回答
1
投票

您必须使用.Shading删除背景。

我将为一个文档演示它。请按照您的代码采用它。

假设您的文档看起来像这样

试试这个代码

Option Explicit

Sub Sample()
    Dim tblCount As Long
    Dim i As Long

    '~~> Get the Tables Count
    tblCount = ActiveDocument.Tables.Count

    '~~> If number of tables is less than 2 then exit sub
    If tblCount < 2 Then Exit Sub

    '~~> Start with 2nd table and loop
    For i = 2 To tblCount
        '~~> Remove background
        With ActiveDocument.Tables(i).Shading
            .Texture = wdTextureNone
            .ForegroundPatternColor = wdColorAutomatic
            .BackgroundPatternColor = wdColorAutomatic
        End With
    Next
End Sub

这是您的文档在代码运行后的样子


0
投票

最后想出了一个宏来迭代细胞。出于某种原因,在我尝试这个循环之前,我无法让每个循环嵌套。所有阴影细胞都是相同的灰色阴影,所以我只是比较了每个细胞,只有当它是灰色的时才改变它。这不是最有效的方法,但由于这些文件相当小,所以工作正常。

Sub decolordocument()

Dim tbl As Table
Dim tblCount As Long
Dim cll As Word.Cell
Dim i As Long

tblCount = ActiveDocument.Tables.Count

For i = 2 To tblCount
    For Each cll In ActiveDocument.Tables(i).Range.Cells
        If cll.Shading.BackgroundPatternColor = RGB(217, 217, 217) Then
            cll.Shading.BackgroundPatternColor = wdColorWhite
        End If
    Next
Next
MsgBox "Color in shaded cells has been removed."

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