excel - 获取元素在数组中出现的次数
问题描述
如何计算元素在数组中出现的次数?
例如水果(香蕉、橙子、苹果、橙子、苹果、橙子)
我想要:香蕉(1) 橙子(3) 苹果(2)
我试过这个:
Private Function IsInArray(findMe As Variant, arr As Variant) As Long
Dim element As Variant
Dim count As Integer
count = 0
For Each element In arr
If element = valToBeFound Then
count = count + 1
IsInArray = Replace(element & "(" & count & ")", " ", "")
Exit Function
End If
Next element
End Function
解决方案
尝试这个
Sub test()
fruitArr = Array("banana", "orange", "apple", "orange", "apple", "orange")
Set dict = CreateObject("Scripting.Dictionary")
For Each Fruit In fruitArr
sKey = Fruit
If Not dict.Exists(sKey) Then
dict.Add sKey, 1
Else
dict(sKey) = dict(sKey) + 1
End If
Next Fruit
For Each key In dict.Keys
Debug.Print key, dict(key)
Next key
End Sub
推荐阅读
- node.js - NodeJS + Express Cors + SocketIO = XMLHttpRequest 错误
- arrays - 将 Match 和 Index 函数与在 VBA 中创建和填充的数组一起使用
- python - 将 CSV 的多行合并为一个
- android - 使单个 MediaPlayer 在 android studio 中播放多个声音的代码
- uml - 简化活动图
- drupal-8 - 视图中的自定义表单字段
- javascript - Bootstrap 4 弹出框 - 人员输入字段(弹出框未显示)
- vue.js - 我在 Vue.js 中的组件模板不起作用?
- amazon-web-services - 如何创建 IAM 策略以授予特定区域的完全管理员访问权限?
- sql - PostgreSQL如何通过值查询jsonb?