确定活动范围而不是预定义范围

时间:2015-12-07 10:13:25

标签: excel vba excel-vba

我正在尝试查找并返回Excel中活动范围内出现“溢出”一词的次数。如何在有效的选定范围内搜索,而不是像A1那样的预定义范围:A50

Dim MyCount As Long
MyCount = Application.Countif(Range("A1:A50"),"Oveflow")
MsgBox "I have completed my search and found  " & MyCount & " cell(s)."

是否可以在有效的选定范围内执行countif?

2 个答案:

答案 0 :(得分:2)

Selection属性是当前选择中的单元格或单元格范围。

MyCount = Application.Countif(Selection,"Oveflow")

这将从当前选定的包含 Oveflow [sic] 的单元格返回计数。

使用Application.Selection属性(非选择)的更多示例可以在How to avoid using Select in Excel VBA macros 中找到。

答案 1 :(得分:2)

您只需在VBA中使用Selection来引用您实际选择的范围:

Dim MyCount As Long
MyCount = Application.Countif(Selection,"Oveflow")
MsgBox "I have completed my search and found  " & MyCount & " cell(s)."