VBA - CountA formula with Unknown Rows

Plokimu77

Board Regular
Joined
Oct 1, 2014
Messages
138
Good Afternoon,

How do I tweak this line of code, to count the number of non-blanks in a column, with an unknown number of rows in a range?

ActiveCell.FormulaR1C1 = "=COUNTA(R[-3]C:R[-1]C)"

I tried to record the macro and used the Relative References, however it did not work.

The amount of rows with items varies.

Here is an example of a result with "3" in Cell B4 and "4" in Cell B9.

Thank you


AB
1Apple4
2Banana15
3Orange5
43
5Johnny10
6Mike25
7Melanie3
8Philip2
94
 

Excel Facts

Excel Wisdom
Using a mouse in Excel is the work equivalent of wearing a lanyard when you first get to college
How about this?
VBA Code:
Sub CountAwithUknownRows()

Dim lastRow As Long
Dim cell As Range
Dim rng As Range

    lastRow = Cells(Rows.count, 1).End(xlUp).Row
    Set rng = Range("A1:A" & lastRow)
    For Each cell In rng
        If Not IsEmpty(cell) Then
            count = count + 1
        End If
 
    Next cell
    Cells(lastRow+1, 2).Value = count
 
End Sub
 
Upvote 0
Almost, it's overwriting the result on the last entry.

Can we have it give the result in the empty cell?

Thank you
 
Upvote 0
Try this.

VBA Code:
Sub CountAwithUknownRows2()
    Dim lastRow As Long
    Dim cell As Range
    Dim rng As Range
    Dim count As Long

    count = 0
    lastRow = Cells(Rows.count, 1).End(xlUp).Row
    Set rng = Range("A1:A" & lastRow)

    For Each cell In rng
        If Not IsEmpty(cell) Then
            count = count + 1
        Else
            cell.Offset(0, 1).Value = count
            count = 0
        End If
    Next cell

    If count > 0 Then
        rng.Cells(rng.Cells.count).Offset(1, 1).Value = count
    End If
End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,223,908
Messages
6,175,306
Members
452,633
Latest member
DougMo

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top