arrays - 将数组写入 ArrayList 的函数

标签 arrays vba excel arraylist

我正在尝试创建一个 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/

相关文章:

vba - Outlook VBA 未在某些 Windows 10 计算机上返回 CurrentUser Recipient 对象

excel - 删除偏移1的行

excel - MS Access 和 Excel 实例化,xlup 未定义

regex - excel VBA 正则表达式 5.5 捕获组

java - 在另一个 JSON 数组中解码 JSON 数组中的信息

c++ - 从 C++ 中的 char 函数返回一个 char 数组

javascript - 正则表达式:多次匹配相同的表达式并返回表达式前的完整字符串

c++ - 在 C++ 中通过初始化数组初始化 vector 时出现段错误

excel - 如何使用 Selenium 包装器从带有 vba 的 html 中获取特定元素

vba - 当我在 vba powerpoint 中按下一个键时调用一个 Sub