我有一些代码贯穿我的工作表,并突出显示其中包含公式的所有单元格。这部分代码工作正常,但是,如果工作表中没有包含公式的单元格,则代码会崩溃。我想要做的是在其中添加一个 if 语句,如果电子表格中没有公式,该语句将结束代码。我尝试遍历单元格并检查每个单元格是否都有公式,但这也会崩溃。所以我想做的是修复 if 语句。
任何帮助将不胜感激。
突出显示代码
'Apply yellow highlight to all formula cells.
Dim ws As Worksheet
Dim rng As Range
Set ws = ActiveSheet
For Each rng In ws.Cells.SpecialCells(xlCellTypeFormulas)
rng.Interior.ColorIndex = 36
Next rng
带有 if 语句的代码
'Apply yellow highlight to all formula cells.
Dim ws As Worksheet
Dim rng As Range
Set ws = ActiveSheet
c = 0
For Each cell in ws.Cells
If cell.HasFormula = True Then
c= c + 1
End If
Next cell
If c > 0 Then
For Each rng In ws.Cells.SpecialCells(xlCellTypeFormulas)
rng.Interior.ColorIndex = 36
Next rng
Else MsgBox ("No formulas in this worksheet")
End If
最佳答案
您可以在代码中使用错误处理。
On Error Resume Next
即使发生错误,也会继续执行下一行,而不会中断脚本。
On Error Goto 0
禁用当前过程中启用的错误处理程序并将其重置为 Nothing。
Sub test()
Dim ws As Worksheet
Dim rng As Range, cell As Range
Set ws = ActiveSheet
On Error Resume Next
Set rng = ws.Cells.SpecialCells(xlCellTypeFormulas)
On Error GoTo 0
If rng Is Nothing Then
MsgBox "No cells found"
Exit Sub
End If
For Each cell In rng
cell.Interior.ColorIndex = 36
Next
End Sub
关于vba - 检查工作表中是否有公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19673635/