如何使用for循环计算ExcelVBA工作表中每一列零的个数?

How to use a for loop to count the number of zeros in each column on a worksheet in Excel VBA?

我正在尝试制作一个循环遍历一张工作表上的 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, 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