问题描述
我正在尝试制作一个循环遍历一个工作表上的 31 列的子程序,以查找每列中存在的 0 的数量。每列可以有不同数量的数据,每列最多 25,000 个单元格。我需要计算 0 的数量并将其粘贴到每列的第 47 行。我需要计算的数据从第 49 行开始,可以达到 25,049。我的思考过程是计算包含数据的行数,而不是让 VBA 查看可能的空白单元格以节省性能。当我运行下面的代码时,它在每一行中的计数从未超过 1 个零。他们中的大多数人说,当有 9 个时,就没有零的情况。我不确定我哪里出错了。
Sub FindingZeros()
'________________________________________
'TO DO:
'Filter data in this workbook for 0's and
'count instances
'________________________________________
Dim zeros As Integer
Dim currcol As Integer
Dim temp As Worksheet
Set temp = Worksheets("306 Toyota 2.5L")
For currcol = 2 To 32
Dim lastrow1 As Long
lastrow1 = temp.Range(Cells(49,currcol),Cells(temp.Rows.Count,currcol)).End(xlUp).Row
zeros = Application.WorksheetFunction.CountIf(Range(Cells(49,Cells(lastrow1,currcol)),0)
temp.Cells(47,currcol).Value = zeros
Next currcol
End Sub
解决方法
您遇到的主要问题是识别列的最后使用的行,在这种情况下,我们不需要知道范围,而只需要知道最后一行,因此 lastrow1 只需要最后一行号。
然后我们不需要为零设置变量,因为该值可以直接放入单元格中。
参考评论:
Sub FindingZeros()
Dim currcol As Integer
Dim temp As Worksheet
Dim lastrow1 As Long
Set temp = Worksheets("306 Toyota 2.5L")
For currcol = 2 To 32
' find last used row of column
lastrow1 = Cells(temp.Rows.Count,currcol).End(xlUp).Row
' set the value of the cell to the counted zeroes.
Cells(47,currcol).Value = Application.WorksheetFunction.CountIf(Range(Cells(49,currcol),Cells(lastrow1,currcol)),0)
Next currcol
End Sub