2017-04-10 43 views
-1

我想识别以特定名称John开头的列中唯一值的计数。计算以特定名称开头的VBA中唯一值的计数

你如何在VBA中做到这一点?

ColumnA ColumnB 
JohnRed 3 
JohnBlue 
JohnGreen 
JohnRed 
IanRed 

如果您正在寻找约翰。然后它的3.

+1

你应该在这里找到答案。 https://support.office.com/zh-cn/article/count-unique-values-among-duplicates-8d9a69b3-b867-490e-82e0-a929fbc1e273 – Variatus

+0

@ Variatus是的,先生,我在阅读之前张贴在这里。但他们没有与条件 – Sid29

+0

这是您搜索范围的定义的一部分。如果我们帮助您定义以“John”开头的范围,MSDN支持中的公式是否会为您完成这项工作? – Variatus

回答

1

您可以尝试读取Range的值,并与"John*"进行比较。稍后使用Dictionary来计算独特的Keys

代码

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 
+0

谢谢先生!我可以根据我的要求改变这一点。 – Sid29

+0

@VBA_Begineer欢迎您:) –