I started using Collection
in VBA (Excel AddIn --> xlam), but find it quite hard to use. I cannot retrieve anything I put into, other then Variants. In Java for example, if you make a Collection
, you assign a type to it, like Collection<MyPerfectObjectThatStoresSomeData>
, so when I foreach it, I know I get my object back and can use it like that. When I would like to do the same in VBA, I get back Variant
types and I can't even cast it to my type.
Example.
Let's say I would like to get the last entry from the Collection
I fill up like this:
Private Function FindTargets(sheet As Worksheet, target As String) As Collection
Dim result As New Collection
Dim aCell As range
Dim i As Long
For i = 1 To 10456
Set aCell = sheet.Rows(i).Find(What:=target, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
MsgBox "Value Found in Cell " & aCell.Address & _
" and the Cell Column Number is " & aCell.Column
result.Add aCell
End If
Next i
Set FindTargets = result
End Function
After, I would like to loop through the results, but I cannot event get the last entry out without an error:
Dim targetCollection As Collection
Set targetCollection = FindTargets(targetSheet, "some text")
Dim target As range
target = targetCollection.Item(targetCollection.Count - 1)
I get the error:
Run-time error '91':
Object variable or With block variable not set
If I try
Set target = targetCollection.Item(targetCollection.Count - 1)
I get:
Run-time error '1004':
Application-defined or object defined error
Can I only loop and get entries from a Collection
into other than Variant
types?
Edit: To be more specific, this code would need the range's coordinates, but in a Variant
I get the text of the cell. I thought about making a new Class, like CellProperties
with properties to both text and coordinates and put this into the Collection, but again, I cannot retrieve anything other than Variant from a Collection
.