用于计算出现次数的VBA代码

时间:2014-09-22 13:06:13

标签: excel vba

我有一个A列,它有一些我需要的元素来计算D&列中的出现和粘贴。 E分别带有姓名和计数 由于A列中的元素各不相同,我无法使用记录数据透视表的VBA代码 有人可以帮帮我吗?

Name            Name    Count  
A                  A    5
A                  B    3
A                  C    1
A                  D    1
B               
B               
C               
B               
D               
A   

这就是我的尝试: -

Sub Macro1()
'
' Macro1 Macro
'

'
    Columns("A:A").Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Sheet1!R1C1:R1048576C1", Version:=xlPivotTableVersion14).CreatePivotTable _
        TableDestination:="Sheet1!R1C4", TableName:="PivotTable1", DefaultVersion _
        :=xlPivotTableVersion14
    Sheets("Sheet1").Select
    Cells(1, 4).Select
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Name")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
        "PivotTable1").PivotFields("Name"), "Count of Name", xlCount
End Sub

2 个答案:

答案 0 :(得分:0)

尝试这个小宏:

Sub KountUneek()
    Dim c As Collection, wf As WorksheetFunction, _
        K As Long, N As Long, i As Long, _
        v As Variant
    Set c = New Collection
    Set wf = Application.WorksheetFunction
    K = 1
    N = Cells(Rows.Count, "A").End(xlUp).Row
    On Error Resume Next

    For i = 1 To N
        v = Cells(i, "A").Value
        c.Add v, CStr(v)
        If Err.Number = 0 Then
            Cells(K, "B").Value = v
            Cells(K, "C").Value = wf.CountIf(Range("A:A"), v)
            K = K + 1
        Else
            Err.Number = 0
        End If
    Next i
    On Error GoTo 0
End Sub

例如:

PseudoPivot

答案 1 :(得分:0)

为什么你不喜欢这个VBA

=COUNTIF(A:A,C2)    'HERE C2 IS THE REFERENCE

enter image description here