我有一些代码贯穿我的工作表,并突出显示所有包含公式的单元格。这部分代码工作正常,但是,如果工作表中没有包含公式的单元格,则代码崩溃。我想要做的是,如果电子表格中没有公式,那么在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
答案 0 :(得分:2)
您可以在代码中使用错误处理。
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
答案 1 :(得分:0)
另一种方式
Sub t()
Dim ws As Worksheet
Dim rng As Range
Set ws = ActiveSheet
If ws.Cells.SpecialCells(xlCellTypeFormulas).Count > 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
End Sub
答案 2 :(得分:0)
Sub subCheckForFormla()
Dim ws As Worksheet
Dim cnt As Integer
Dim cel
On Error Resume Next
For Each ws In ThisWorkbook.Worksheets
If ws.Cells.SpecialCells(xlCellTypeFormulas).Count > 0 Then
If Not Err = 1004 Then
For Each cel In ws.Cells.SpecialCells(xlCellTypeFormulas).Cells
cel.Interior.ColorIndex = 36
Next cel
End If
End If
Next ws
End Sub
答案 3 :(得分:0)
这是一个旧线程,但如果将来有人需要它,检查工作表上是否有任何公式的最简单方法就是使用 HasFormula。
如果范围内的所有单元格都包含公式,则 HasFormula 为 True;如果区域中的单元格都不包含公式,则为 False;否则为 null。
您不能只检查 HasFormula = False 是否因为如果 HasFormula 为 null 则检查返回 null,因此您需要检查其他两种情况(null 或 True)才能使其工作。
Dim ws As Worksheet
Set ws = ActiveSheet
If IsNull(ws.UsedRange.HasFormula) Or ws.UsedRange.HasFormula Then
'Do stuff
End If