使用 vba 更改 countif 范围

Change countif range using vba

我想使用 vba 更改计算公式中的范围。通过单击一个按钮,范围 A3:A3 变为 A3:A4,然后再次单击该按钮 A3:A4 变为 A3:A5,依此类推...我设法创建了一个常量 vba-公式,但我不知道如何进行。有人吗? :)

Excel

VBA

我认为您需要一个虚拟 cell/value 来实现,虚拟单元格将“计算”您单击按钮的次数。我的解决方案将需要一个虚拟电池。

Sub Countif_function()
Dim start_value As Long

start_value = Cells(1, "D").Value 'Take the value from cell D1
If start_value <= 3 Or Cells(1, "D").Value = "" Then start_value = 3 ' If the value is less than 3 (since you start at row 3) or if the value is empty then set the minimum start value to 3 (otherwise countif will fail).

Cells(3, "D").Value = Application.WorksheetFunction.countif(Range(Cells(3, "A"), Cells(start_value, "A")), "A") 'Using the inbuild function in VBA to retrieve the countif
Cells(3, "E").Value = "=COUNTIF(A3:A" & start_value & ",""A"")" 'Just for view purpose of the final formula result, can be ignored in the code
Cells(1, "D").Value = Cells(1, "D").Value + 1 'Add +1 row. This will be used as the start value for next time the code is executed.

End Sub

我使用“A”作为标准,因为您在示例代码中使用了它,但可以更改为“C3”或其他一些单元格。

结果:

如果您不希望虚拟单元格按照之前的答案进行计数,另一种方法是通过 range.formula 将单元格中的公式读入字符串变量,用逗号分隔,阅读拆分数组中第一个条目的最后一位数字,递增 1。(如果数字是 9,则检查前面的字符是数字还是字母,如果是字母,则将 9 设为 10,如果是数字,则将其递增一个并使 9 成为 0,如果前面的字符也是 9,递归调用)。所以,是的,除非你真的没有虚拟电池,否则使用那个解决方案,它更容易。