VBA CountIf 语法失败?

huangapple go评论99阅读模式
英文:

VBA CountIf syntax failure?

问题

使用以下简单的VBA代码,我尝试显示范围内单元格值大于六的总数。我仍然无法弄清楚为什么CountIf函数无法按预期工作。

请帮助我修复在这里应用CountIf函数时的缺陷。

Sub countcells()                                                                            ' 

Dim rng As Range

Set rng = Range("A1:E2")

Range("G1") = CountIf(rng, "> 6")

End Sub

以下错误消息由Excel模块引发:
https://www.screencast.com/t/Ip8jyuUO11

谢谢

在阅读了“整个网络”之后,我觉得在这段代码中语法已经正确应用。显然情况并非如此。

英文:

With the below simple VBA code I attempt to display the total number of cells in a range where the cell value is greater than six. I still can't figure out why CountIf function won't work out as expected.

Please assist me how to repair the imperfection when applying CountIf function here.

Sub countcells()                                                                            ' 

Dim rng As Range

Set rng = Range("A1:E2")

Range("G1") = CountIf(rng, "> 6")

End Sub

The following error message is thrown by the Excel module:
https://www.screencast.com/t/Ip8jyuUO11

Thanks

After reading through the "entire web" it seems to me that the syntax is properly applied in this code. Obviously that is not the case.

答案1

得分: 0

你需要在代码中指定WorksheetFunction对象来访问CountIf。这将在子例程中计算结果。如果A1:E2中的值被修改,你将需要重新运行VBA代码。

如果你希望在工作表中使用COUNTIF并实现自动更新,也可以这样做。

Sub CountCells()
    
    Dim rng As Range

    Set rng = Range("A1:E2")

    Range("G1").Value = WorksheetFunction.CountIf(rng, "> 6")
    Range("G2").Formula = "=COUNTIF(" & rng.Address(False, False) & ",""> 6"")"

End Sub
英文:

You have to specify the WorksheetFunction object to access CountIf in code. This will calculate the result within the subroutine. If values in A1:E2 are modified you will have to re-run the VBA code.

If you want COUNTIF in the sheet so it updates automatically then you can do that as well.

Sub CountCells()                                                                            

    Dim rng As Range

    Set rng = Range("A1:E2")

    Range("G1").Value = WorksheetFunction.CountIf(rng, "> 6")
    Range("G2").Formula = "=COUNTIF(" & rng.Address(False, False) & ",""> 6"")"

End Sub

huangapple
  • 本文由 发表于 2023年3月7日 19:28:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定