Ale*_*Ale 14 excel vba excel-vba
我想在电子表格中为具有"#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
Run Code Online (Sandbox Code Playgroud)
但该行If cell.Value = "#N/A" Then
给出错误:类型不匹配.也许有人可以帮助理解错误在哪里?谢谢
Dmi*_*liv 11
非VBA解决方案:
使用带公式的条件格式规则:( =ISNA(A1)
突出显示包含所有错误的单元格- 不仅#N/A
使用=ISERROR(A1)
)
VBA解决方案:
你的代码循环通过50万个单元格.为了减少细胞数量,我使用.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
Run Code Online (Sandbox Code Playgroud)
注意,要突出显示任何错误的单元格(不仅仅是"#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
Run Code Online (Sandbox Code Playgroud)
同
If Not Data Is Nothing Then Data.Interior.ColorIndex = 3
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
211153 次 |
最近记录: |