Skip to main content

VBA Function to return unique values



'The following function returns a unique list if passed an array of values

Public Function UniqueValues(SourceValues As Variant) As Variant
'Returns a variant containing the unique values contained within SourceValues
'If called from a worksheet array formula, returns either a row or column array, as needed.
Dim Items As New Collection
Dim i As Long, j As Long, m As Long, nCols As Long, nRows As Long, Row As Long
Dim rg As Range
Dim cel As Variant, Result() As Variant

On Error Resume Next
Set rg = Application.Caller
For Each cel In SourceValues
   If cel <> "" Then Items.Add CStr(cel), CStr(cel)
Next
If rg Is Nothing Then
Else
    nCols = rg.Columns.Count
    nRows = rg.Rows.Count
    m = Application.Max(nCols, nRows)
End If
On Error GoTo 0

i = Items.Count
ReDim Result(1 To i)
For Row = 1 To i
     j = 0
    If rg Is Nothing Then
        For Each cel In SourceValues
            If cel = Items(Row) Then j = j + 1
        Next
        Result(Row) = Items(Row) ' & "(" & j & ")"
    Else
        Result(Row) = Items(Row) '& "(" & Application.CountIf(SourceValues, Items(Row)) & ")"
    End If
Next Row

If m > i Then
    ReDim Preserve Result(1 To m)
    For Row = i + 1 To m
       Result(Row) = ""
    Next Row
End If

If nRows < 2 Then
    UniqueValues = Result
Else
    UniqueValues = Application.Transpose(Result)
End If

End Function

Comments

Popular posts from this blog

A simple customization in MPOS (Blank Operation) with AX7

Hi All, I recently had to add a Blank Operation to Modern POS (MPOS) to open a url from MPOS. Blank Operation as you may already be aware enable you to extend Microsoft Dynamics Retail for POS by adding custom logic that can be triggered from the Retail POS Register buttons. The way to implement Blank Operations in MPOS  is different from Enterprise POS as MPOS is a modern app as compared to EPOS which is a windows forms based app. So lets explore a very simple customization i.e. we want to open a URL on triggering a button from MPOS. 1. We would need to start with AX to add a button to the layout of MPOS. If you do not want to disturb the standard layouts its better to copy one of the existing layouts and then modify it using the designer. Please note the designer only opens in Internet Explorer so it will save you time by not trying to open it in other browsers e.g Chrome 2. Next we need to add this layout to the Store where we intend to use it, in

Hyper-V VM 100% disk utilization

I was facing a persistent issue of 100% disk utilization on starting any VM in my Hyper-V. The below link helped me to resolve it https://social.technet.microsoft.com/Forums/office/en-US/2b184f22-ea8c-4bc3-9f64-8b46eeaeef61/hyperv-host-disk-usage-at-100?forum=w8itprovirt