Home » excel » excel – Avoid "Error 1004: no cells were found" when counting a blank column

excel – Avoid "Error 1004: no cells were found" when counting a blank column

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am building a macro which includes an intermediate step for counting the results of a search.

If the search does not come up with results, the column stays blank and that causes the count to give a 1004-error.

My code looks like this:

Sub Test()
Dim z As Integer
z=Worksheets("Pumps").Range("N:N").Cells.SpecialCells(xlCellTypeConstants).Count
Range("O1").Value = z
End Sub

Does anybody have an idea how to control this ?

Thank you in advance.

How to&Answers:

Use error handling with SpecialCells.

Plus I have removed the unnecessary use of a count.

Dim rng1 As Range
On Error Resume Next
Set rng1 = Worksheets("Pumps").Range("N:N").Cells.SpecialCells(xlCellTypeConstants)
On Error GoTo 0
If Not rng1 Is Nothing Then Range("O1").Value = rng1.Cells.Count

Answer:

You could solve it like this

Sub Test()

Dim z As Integer

If Application.WorksheetFunction.Count(Range("N:N")) >= "1" Then
    z = Worksheets("Pumps").Range("N:N").Cells.SpecialCells(xlCellTypeConstants).Count
    Range("O1").Value = z
End If

End Sub

Answer:

The range returned by SpecialCells() can be empty, so test it beforehand:

Sub Test()
    Dim results As Range

    Set results = Worksheets("Pumps").Range("N:N").Cells.SpecialCells(xlCellTypeConstants)
    If results Is Nothing Then
        Range("O1") = 0
    Else
        Range("O1") = results.Count
    End If
End Sub

BTW, maybe you should qualify Range("O1") to get the return value onto the sheet you intend, like in Worksheets("Pumps").Range("O1").