我正在尝试创建一个 VBA 函数,它将数组写入 .NET System.Collections.ArrayList
并返回它。
到目前为止我已经:
Function arrayToArrayList(inArray As Variant) As ArrayList
'function to take input array and output as arraylist
If IsArray(inArray) Then
Dim result As New ArrayList
Dim i As Long
For i = LBound(inArray) To UBound(inArray)
result.Add inArray(i) 'throws the error
Next i
Else
Err.Raise 5
End If
Set arrayToArrayList = result
End Function
调用(例如)
Sub testArrayListWriter()
'tests with variant/string array
'intend to pass array of custom class objects
Dim result As ArrayList
Dim myArray As Variant
myArray = Split("this,will,be,an,array",",")
Set result = arrayToArrayList(myArray)
End Sub
但我收到错误
Variable uses an Automation type not supported in Visual Basic
可能是因为我的数组类型不正确(可能是Variant
)。然而
Dim v As Variant, o As Variant
v = "test_string"
set o = New testClass
result.Add v 'add a string in variant form
result.Add o 'add an object in variant form
不会引发任何错误,因此问题与 Variant
类型没有直接关系
这里发生了什么,有什么方法可以将未指定类型的数组写入ArrayList
,或者我必须定义inArray
的类型吗?
最佳答案
改变
result.Add inArray(i)
至
result.Add CVar(inArray(i))
关于arrays - 将数组写入 ArrayList 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47893857/