如何在Excel VBA中使用for循环计算工作表中每列的零数



我正在尝试创建一个子表,循环遍历一个工作表上的31列,以查找每列中存在的0的数量。每列可以有不同数量的数据,每列最多25000个单元格。我需要把0的计数粘贴到每列的第47行。我需要计数的数据从第49行开始,可以到达25049。我的想法是计算包含数据的行数,而不是让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, currcol), 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

相关内容

最新更新