VBA | 统计数组某元素出现的次数,适用于一维、二维数组


很简单的需求,但是中文网络上基本都是循环的方法,经过查找下面的方法很有效。为了方便用户的使用,进行了如下的整改。

 

1 Sub Statistics_Number_of_occurrences_test()
2 MyArray = Array("1", 23, 3, "1")
3 MsgBox Application.count(Application.Match(MyArray, Array("1"), 0)) '统计字符串"1"的出现次数,返回2
4 End Sub

 

为了便于使用,写成函数,用户可以调用该函数 Statistics_Number_of_occurrences(s, arr) 直接使用。

 

1 Function Statistics_Number_of_occurrences(s As Variant, arr As Variant) As Integer
2     '------------适用于一维数组、二维数组----------
3     '------------博客园:IssacNew------------------
4     '----https://www.cnblogs.com/issacnew/---------
5     Statistics_Number_of_occurrences = Application.count(Application.Match(arr, Array(s), 0))
6 End Function

 

1 '------使用例子-----
2 Sub test()
3     Dim s, arr1, arr2
4     s = 1
5     arr1 = Array(1, 2, 3, 3, 2, 1) '一维数组
6     arr2 = Array(Array(1, 2, 3, 1, 2, 1), Array(1, 2, 3, 3, 2, 1))
7     MsgBox Statistics_Number_of_occurrences(s, arr1) '一维数组,统计1出现的个数,返回3
8     MsgBox Statistics_Number_of_occurrences(s, arr2) '二维数组,统计1出现的个数,返回5
9 End Sub

 

参考资料:

01. https://www.mrexcel.com/board/threads/countif-for-vba-array-without-a-loop.739653/#post3635486

02. https://stackoverflow.com/questions/45367671/vba-array-countif


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM