【问题标题】:Easy way to convert an Array to a Collection in VBA在 VBA 中将数组转换为集合的简单方法
【发布时间】:2012-08-28 19:59:01
【问题描述】:

有没有一种简单的方法可以在 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

感谢任何提示!

【问题讨论】:

    标签: arrays vba collections


    【解决方案1】:

    “现代语言”是您的问题所在 - 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)
    

    【讨论】:

    • 非常感谢您的快速帮助!我通常不喜欢 VBA 可能是有原因的 ;-)
    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 2014-11-23
    • 2020-07-17
    • 2021-11-17
    • 2011-10-03
    • 2014-07-23
    • 2011-10-03
    • 1970-01-01
    相关资源
    最近更新 更多