Sorting values of an excel column by max occurrenc

2019-09-05 13:48发布

I have an excel file which has column B1 to B500 (may vary) filled with numbers. For example:

![sample data](http://i.stack.imgur.com/zSkLt.jpg)

I need the output to be like:

![sample output](http://i.stack.imgur.com/nTqEK.jpg)

I have this much code till now:

 Sub Max()
    Dim i As Long, j As Long
    Dim cl As Excel.Range

    i = 1
    j = 1
    For i = sheet.UsedRange.Rows.Count To 1 Step -1
        cl = sheet.Cells(i, 2) '## Examine the cell in Column B
        If xl.WorksheetFunction.CountIf(sheet.Range("B:B"), cl.Value) > 1 Then
            cl.Value = sheet.Cells(j, 3).value 'copy to Column C
        End If
        j = j + 1
    Next i
End Sub

What this code does is to find duplicates in column B and remove other entries from the column. Nothing gets written in column C. I want the column B to be unedited at the end. Also cannot figure out how to achieve the sorting here.

Please help.

标签: vb.net excel
1条回答
Viruses.
2楼-- · 2019-09-05 14:20

Well, you could use formulas if you want too:

Static Sort Using Excel Formulas - lmiguelmh

It is very important to use array formulas (Ctrl+Shift+Enter when done editing the cell), my Excel is an Spanish Version, so you just need to change: - SI by IF - CONTAR.SI by COUNT.IF

I came up with this solution thinking about the bubble sort algorithm. I hope this will be useful for you.

查看更多
登录 后发表回答