vba - 如何在VBA中给单元格填充颜色?

标签 vba excel

我想为当前工作表中具有“#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

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

最佳答案

非 VBA 解决方案:

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

enter image description here

VBA 解决方案:

您的代码循环遍历 50 mn 个单元格。为了减少单元格数量,我使用 .SpecialCells(xlCellTypeFormulas, 16).SpecialCells(xlCellTypeConstants, 16) 仅返回有错误的单元格(注意,我使用的是如果 cell.Text = "#N/A"则)

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

注意,要突出显示没有任何错误的单元格(不仅仅是“#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

If Not Data Is Nothing Then Data.Interior.ColorIndex = 3

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

关于vba - 如何在VBA中给单元格填充颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22193415/

相关文章:

excel - 将任何长度的有符号十六进制数转换为有符号十进制数 (Excel)

java - 如何在java中使用poi从excel中的第一行到最后一行读取?

excel - 如何在 Excel 2007 的 VBA 中关闭自动更正?

vba - 根据模板和数据工作表生成多张发票

excel - 如何阅读声明数组大小?

VBA Excel 如何插入预定行的标题

excel - 计算两列连接的唯一组合

Excel 格式

vba - 从给定的日期/时间减去指定的小时数以获得新的日期/时间

vba - 复制工作表的数据源