2

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

4 回答 4

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
于 2013-10-30T04:12:48.303 回答
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
于 2013-10-30T04:18:12.190 回答
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
于 2015-06-27T14:41:20.917 回答
0

这是一个旧线程,但如果将来有人需要它,检查工作表上是否有任何公式的最简单方法就是使用 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
于 2021-01-27T13:55:37.743 回答