【问题标题】:run time error 1004 while counting cell with formula使用公式计算单元格时出现运行时错误 1004
【发布时间】:2020-11-22 15:25:37
【问题描述】:

我为我的 excel 文件编写了 VBA 代码。在 VBA 代码中,我必须删除具有公式的单元格。如果我的代码找到至少一个具有公式的单元格,但如果没有这样的单元格,则它会显示错误 - 运行时错误“1004”。

我的代码是

Dim n As Integer
n = Sheets("Pay_Slip").Range("B11:AO510").SpecialCells(xlCellTypeFormulas, 23).Count

If n > 0 Then
    Sheets("Pay_Slip").Range("B11:AO510").Select
    Selection.SpecialCells(xlCellTypeFormulas, 23).Select
    Selection.ClearContents
End If

请帮我找出错误。

【问题讨论】:

    标签: excel vba excel-2016


    【解决方案1】:

    您可以捕获无公式单元格条件:

    Sub qwerty()
        Dim n As Long
        On Error Resume Next
            n = Sheets("Pay_Slip").Range("B11:AO510").SpecialCells(xlCellTypeFormulas, 23).Count
            If Err.Number > 0 Then
                MsgBox "no formula cells"
                Exit Sub
            End If
        On Error GoTo 0
        
        If n > 0 Then
            Sheets("Pay_Slip").Range("B11:AO510").Select
            Selection.SpecialCells(xlCellTypeFormulas, 23).Select
            Selection.ClearContents
        End If
    End Sub
    

    【讨论】:

      【解决方案2】:

      为了解决没有公式的可能性,并添加其他改进机会

      Sub Demo()
          Dim rFormula as Range
      
          On Error Resume Next
              Set rFormula = Workheets("Pay_Slip").Range("B11:AO510").SpecialCells(xlCellTypeFormulas, 23)
          On Error GoTo 0
          
          If Not rFormula Is Nothing Then
              rFormula.ClearContents
          End If
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-06
        相关资源
        最近更新 更多