如何在VBA中填充单元格中的颜色?

Ale*_*Ale 14 excel vba excel-vba

我想在电子表格中为具有"#N/A"值的单元格着色.为了做到这一点,我使用以下宏:

Sub ColorCells()

Dim Data As Range
Dim cell As Range
Set currentsheet = ActiveWorkbook.Sheets("Comparison")
Set Data = currentsheet.Range("A2:AW1048576")

For Each cell In Data
If cell.Value = "#N/A" Then
   cell.Interior.ColorIndex = 3
End If
Next

End Sub
Run Code Online (Sandbox Code Playgroud)

但该行If cell.Value = "#N/A" Then给出错误:类型不匹配.也许有人可以帮助理解错误在哪里?谢谢

Dmi*_*liv 11

非VBA解决方案:

使用带公式的条件格式规则:( =ISNA(A1)突出显示包含所有错误的单元格- 不仅#N/A使用=ISERROR(A1))

在此输入图像描述

VBA解决方案:

你的代码循环通过50万个单元格.为了减少细胞数量,我使用.SpecialCells(xlCellTypeFormulas, 16).SpecialCells(xlCellTypeConstants, 16)仅返回有错误的细胞(注意,我正在使用If cell.Text = "#N/A" Then)

Sub ColorCells()
    Dim Data As Range, Data2 As Range, cell As Range
    Dim currentsheet As Worksheet

    Set currentsheet = ActiveWorkbook.Sheets("Comparison")

    With currentsheet.Range("A2:AW" & Rows.Count)
        .Interior.Color = xlNone
        On Error Resume Next
        'select only cells with errors
        Set Data = .SpecialCells(xlCellTypeFormulas, 16)
        Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
        On Error GoTo 0
    End With

    If Not Data2 Is Nothing Then
        If Not Data Is Nothing Then
            Set Data = Union(Data, Data2)
        Else
            Set Data = Data2
        End If
    End If

    If Not Data Is Nothing Then
        For Each cell In Data
            If cell.Text = "#N/A" Then
               cell.Interior.ColorIndex = 4
            End If
        Next
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

注意,要突出显示任何错误的单元格(不仅仅是"#N/A"),请替换以下代码

If Not Data Is Nothing Then
   For Each cell In Data
       If cell.Text = "#N/A" Then
          cell.Interior.ColorIndex = 3
       End If
   Next
End If
Run Code Online (Sandbox Code Playgroud)

If Not Data Is Nothing Then Data.Interior.ColorIndex = 3
Run Code Online (Sandbox Code Playgroud)

UPD :(如何通过VBA添加CF规则)

Sub test()
    With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
        .Delete
        .Add Type:=xlExpression, Formula1:="=ISNA(A1)"
        .Item(1).Interior.ColorIndex = 3
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!它工作正常,两种方法!VBA的唯一问题是,如果我需要运行宏,另一个输入和N/A单元格的位置发生变化,这个宏不会重写颜色.例如,如果A2细胞被着色,即使从第二次尝试再也没有N/A值,它仍保持着色. (2认同)