excel - 如何使用 for 循环来计算 Excel VBA 工作表上每列中零的数量?
问题描述
我正在尝试制作一个循环遍历一个工作表上的 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
解决方案
您遇到的主要问题是识别列的最后使用的行,在这种情况下,我们不需要知道范围而只需要知道最后一行,因此 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
推荐阅读
- python - 用于创建和写入 csv 任意数量的 DataFrame 的矢量化方法
- php - PHPUnit 测试用例随机失败,索引未定义,尝试获取非对象的属性
- ibm-cloud - 设置 ibm-cloud 组织
- database - VB.NET OleDb Connection.Close()/.Dispose() 执行时间过长
- powershell - 在单独的 Excel 工作表上输出 Powershell 域搜索
- ios - 攻击者能否在 iPhone 上安装名称与合法应用相似的应用
- azure-devops - 来自不同存储库的 Helm Chart
- c# - 如何解析 AWS S3 路径 (s3://
/ ) 在 C# 中使用 AWSSDK.S3 以获取存储桶名称和密钥 - jquery - jQuery中的执行顺序
- c# - 如何在 c# ASP.NET 中传递这个值?