我想在电子表格中为具有“#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
给出错误:类型不匹配。也许有人可以帮助理解错误在哪里?感谢
答案 0 :(得分:11)
非VBA解决方案:
使用公式为=ISNA(A1)
的条件格式规则(突出显示所有错误的 - 不仅#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
注意,突出显示有任何错误的单元格(不仅是"#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
答案 1 :(得分:3)
使用条件格式代替VBA来突出显示错误。
使用与您发布的VBA循环相似的VBA循环需要很长时间才能处理
语句If cell.Value = "#N/A" Then
永远不会奏效。如果您坚持使用VBA突出显示错误,请尝试此操作。
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 IsError(cell.Value) Then
cell.Interior.ColorIndex = 3
End If
Next
End Sub
为漫长的等待做好准备,因为程序循环通过5100万个单元
有更有效的方法来实现您想要做的事情。如果您改变主意,请更新您的问题。
答案 2 :(得分:2)
答案 3 :(得分:0)
您需要使用cell.Text =“#N / A”而不是cell.Value =“#N / A”。单元格中的错误实际上只是存储在单元格中的文本。