9

有没有一种简单的方法可以在 VBA 中使用数组中的所有值填充集合?例如类似的东西

Dim c As New Collection
Dim a(10) As Variant
...
c.AddAll a

一个简单的解决方案将导致迭代数组,但我希望现代语言提供开箱即用的此类方法......

Dim c As New Collection
Dim a(10) as Variant
...
For Each item in a
  c.Add item
Next item

感谢您的任何提示!

4

1 回答 1

13

“现代语言”是您的问题所在 - VBA/VB6 并不是真正的现代语言 - 几年来也没有进步太多。

如果你需要做很多,写一个函数来做循环:

Sub AddAll(ByVal c as Collection, a as Variant)
    For Each item in a
      c.Add item
    Next item
End Sub

或者如果您每次都想要一个新集合:

Function ToCollection(a as Variant) As Collection
    Dim c As New Collection
    For Each item in a
      c.Add item
    Next item
    Set ToCollection = c
End Function

然后使用它:

Dim c As New Collection
Dim a(10) as Variant
...
AddAll c,a

或者

Dim a(10) as Variant
Dim c as Collection
...
Set c = ToCollection(a)
于 2012-09-04T07:46:35.473 回答