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