【发布时间】:2020-02-15 17:31:11
【问题描述】:
帮助!在这里的 Excel VBA 相当新,我现在正在参加一些付费课程以变得更好,但我遇到了障碍,谷歌搜索并没有让我得到我正在寻找的结果。
我有一个不断增长的跟踪电子表格,它在列中显示有关我们已处理(我们称之为“构建”)的数据,然后显示我们已检查(我们称之为已审核)该数据的数据我们已经在其他专栏中进行了处理。我想查找已处理的年份,并查找是否已审核,无论审核年份如何,如果是,则将其加起来。我想每年都这样做,所以 2017 年、2018 年、2019 年、2020 年等等。
然后最后将每年的调查结果放在仪表板单元格中。
例如搜索包含我们处理 2017 年数据的日期的列 J,然后查看同一行中的已审计列(也包含日期),如果其中有任何内容并计数 1。然后一次又一次地执行,直到整个范围已被检查。每次我们找到 2017 年的日期时,我们都会添加一个,并且每年都会这样做。在搜索结束时,需要在仪表板表中输入每年的结果。
有没有办法编写代码让它每年检查一次,而不必每年专门调用?
这是我到目前为止所得到的,但我一直遇到错误。要么是“next without for”,要么是我现在不记得了。我已经用谷歌搜索并添加了各种东西并移动它等等。我确定我在这里做的事情确实明显错误,但我只是没有看到它。请在这里帮助新手。
Sub CountAudits()
Dim CellBuild As Range
Dim CellAudit As Range
Dim CellDateCount2017 As Long
For Each CellBuild In Sheet1.Range("J:J500") 'column J contains a date MMYYDD what we call "build" data in other words we processed it.
If CellBuild.Value = "2017" Then 'this checks if the date it was processed was in 2017
For Each CellAudit In Sheet1.Range("Q:Q500") 'this is the column containing the date it was audited. It will be blank if it was not audited.
If CellAudit.Value <> "" Then 'this checks if it's been audited. I don't care about the date just as long a there is something in the cell
CellDateCount2017 = CellDateCount2017 + 1 'if the processed date was 2017 and it was audited it adds a count of 1 to here.
Exit For
Sheet2.Range("V18").Value = CellDateCount2017 'Sheet2 is the sheet code name to the dashboard
Next ' I keep getting an "Next without for" error for this here. I've added all sorts of ends, end ifs, etc. but I can't figure it out.
End If
End Sub
我找到了 SUMPRODUCT,我想我可以用它来计算 2017 年出现在我的列中的次数,但是我如何将它添加到仪表板中?例如SUMPRODUCT(1*(YEAR(J1:J500)=2017))
如果只是弄清楚这些东西不是那么有趣,我可以离开它!我一直被“这个 excel VBA 的东西很有趣”的错误所困扰。
【问题讨论】:
-
添加另一个每年都会执行的外部循环。但我会考虑过滤然后计算返回的数量。
-
为什么不直接使用
WorksheetFunction.CountIfs?并且 - 将End If移动到Next之前。好吧,你错过了几个End Ifs,还有一个Next。 -
另一个有用的工具:indenter :) 它将阐明其中的一些问题。
标签: excel vba date if-statement count