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