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