![](/img/trans.png)
[英]How to clear all check boxes in a worksheet and update formulas connected to them
[英]Check if there are any formulas in worksheet
我有一些代码贯穿我的工作表并突出显示所有带有公式的单元格。 这部分代码工作正常,但是,如果工作表中没有带有公式的单元格,则代码会崩溃。 我想要做的是,如果电子表格中没有公式,则在其中放置一个 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
另一种方式
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
这是一个旧线程,但如果将来有人需要它,检查工作表上是否有任何公式的最简单方法就是使用 HasFormula。
如果范围内的所有单元格都包含公式,则 HasFormula 为 True; 如果范围内的单元格都不包含公式,则为 False; 否则为空。
您不能只检查 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.