检查工作表中是否有任何公式

我有一些代码运行在我的工作表中,并突出显示所有带有公式的单元格。 代码的这部分工作正常,但是,如果在工作表中没有公式的单元格,则代码将崩溃。 我想要做的是,如果在电子表格中没有公式,则放置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 

您可以在代码中使用error handling。

On Error Resume Next即使发生错误,下一行仍将继续执行而不中断脚本。
On Error Goto 0禁用当前过程中启用的error handling程序,并将其重置为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 

其他方式

 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 
 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