计算除标题之外的活动单元格上方的列中的所有单元格

时间:2016-12-15 02:24:16

标签: excel-vba count cells vba excel

我试图找到一些excel vba代码,该代码计算列中除了标题之外的活动单元格以上的值并排除活动单元格正上方的单元格的所有单元格。例如,如果我有一个列

  

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

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

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

我希望连续260个列发生这种情况。

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

为什么这必须是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