首页 > 解决方案 > 用于根据不同列中的值更改特定列中负数颜色的 Word 宏

问题描述

提前感谢您的任何回复。
我正在提交一些报告。定期报告从不同的软件导入 Word 模板。对于所有表格和每一行,只有在第 3 列中有特定文本时,我才想更改第 14 列中负数的颜色。不幸的是,我必须使用 Word 模板来执行此操作。似乎宏是我唯一的选择,所以我尝试从网上找到的不同宏中对科学怪人进行一些尝试:

Dim varColumn As Column
Dim clColumn As Column
Dim cCell As Variant

    Set clColumn = Selection.Columns(3)
    Set varColumn = Selection.Columns(14)

With clColumn
With .Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .text = "value"
        .Replacement.text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchWildcards = True
        .Execute
      End With
      Do While .Find.Found
        If .Information(wdWithInTable) = True Then
        Selection.MoveRight Unit:=wdCell, Count:=11
        End If
            If cCell < 0 Then
            Selection.Font.color = wdColorRed
        End If
    Loop
    End With
End Sub

标签: vbams-word

解决方案


我认为宏需要行来重复搜索。请参阅 Loop 之前添加的两行。

With Selection
    .HomeKey Unit:=wdStory 'Starts at the beginning, to search all tables.
    With .Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "value"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchWildcards = True
        .Execute
    End With
    Do While .Find.Found
        If .Information(wdWithInTable) = True And _
            .Cells(1).ColumnIndex = 3 Then 'Confirms it's in the 3rd column.
            .MoveRight Unit:=wdCell, Count:=11
        End If
        If .Range < 0 Then
            .Font.Color = wdColorRed
        End If
        .Collapse wdCollapseEnd 'Collapses the selection to no characters.
        .Find.Execute 'Searches again from the current selection point.
    Loop
End With

推荐阅读