[英]Passing an Array of Collections as a Parameter
On Excel-VBA I have an array of collections (trying to function as a hashlist) that I want to pass into a function. 在Excel-VBA上,我有一个要传递给函数的集合数组(试图用作哈希表)。
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. 每当代码触发
data(2).Add "value"
行时,都会出现以下错误: 对象变量或With块变量未设置。
First attempted Fix: I tried to change the function parameters from "As Variant" to "As Collection" 首次尝试修复:我尝试将功能参数从“ As Variant”更改为“ As Collection”
Function populateHashArray(data As Collection)
data(2).Add "value"
End Function
This gave me a ByRef mismatch 这给了我ByRef不匹配的情况
Would any of you guys know how to solve this? 你们当中有人知道如何解决这个问题吗?
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. 这是在数组声明中使用
New
的副作用-您设置了自动实例化情况,该情况仅适用于调用子而不适用于被调用函数。
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 . 在Tester中引用
hashArray(2)
会在数组中的该位置自动创建一个Collection实例,并且该实例仍在populateHashArray中 。
hashArray(1)
was not referenced in Tester , so data(1)
is empty (Nothing) in populateHashArray . 在Tester中未引用
hashArray(1)
,因此populateHashArray中的 data(1)
为空(无)。
More on this: What is the reason for not instantiating an object at the time of declaration? 有关此内容的更多信息: 在声明时不实例化对象的原因是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.