0

On Excel-VBA I have an array of collections (trying to function as a hashlist) that I want to pass into a function.

This is what I originally had.

Dim hashArray(200) As New Collection

populateHashArray(hashArray)
Function populateHashArray(data As Variant)
    data(2).Add "value"
End Function

Whenever the code fires off the data(2).Add "value" line I get the following error: Object variable or With block variable not set.

First attempted Fix: I tried to change the function parameters from "As Variant" to "As Collection"

Function populateHashArray(data As Collection)
    data(2).Add "value"
End Function

This gave me a ByRef mismatch

Would any of you guys know how to solve this?

vba_user111
  • 215
  • 1
  • 15
Stevoni
  • 3
  • 5

1 Answers1

0

This is a side effect of using New in your array declaration - you set up an auto-instancing situation which only applies in the calling sub but not in the called function.

To illustrate:

Sub Tester()

    Dim hashArray(200) As New Collection

    Debug.Print "hashArray(2) = ", TypeName(hashArray(2)) '>> Collection

    populateHashArray hashArray

End Sub

Function populateHashArray(data() As Collection)
    Debug.Print "data(1) in function = ", TypeName(data(1)) '>> Nothing
    Debug.Print "data(2) in function = ", TypeName(data(2)) '>> Collection
End Function

Referencing hashArray(2) in Tester auto-creates a Collection instance at that position in the array, and it's still there in populateHashArray.

hashArray(1) was not referenced in Tester, so data(1) is empty (Nothing) in populateHashArray.

More on this: What is the reason for not instantiating an object at the time of declaration?

Tim Williams
  • 154,628
  • 8
  • 97
  • 125