vba - 检查工作表中是否有公式

标签 vba excel

我有一些代码贯穿我的工作表,并突出显示其中包含公式的所有单元格。这部分代码工作正常,但是,如果工作表中没有包含公式的单元格,则代码会崩溃。我想要做的是在其中添加一个 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/

相关文章:

vba - Excel VBA 脚本中的对象定义错误

excel - 如何在 Excel 中将 12 小时格式的时间转换为 24 小时格式

excel - 用户窗体关闭时如何自动保存工作簿?来自红色 "X"

vba - 用于编辑页眉和页脚的 WORD 2010 宏

vba - 使用变量时,在 Excel 中通过 VBA 设置验证失败

xml - 是否可以在 Excel VBA 中跳过 XML 文件中的节点?

php excel库

vba - 打开/关闭标志以更改名称

vba - 有没有办法在Excel中隐藏宏?

excel - 从 0 开始 for 循环(而不是 1)