【问题标题】:How can I get a unique set of values?如何获得一组独特的值?
【发布时间】:2015-12-13 15:10:46
【问题描述】:

给定某种值的集合(数组或某种集合),我如何生成一组不同的值?

【问题讨论】:

  • @Jeeped 这旨在展示一般技术,而不是混入 Excel 或其他特定于主机的代码。
  • 是的,我完全了解您想要完成的工作。只是已经有如此多的 Scripting.Dictionary 示例我质疑我们是否需要非社区 Wiki 的自我回答的帖子。也许您应该注册新的Warlords of Documentation 努力。我有。
  • @Jeeped 可能已经有很多可用的 Dictionary 示例,但很少显示这种特定技术,并且它总是与特定于主机的代码一起隐藏。 (是的,我已经注册了 SO 文档测试版。)

标签: vba vbscript vb6


【解决方案1】:

使用Scripting.Dictionary工具 -> 参考... -> Microsoft Scripting Runtime):

Function Unique(values As Variant) As Variant()
    'Put all the values as keys into a dictionary
    Dim dict As New Dictionary
    Dim val As Variant
    For Each val In values
        dict(val) = 1
    Next
    Unique = dict.Keys 'This cannot be done with a Collection, which doesn't expose its keys
End Function

在 VBScript 或 VBA 中,如果您更喜欢使用后期绑定(没有显式类型的变量):

Function Unique(values)
    Dim dict, val
    Set dict = CreateObject("Scripting.Dictionary")
    For Each val In values
    ...

如果在 Mac(没有 Microsoft Scripting Runtime)上运行 VBA,则有一个 drop-in replacement for Dictionary 可用。

一些例子:


另一个选项(仅限 VBA)是使用 Collection。这有点尴尬,因为没有办法在不抛出错误的情况下设置现有键,并且必须手动创建返回的数组:

Function Unique(values As Variant) As Variant()
    Dim col As New Collection, val As Variant, i As Integer
    For Each val In values
        TryAdd col, val, val
    Next
    Dim ret() As Variant
    Redim ret(col.Count - 1)
    For i = 0 To col.Count-1
        ret(i) = col(i+1)
    Next
    Unique = ret
End Function

Sub TryAdd(col As Collection, item As Variant, key As String)
    On Error Resume Next
    col.Add(item, key)
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2022-01-11
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多