计算VBA中以特定名称开头的唯一值的计数
我试图识别以特定名称John开头的列中唯一值的计数 如何在VBA中实现这一点计算VBA中以特定名称开头的唯一值的计数,vba,excel,Vba,Excel,我试图识别以特定名称John开头的列中唯一值的计数 如何在VBA中实现这一点 ColumnA ColumnB JohnRed 3 JohnBlue JohnGreen JohnRed IanRed 如果你在找约翰。然后是3。您可以尝试从范围中读取值,并与“John*”进行比较。稍后使用字典计算唯一的键 代码 Option Explicit Sub UniqueJohns() Dim JohnsArr As Variant Dim i As Long Dim Dict A
ColumnA ColumnB
JohnRed 3
JohnBlue
JohnGreen
JohnRed
IanRed
如果你在找约翰。然后是3。您可以尝试从
范围中读取值,并与“John*”
进行比较。稍后使用字典
计算唯一的键
代码
Option Explicit
Sub UniqueJohns()
Dim JohnsArr As Variant
Dim i As Long
Dim Dict As Object
Dim Result As Long
Set Dict = CreateObject("Scripting.Dictionary")
' read into array, to run faster
JohnsArr = Application.Transpose(Range("A1:A5"))
' loop through array elements
For i = 1 To UBound(JohnsArr)
If JohnsArr(i) Like "John*" Then
' check if already exists in Dictionary
If Not Dict.exists(JohnsArr(i)) Then
Dict.Add JohnsArr(i), JohnsArr(i)
End If
End If
Next i
Result = UBound(Dict.keys) ' <-- this is the result, unique keys in Dictionary
MsgBox Result
End Sub
选项显式
大学附属学院()
Dim JohnsArr作为变体
我想我会坚持多久
作为对象的Dim Dict
结果很长
Set Dict=CreateObject(“Scripting.Dictionary”)
'读入阵列,以更快地运行
JohnsArr=Application.Transpose(范围(“A1:A5”))
'循环遍历数组元素
对于i=1至UBound(约翰萨尔)
如果约翰萨尔(我)喜欢“约翰*”那么
'检查字典中是否已存在
如果不存在Dict.exists(JohnsArr(i)),则
添加JohnsArr(i),JohnsArr(i)
如果结束
如果结束
接下来我
Result=UBound(Dict.keys)'您应该在这里找到答案@是的,先生,我在这里发布之前读过。但他们并没有以条件开头,这是搜索范围定义的一部分。如果我们帮助您定义一个以“John”开头的范围,MSDN支持中的公式是否能为您提供帮助?@Robin Mackenzie-他想计算的是唯一的值,而不是重复。@Variatus-没问题,误读了问题。现在我重读它,我感到困惑。这是一个标题为值为John
的列的范围,还是一个值前缀为John
的列的范围,我想计算John_foo
出现的次数?谢谢先生!我可以根据我的要求修改这个。