我在A列中有一列数据,如下所示:
Joe
Joe
Joe
John
John
Josh
Josh
Josh
Josh
有人可以向我提供代码,该代码可以汇总Joes,Johns和Joshs的数量,并将每个名字的总和放在邻接列中。先感谢您!巨大的帮助..我有5000行名称
答案 0 :(得分:0)
<强> [注] 强>
问题的含义一直在变化。我的回答是指原始版本的问题。
您可以使用Dictionary class来计算string
中每个名字的数量。请看:
'needs reference to Sctipting Runtime dll
Sub DoSomething()
Dim s As String, result() As String
Dim i As Integer, counter As Integer
Dim dic As Dictionary, k As Variant
s = "Joe Joe Joe John John Josh Josh Josh Josh"
result = Split(s, " ")
Set dic = New Dictionary
With dic
.CompareMode = BinaryCompare
For i = LBound(result) To UBound(result)
If Not .Exists(result(i)) Then
.Add Key:=result(i), Item:=1
Else
k = dic(result(i))
dic(result(i)) = k + 1
End If
Next
End With
For Each k In dic.Keys
Debug.Print k, dic(k)
Next
Set dic = Nothing
End Sub
结果:
Joe 3
John 2
Josh 4
<强> [编辑] 强>
关于更改的问题,您只需更改一个循环。而不是:
For i = LBound(result) To UBound(result)
'
Next
使用:
'earlier (variable declaration section):
Dim wsh As Worksheet
'later:
Set wsh = Thisworkbook.Worksheets("SheetName")
i = 2
Do While wsh.Range("A" & i) <>""
If Not .Exists(wsh.Range("A" & i)) Then
.Add Key:=wsh.Range("A" & i), Item:=1
Else
k = dic(wsh.Range("A" & i))
dic(wsh.Range("A" & i)) = k + 1
End If
i = i +1
Loop
最后说明:
我建议您将注意力放在array formula上,这样您就可以进行任何计算。
要做的步骤(MS Excel 2010及更高版本):
1)将列A
复制到新工作表
2)删除重复项(使用菜单)
3)选择列B
并插入以下公式:
=SUM(IF((Sheet1!$A$1:$A$1000=$A1), 1, 0))
4)按CTRL
+ SHIFT
+ ENTER