无需使用VBA的解决方案:
使用条件格式公式:=ISNA(A1)
(用于突出显示所有错误单元格-不仅限于#N/A
,使用=ISERROR(A1)
以突出显示所有错误)
使用VBA的解决方案:
您的代码循环遍历5000万个单元格。为了减少单元格数量,我使用.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
注意,要突出显示任何错误的单元格(不仅限于"#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
更新:(如何通过 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
If cell.Text ="#N/A" Then
。还有一个提示,尝试使用Set Data = Intersect(currentsheet.UsedRange,currentsheet.Range("A2:AW1048576"))
来最小化循环中的单元格数量。现在您正在遍历5000万个单元格 :) - Dmitry PavlivIsError(Cell.Value)
。 - Kapol