繁体   English   中英

Excel计算一个值的出现

[英]Excel count occurrences of a value

我得到了与邮政编码相关联的数据。

我需要计算某些列中某些值出现的次数。 示例数据如下。

Survey# PostCode
1       2136
1       2136
2       136
2       2136
1       2137
2       2137

我想获取这些数据并生成这种类型的excel工作簿:

Postal Code Survey #1   Survey #2   Survey #3   Survey #4
2136        2           2           0           0
2137        1           1           0           0

我试图通过使用while循环和以下代码来编写代码以产生此结果。 该代码无需while循环即可工作。

如果您注释掉它的效果,但是,我必须选择所需的邮政编码,然后运行宏...在执行此操作时效果很好,它将所有出现的1,2,3加起来,或4,然后将这些计数值放在适当的列中。

我想要的是使它遍历该列,并用一个邮政编码(2136)将所有出现的事件相加,然后停止并将计数添加到列中。 然后再次开始计算下一个邮政编码的出现,直到到达下一个邮政编码,然后停止-添加计数。

Sub sort_PC_CPE()

Dim cell As Object
Dim count As Integer
Dim count1 As Integer
Dim count2 As Integer
Dim SV1Count As Integer
Dim SV2Count As Integer
Dim SV3Count As Integer
Dim SV4Count As Integer
Dim ofset As Integer
Dim newVal As Object

'Dim origvalue As Object

count = 0
count1 = 0
count2 = 0
SV1Count = 0
SV2Count = 0
SV3Count = 0
SV4Count = 0
ofset = -1

' if you use the for each cell... and then highlight the cells with the same postal code, this works (also commenting out the while loop)
'For Each cell In Selection

    While cell.Offset(ofset, 0).Value = cell.Value
        cell.Offset(ofset, 0).Select
        ofset = ofset - 1
    Wend

       'the following works well so long as you manually highlight the cells you want. 
        If cell.Offset(0, -3).Value = 1 Then

            SV1Count = SV1Count + 1
            cell.Offset(-count, 1).Value = SV1Count

            count = count + 1

        ElseIf cell.Offset(0, -3).Value = 2 Then

            SV2Count = SV2Count + 1
            cell.Offset(-count, 2).Value = SV2Count
            count = count + 1

        ElseIf cell.Offset(0, -3).Value = 3 Then

            SV3Count = SV3Count + 1
            cell.Offset(-count, 3).Value = SV3Count
            count = count + 1

        ElseIf cell.Offset(0, -3).Value = 4 Then

            SV4Count = SV4Count + 1
            cell.Offset(-count, 4).Value = SV4Count
            count = count + 1





    End If




End Sub

为什么不只使用数字呢?

我将样本放到A和B列的新表中,在DI列中,将1136放置在第1行中,将2137放置在第2行中。如果您有大量邮政编码,请从源中复制整列并粘贴到D列中,然后单击数据,然后删除重复项以获取您的非重复列表。

E1是这个公式:

=COUNTIFS($A:$A,COLUMN(E1)-4,$B:$B,$D1)

拖4列,然后向下2行

结果:

2136 2 2 0 0

2137 1 1 0 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM