0

我有一个宏来为其中包含单词 VOID 的单元格着色。

我在这样的单元格中也有 VOID 这个词:[$189.00VOID]。

我找不到为所有包含以下内容的单元格着色的方法:

无效和 [$189.00无效]

或其中的任何其他美元金额。

Sub Macro1()
On Error Resume Next
Dim current As String

For i = 1 To 65536 ' go from first cell to last

    current = "c" & i ' cell counter

    Range(current).Select ' visit the current cell

    If Range(current).Text = "VOID" Then ' if it says VOID then we...
        With Selection.Interior
            .ColorIndex = 3 ' ...go red
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
        End With
    End If

    If Range(current).Text = "FORWARDED" Then ' if it says FORWARDED then we...
        With Selection.Interior
            .ColorIndex = 4 ' ...go green
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
        End With
    End If
Next i ' loop and check the next cell
End Sub
4

2 回答 2

1

VBA 似乎真的有点矫枉过正。正如 pnuts 所说,条件格式将满足您的所有需求。

选择要格式化的单元格,然后选择主页功能区 -> 条件格式 -> 新规则 -> 仅格式化包含的单元格

然后将第一个组合框从单元格值更改为特定文本。并在右侧的空白文本框中键入 VOID。

然后,您可以将单元格格式调整为您想要的任何格式。

于 2013-09-04T19:37:11.737 回答
1

对于这样的事情,我真的建议使用条件格式(如前所述)。以下是您需要应用于 C 列的两个条件格式公式:

=COUNTIF($C1,"*VOID*")>0
=COUNTIF($C1,"*FORWARDED*")>0

但是,如果它绝对必须是 VBA,则右键单击要监视的工作表选项卡并选择“查看代码”。在那里,粘贴以下内容:

Private Sub Worksheet_Calculate()

    Dim rngColor As Range
    Dim rngFound As Range
    Dim strFirst As String
    Dim varFind As Variant

    'Remove current formatting (if any)
    Columns("C").Interior.Color = xlNone

    'Check for both VOID and FORWARDED
    For Each varFind In Array("VOID", "FORWARDED")

        'Attempt to find a cell that contains varFind
        Set rngFound = Columns("C").Find(varFind, Me.Cells(Me.Rows.Count, "C"), xlValues, xlPart)

        'Check if any cells were found
        If Not rngFound Is Nothing Then

            'The first cell was found, record its address and start rngColor
            strFirst = rngFound.Address
            Set rngColor = rngFound

            'Begin loop
            Do

                'Add found cell to rngColor
                Set rngColor = Union(rngColor, rngFound)

                'Advance loop by finding the next cell
                Set rngFound = Columns("C").Find(varFind, rngFound, xlValues, xlPart)

            'Exit loop when back to first cell
            Loop While rngFound.Address <> strFirst

            'Fill rngColor based on varFind
            Select Case varFind
                Case "VOID":        rngColor.Interior.Color = vbRed
                Case "FORWARDED":   rngColor.Interior.Color = vbGreen
            End Select

        End If
    Next varFind

End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    Worksheet_Calculate
End Sub
于 2013-09-04T19:58:03.620 回答