Greetings!
I'm starting to experiment with arrays to expand my vba proficiency and decided to see if I could use an array to count the number of instances of a bunch of entries in a list. This obviously could then be used to show duplicates or unique values etc. etc.
I know there are likely more efficient ways to do it - it's not really about the end goal but more about figuring out how to use arrays!
Anyhow, I have the following code:
Sub CountInstances()
Dim summary() As Integer, size&, present As Boolean, pos&
size = 2
ReDim summary(size, 2)
For i = 1 To Range("A" & Rows.Count).End(xlUp).Row
present = False
'check if "i" is in array
For k = 1 To size
If summary(k, 1) = Range("A" & i).Value Then
present = True
pos = k
Exit For
End If
Next k
'if "i" is in array, find coordinates and add 1 to second 1
If present = True Then
summary(k, 2) = summary(k, 2) + 1
'if "i" is not in array, increase upperbound by 1, add it to array
Else
size = size + 1
ReDim summary(size, 2) As Integer
summary(size, 1) = Range("A" & i).Value
summary(size, 2) = 1
End If
Next i
'This is just to test if it's worked. It doesn't.
Sheets(2).Activate
For i = 1 To size
Range("A" & i).Value = summary(i, 1)
Range("B" & i).Value = "Number of instances of " & summary(i, 1) & ": " & summary(i, 2)
Next i
End Sub
This is what I get from th
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
0 |
Number of instances of 0: 0 |
7 |
Number of instances of 7: 1 |
So, for some reason it only remembers the last entry to the table - which is the 7. Everything else seems to get forgotten along the way.
What am I doing wrong, and do you have any generic tips for dealing with arrays where I'm going horribly wrong? I know it's inefficient to keep redefining the array - could I possibly set the array size from the start to be the total number of entries in the sample I'm analysing (which obviously would be the max number of inputs if there were zero duplicates) and then resize it smaller to match the number of actual entries to the array?
Any suggestions would be appreciated!
Thanks,
Lady Marmalade
Bookmarks