【发布时间】:2021-08-25 21:58:34
【问题描述】:
我想使用 vba 更改 counfif 公式中的范围。通过单击按钮范围 A3:A3 更改为 A3:A4,然后再次单击按钮 A3:A4 更改为 A3:A5,依此类推...我设法创建了一个常量 vba 公式,但我不知道如何进行。有人吗? :)
【问题讨论】:
我想使用 vba 更改 counfif 公式中的范围。通过单击按钮范围 A3:A3 更改为 A3:A4,然后再次单击按钮 A3:A4 更改为 A3:A5,依此类推...我设法创建了一个常量 vba 公式,但我不知道如何进行。有人吗? :)
【问题讨论】:
我认为您需要一个虚拟单元格/值来实现,虚拟单元格将“计算”您单击按钮的次数。我的解决方案需要一个虚拟单元。
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,递归调用)。所以,是的,除非你真的不能拥有虚拟单元,否则使用那个解决方案会更容易。
【讨论】: