循环单元格并在所有工作表中获取字符串值的计数,并将计数序列打印在相应工作表中的另一列中

时间:2013-07-10 15:16:06

标签: excel vba excel-vba excel-vba-mac

我遇到了excel中的问题,也是VBA宏的新问题。 我在excel文件中有4张纸(纸张1,纸张2,纸张3,纸张4),在所有纸张中包含相同的两列。列是“人名”和“序列计数” 我的床单看起来像这样:

Sheet 1
Person name | Sequence Number
John            
John
John
Mathew
Prince
Raj
Raj
Whale
Sheet 2
Person name | Sequence Number
John            
John
Mathew
Mathew
Prince
Prince
Raj
Raj
Raj
Whale
Whale
Sheet 3
Person name | Sequence Number
John            
John
John
John
Mathew
Prince
Sandy
Raj
Raj
Raj
Whale

现在运行了所需的宏后,我需要这种格式的输出

Sheet 1
Person name | Sequence Number
John            1
John            2
John            3
Mathew          1
Prince          1
Raj             1
Raj             2
Whale           1
Sheet 2
Person name | Sequence Number
John            4
John            5
Mathew          2
Mathew          3
Prince          2
Prince          3
Raj             3
Raj             4  
Raj             5
Whale           2
Whale           3
Sheet 3
Person name | Sequence Number
John            6
John            7
John            8
John            9
Mathew          4
Prince          4
Sandy           1
Raj             6
Raj             7
Raj             8
Whale           4

我的意思是说,在表1中,名为“John”的值有4个计数,因此它以序列号1,2,3,4打印,在表2中,相同的值“John”再次出现2因此,在序列号列中,计数从表1(5,6)继续。当序列号列中的值变为“Mathew”时,它已分配计数(1)表1,在表2中,对于特殊值“Mathew”,计数从表1开始增加并打印,如同在工作表3.现在,这应该适用于所有值。

请帮我解决这个问题,因为数据很大,无法手动操作。 请告诉我宏的方式。提前谢谢。

1 个答案:

答案 0 :(得分:0)

添加以下代码并添加对“Microsoft Scripting Runtime”(工具>参考)的引用,以便您可以使用字典结构

Sub CountOccurence()
' Reference: Microsoft Scripting Runtime

Application.ScreenUpdating = False

Set oDict = New Dictionary
Dim Shts() As Variant
Dim wS As Worksheet
Dim r As Integer, rLast As Integer
Dim i As Integer

Shts = Array("Sheet1", "Sheet2", "Sheet3", "Sheet4")

For i = 0 To 3 Step 1

    Set wS = Sheets(Shts(i))

    rLast = wS.Cells(1, 1).CurrentRegion.Rows.Count

    For r = 2 To rLast Step 1

        If Not (oDict.Exists(wS.Cells(r, 1).Value)) Then

            oDict.Add wS.Cells(r, 1).Value, 1

        Else

            oDict.Item(wS.Cells(r, 1).Value) = oDict.Item(wS.Cells(r, 1).Value) + 1

        End If

        wS.Cells(r, 2).Value = oDict.Item(wS.Cells(r, 1).Value)

    Next r

Next i

Set oDict = Nothing


Application.ScreenUpdating = True
End Sub