1

I stuck with a problem in excel, also new to VBA macro. I have 4 sheets (sheet 1, Sheet 2, Sheet 3, Sheet 4) in a excel file which consists of same two columns in all the Sheets. Columns namely "Person name" and "Sequence Count" My sheets looks like this:

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

Now after running the desired Macro, I need the output in this format

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

I mean to say, In the sheet 1, Value named "John" has 4 counts so it is printed in sequence number 1,2,3,4 and in sheet 2, the same Value "John" has again appeared 2 times, so in the sequence number column the count has continued from sheet 1 (5,6). As the value changes to "Mathew" in the sequence number column it has allotted the count (1) Sheet 1, In sheet 2 for the Particular value "Mathew" the count is incremented from sheet 1 and it is printed, as of same in the sheet 3. Now, this should apply for all the values.

Please help me regarding this, as the data is huge it is impossible to manipulate manually. Please show me the way in macros. Thanks in advance.

4

1 回答 1

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
于 2013-07-10T16:11:55.933 回答