简体   繁体   中英

VBA count consecutive non-empty cells in a column, starting from a given one: must handle special cases

I'm having difficulties with a seemingly trivial task. I'm writing a function which, starting from a cell, counts all consecutive non-empty cells ( including the first one), or stops before in case an optional Ncells number of cells has been reached. That's what I cooked up:

Function CountCells(Row As Long, Column As Long, Optional Ncells As Variant, _
Optional sht As Worksheet) As Long
Dim I As Long
Dim xlsht As Worksheet
'
'           set target worksheet
'
If sht Is Nothing Then
   Set xlsht = ActiveSheet
Else
   Set xlsht = sht
End If
If IsMissing(Ncells) Then
   Ncells = xlsht.Rows.Count
End If

With xlsht
   I = .Cells(Row, Column).End(xlDown).Row
   If I > Ncells Then I = Ncells
End With

CountCells = I - Row + 1

End Function

It looked nice to me, but it does fail spectacularly if the first cell below the starting cell xlsht.Cells(Row, Column) is empty. I'd like CountCells to return 1 in this case, but instead it returns the number of consecutive empty cells down to the first non-empty one, or the end of the column. The same result is obtained if the starting cell is empty; in this case, I would say that the user is using the function the wrong way, but let's say that the return value must be 0. Can you help me? Thanks,

best

deltaquattro

EDIT a user requested an example. Since it looks like spreadsheets can't be attached to posts, I'm giving a link to Google Drive https://docs.google.com/file/d/0BxB-VPeuApOkeThFZUJ3X2hyTGs/edit?usp=sharing

.End(xlDown) has same behavior as pressing Ctrl + Down arrow .

When you are in last cell in a non-empty area, cursor will jump to first cell of following non-empty area.

You must handle this case:

If row > Ncells Then
   If xlsht.Cells(Row+1, Column).Value = Empty Then
       CountCells = 1
       Exit Function
   End If

End If

Note that name Ncells induce in error, it is really a MaxRow .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM