【问题标题】:How to use a for loop to count the number of zeros in each column on a worksheet in Excel VBA?如何使用 for 循环计算 Excel VBA 工作表上每列中零的数量?
【发布时间】:2021-07-16 14:47:00
【问题描述】:

我正在尝试制作一个循环遍历一个工作表上的 31 列的 sub,以查找每列中存在的 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

【问题讨论】:

  • 您的 lastrow 是否返回了正确的最后一行?试试lastrow1 = temp.Cells(Rows.Count, currcol).End(xlUp).Row
  • 为什么不在整个列上使用 COUNTIF 并跳过查找最后一行?
  • 在我的代码中 lastrow1 最终返回 10 而不是 6,700 之类的东西。当我将其更改为您的线路时,它最终起作用了!非常感谢。
  • 我不能在整个事情上使用 CountIf 因为第 1 到 46 行有一堆公式可以包含一个 0 用于根据每列数据生成直方图不应该包含在第 48 行下方的原始数据所需的零计数中。所以我无法计算整个列。
  • 您仍然可以跳过查找最后一行,直接使用 Rows.Count... 从第 49 行开始一直计数到工作表底部。

标签: excel vba excel-2016


【解决方案1】:

您遇到的主要问题是识别列的最后使用的行,在这种情况下,我们不需要知道范围而只需要知道最后一行,因此 lastrow1 只需要最后一个行号。

那么我们不需要为零设置一个变量,因为值可以直接放入单元格中。

参考cmets:

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

【讨论】:

    猜你喜欢
    • 2014-03-22
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    相关资源
    最近更新 更多