使用 VBA 获取在 VBA 中使用的唯一值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15799172/
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-08 15:18:57  来源:igfitidea点击:

Use VBA to get Unique values for use within VBA?

arraysexcelvbaexcel-vbaunique

提问by user2140261

I currently would use something like this either with Range, Cells or the like many different ways same basic principle.

我目前会在范围、单元格或类似的许多不同方式中使用类似的基本原理。

Range("A1", Range("A1").End(xlDown)).AdvancedFilter Action:=xlFilterCopy, _
    CopyToRange:=Range("IV1"), Unique:=True

Dim myArr as Variant 
myArr = Range("IV1", Range("IV1").End(xlDown))
Columns("IV").Delete

Is there a way to directly load those unique values into any type of object in VBA without the need to copy to another location?

有没有办法将这些唯一值直接加载到 VBA 中的任何类型的对象中,而无需复制到另一个位置?

回答by Siddharth Rout

You can use a Collection Objectto create unique entries. For example

您可以使用 aCollection Object创建唯一条目。例如

Sub Sample()
    Dim Col As New Collection
    Dim itm
    Dim i As Long
    Dim CellVal As Variant

    '~~> Lets say looping through Row 1 to 22 For 
    '~~> Range("A1:A22") as mentioned in your recent comment
    For i = 1 To 22
        CellVal = Sheets("Sheet1").Range("A" & i).Value
        On Error Resume Next
        Col.Add CellVal, Chr(34) & CellVal & Chr(34)
        On Error GoTo 0
    Next i

    For Each itm In Col
        Debug.Print itm
    Next
End Sub

ScreenShot:

截图

enter image description here

在此处输入图片说明