Hi.
I currently have an array and I want to count the number of duplicates in this array, but I'm not sure exactly the best approach for this.
Current Array
Array: arry(i,count)
arry(1,count) = 'ISB2-01"
arry(2,count) = 'ISB2-01"
arry(3,count) = 'ISB2-02"
arry(4,count) = 'ISB2-02"
arry(4,count) = 'ISB2-02"
arry(5,count) = 'ISB2-03"
New Array Result (this is what I want to end up with)
newarry(string,count) = newarry("ISB2-01",2)
newarry(string,count) = newarry("ISB2-02",3)
newarry(string,count) = newarry("ISB2-03",1)
I know this is pretty easy but I can't rap my head around it to get this.
Hi,
You could consider using a dictionary object to do this. For example:
Results in immediate window:Sub foo() Dim sarrCodes(0 To 5) As String Dim a As Long Dim vKey As Variant Dim objDic As Scripting.Dictionary sarrCodes(0) = "ISB2-01" sarrCodes(1) = "ISB2-01" sarrCodes(2) = "ISB2-02" sarrCodes(3) = "ISB2-02" sarrCodes(4) = "ISB2-02" sarrCodes(5) = "ISB2-03" Set objDic = CreateObject("Scripting.Dictionary") For a = LBound(sarrCodes) To UBound(sarrCodes) If objDic.Exists(sarrCodes(a)) Then objDic.Item(sarrCodes(a)) = objDic.Item(sarrCodes(a)) + 1 Else objDic.Add sarrCodes(a), 1 End If Next a For Each vKey In objDic.Keys Debug.Print vKey; objDic.Item(vKey) Next vKey End Sub
This example uses early binding so it requires a reference to the Microsoft Scripting Runtime library.ISB2-01 2 ISB2-02 3 ISB2-03 1
Last edited by Colin Legg; 03-06-2011 at 08:18 PM.
Is there any downfall with using this MS reference?
No, not really. Here's a late bound version if you don't want to add the reference...
Sub foo() Dim sarrCodes(0 To 5) As String Dim a As Long Dim vKey As Variant Dim objDic As Object sarrCodes(0) = "ISB2-01" sarrCodes(1) = "ISB2-01" sarrCodes(2) = "ISB2-02" sarrCodes(3) = "ISB2-02" sarrCodes(4) = "ISB2-02" sarrCodes(5) = "ISB2-03" Set objDic = CreateObject("Scripting.Dictionary") For a = LBound(sarrCodes) To UBound(sarrCodes) If objDic.Exists(sarrCodes(a)) Then objDic.Item(sarrCodes(a)) = objDic.Item(sarrCodes(a)) + 1 Else objDic.Add sarrCodes(a), 1 End If Next a For Each vKey In objDic.Keys Debug.Print vKey; objDic.Item(vKey) Next vKey End Sub
Last edited by Colin Legg; 03-06-2011 at 08:18 PM.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks