计数具有在活性单元格上方最多两个的列中的值,不包括标头



我正在尝试计算一个列中的所有单元格,该列中的所有电池都在主动单元格上方,排除了标头,并将其排除在活动单元格上方。

例如,如果我有列

1
5
4
N/A N/A
4
当前单元格

我希望当前单元格等于2。(计数5和4,而不是N/A N/A,而不是电流单元上方的单元格,而不是第一个单元格。)

列中的单元格数将有所不同。

我想要连续260列。

尝试以下:

Sub counter()
Dim col As Integer
Dim lastrow As Integer
Dim cellcount As Integer
With ActiveCell
    col = .Column
    lastrow = .Row - 2
End With
cellcount = 0
For Each cell In ActiveSheet.Range(Cells(2, col), Cells(lastrow, col))
    If IsError(cell) Then GoTo skipcell
    If cell.Value > 0 And IsNumeric(cell) Then cellcount = cellcount + 1
skipcell:
Next cell
ActiveCell = cellcount
End Sub

它采用活动单元格并找到所选的柱子,并在活动单元格上方找到两个单元格。

然后循环循环,每次发现一个高于" 0"

的范围会添加到计数器中

按照OP在检查中添加的注释中要求的,以确保单元格中的日期是数字的,并且在单元格中没有错误(#n/a)值

也要求这是在同一行中跨越260列。为此,使用for循环的使用:

Sub counter()
Dim firstCol as Integer
dim lastCol as Integer
firstCol = 1 'You can change this value depending on your first column
             ' for example you might use ActiveCell.Column
lastCol = firstCol + 260
Dim col As Integer
Dim lastrow As Integer
lastRow = 6  ' Make this the actual last row of the data to include
Dim cellcount As Integer
for col = firstCol to lastCol
    cellcount = 0
    For Each cell In ActiveSheet.Range(Cells(2, col), Cells(lastrow, col))
        If IsError(cell) Then GoTo skipcell
        If cell.Value > 0 And IsNumeric(cell) Then cellcount = cellcount + 1
    skipcell:
    Next cell
    ActiveSheet.Cells(lastRow + 2, col) = cellcount
Next col
End Sub

为什么必须是VBA代码?

在单元格公式中进行非常简单:

=COUNTIF(A1:A5,"<>0")-2

这计算给定范围内的所有单元格(A1:A5)中不等于零。由于您知道要删除标题行和上面的一行,因此从答案中减去2。当然,这与

相同
=COUNTIF(A2:A4,"<>0")

如果您想在VBA中使用它,请查看WorksheetFunction

Dim myCount As Integer
myCount = WorksheetFunction.COUNTIF(ActiveSheet.Range("A2:A4"),"<>0")

然后将myCount插入工作表

ActiveSheet.Range("A6").value = myCount

最新更新