在 VBA 中将数组转换为集合的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12258732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 17:34:01  来源:igfitidea点击:

Easy way to convert an Array to a Collection in VBA

arraysvbacollections

提问by Peter T.

Is there an easy way to populate a Collection with all Values from an Array in VBA? e.g. something like

有没有一种简单的方法可以用 VBA 中的数组中的所有值填充集合?例如像

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

A simple solution would be of cause to iterate over the array, but I would expect that a modern language offers such methods out of the box ...

一个简单的解决方案是迭代数组的原因,但我希望现代语言提供这种开箱即用的方法......

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

Thanks for any hints!

感谢您的任何提示!

回答by Jon Egerton

"modern language" is where your problem lies - VBA/VB6 aren't really modern - neither have been advanced much for some years.

“现代语言”就是您的问题所在——VBA/VB6 并不是真正的现代语言——这些年来它们都没有取得太大进步。

If you need to do it a lot, write a function to do the looping:

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

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

or if you want a new collection each time:

或者如果您每次都想要一个新系列:

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

and then use it:

然后使用它:

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

or

或者

Dim a(10) as Variant
Dim c as Collection
...
Set c = ToCollection(a)