如何在VBA中的单元格中填充颜色?
我想在电stream表中给单元格加上“#N / A”值。 为了做到这一点,我使用下面的macros:
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
给出一个错误:types不匹配。 也许有人可以帮助理解错误在哪里? 谢谢
非VBA解决scheme:
使用CF规则,公式如下: =ISNA(A1)
(对所有错误的单元格 – 不仅=ISERROR(A1)
#N/A
,use =ISERROR(A1)
)
VBA解决scheme:
你的代码循环通过50万个单元格。 为了减less单元格的数量,我使用.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"
#N "#N/A"
),请replace以下代码
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循环将花费很长时间来处理
-
声明
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万个单元
-
有更有效的方法来实现你想要做的事情。 更新你的问题,如果你有改变主意。
- 按左上angularselect所有单元格
- select[首页] >> [条件格式] >> [新规则]
- select[仅格式化包含的单元格]
- 在[仅格式化单元格]中,select“错误”
- 在[格式..]button中select适当的格式
您需要使用cell.Text =“#N / A”而不是cell.Value =“#N / A”。 单元格中的错误实际上只是存储在单元格中的文本。