Sum Unique/Distinct Values in Excel

Posted on the October 20th, 2009 under Excel VBA Function by Poer @ Excel VBA/Macro

Usually in the sequential database system, we can SUM only unique values in table column by adding all the values from SELECT DISTINCT query result only.

Based on the same principle, we can also create a simple VBA function in Microsoft Excel by adding the values only available in a collection of unique values we have created before hand.

Public Function DISTINCTSUM(Rg As range)
    Dim rCell As range
    Dim cCells As New Collection
    Dim vValue As Variant

    ' create a unique no duplicate value collection
    For Each rCell In Rg
        On Error Resume Next
        cCells.Add rCell.Value, CStr(rCell.Value)
    Next rCell

    ' sum all the data in previous collection
    For Each vValue In cCells
        DISTINCTSUM = vValue + DISTINCTSUM
    Next vValue

    Set cCells = Nothing
End Function

In here, first we create a Collection object that contains unique values only. Only then will we loop throught the collection and add up all the values stored there to get the DISTINCT SUM value.

Now we can call the above DISCTINCTSUM formula directly from Excel formula bar to sum only the unique or disctinct values in some range of cells, with the cell range as parameter.

=distinctsum(D4:D8)

Will sum all the unique values in range of D4 until D8. This is really helpful if we have a lot of duplicate data that we don’t want to count.

The other way around to get the sum of unique/distinct values in Excel is using Pivot Table.

Create a Pivot Table, then drop the column containing duplicate values in the Row fields area. Excel will then automatically filtered all the values and remove any duplicate values in that column. Later on, simply SUM all the data in the row fields to get the distinct sum.

The final result will be the same, but we don’t want to create a Pivot Table for every column we wanna sum, right?

Another way to get a list of unique values is to use the Advanced Filter feature. In advanced filtering options, check the option Copy to another location, and Unique records only option. Then select the cell where we want to put the unique values.

Easier to do compare to Pivot Table, but we still don’t have the flexibility of the previous DISTINCTSUM macro.

Related Entries

External Resources

Leave a Reply




XHTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
SYNTAX HIGHLIGHTER:
Place your VBA code between <pre> tags like this <pre class="brush:vb"> sub vba() ... end sub </pre>.