非VBA colution:
使用CF規則與公式:=ISNA(A1)
(以higlight細胞所有錯誤 - 不僅#N/A
,使用=ISERROR(A1)
)
VBA解決方案:
您的代碼通過50 mln個單元循環。爲了減少細胞數量,我用.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
注意,突出細胞WITN任何錯誤(不僅"#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
爲什麼不只是使用條件格式來突出顯示帶有錯誤的單元?)如果你不喜歡它,使用'If cell.Text =「#N/A」Then'。還有一點,嘗試使用'Set Data = Intersect(currentsheet.UsedRange,currentheet.Range(「A2:AW1048576」))'來最小化循環中的單元數。現在你循環* 50毫升*細胞:) –
你也可以使用'IsError(Cell.Value)' – Kapol
來代替** value ** use **。text ** –