我需要修改代码来计算列中可变数量的行

时间:2016-12-16 19:27:13

标签: excel-vba vba excel

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

1
5
4
N/A
4
current cell

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

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

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

我有以下代码from this answer但是列中的单元格数量是6而不是灵活的:

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

2 个答案:

答案 0 :(得分:0)

如果您只需要将lastRow动态更改为

lastRow = Cells(Rows.Count, "A").End(XlUp).Row

更改“A”,列将准确地为您提供最后一行。

答案 1 :(得分:0)

以下代码经过测试(至少基于我对您所寻找内容的理解)。

Sub counter()

Dim ws As Worksheet
Set ws = Worksheets("mySheet") 'change as needed

Dim firstCol As Integer, lastCol As Integer
firstCol = 1
lastCol = 1 + 260

Dim i As Integer

For icol = firstCol To lastCol

    With ws

        Dim lRow As Long
        lRow = .Cells(.Rows.Count, icol).End(xlUp).Row

        .Cells(lRow + 2, icol).Value = Application.WorksheetFunction.Count(.Range(.Cells(2, icol), .Cells(lRow - 2, icol)))

    End With

Next

End Sub