很簡單的需求,但是中文網絡上基本都是循環的方法,經過查找下面的方法很有效。為了方便用戶的使用,進行了如下的整改。
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