0
votes

I have written a VBA code for my excel file. In the VBA code, I have to delete cells having formula. My code is working fine if it found at least one cell having formula but if there is no such cell then it shows an error - run time error '1004'.

my code is

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

Please help me in finding the error.

2

2 Answers

1
votes

You can trap the no formula cells condition:

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

To address the possibility there are no Formula, and adding other opportunities for improvement

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