我会使用一个简单的VBA-Collection
,并通过 key 添加每个项。因为 key 本身不能重复,所以集合中将包含唯一的值。
注意:因为添加重复的 key 到 collection 会引发错误,请将 collection-add 的调用封装到 on-error-resume-next 中。
函数 GetUniqueValues
的参数是 source-range-values,返回一个包含唯一源范围值的VBA-Collection
。在main
方法中调用该函数,并将结果打印到输出窗口。希望这有帮助。
示例源范围如下:
![enter image description here](https://istack.dev59.com/wAY10.webp)
Option Explicit
Sub main()
Dim uniques As Collection
Dim source As Range
Set source = ActiveSheet.Range("A2:F6")
Set uniques = GetUniqueValues(source.Value)
Dim it
For Each it In uniques
Debug.Print it
Next
End Sub
Public Function GetUniqueValues(ByVal values As Variant) As Collection
Dim result As Collection
Dim cellValue As Variant
Dim cellValueTrimmed As String
Set result = New Collection
Set GetUniqueValues = result
On Error Resume Next
For Each cellValue In values
cellValueTrimmed = Trim(cellValue)
If cellValueTrimmed = "" Then GoTo NextValue
result.Add cellValueTrimmed, cellValueTrimmed
NextValue:
Next cellValue
On Error GoTo 0
End Function
输出
SGD
PHP
KRW
CNY
IDA
BGN
PDSS
CBBT
INPC
DBS
a
如果源范围包含多个区域,请先获取所有区域的值。
Public Function GetSourceValues(ByVal sourceRange As Range) As Collection
Dim vals As VBA.Collection
Dim area As Range
Dim val As Variant
Set vals = New VBA.Collection
For Each area In sourceRange.Areas
For Each val In area.Value
If val <> "" Then _
vals.Add val
Next val
Next area
Set GetSourceValues = vals
End Function
数据源类型现在是集合,但是所有操作都是一样的:
Dim uniques As Collection
Dim source As Collection
Set source = GetSourceValues(ActiveSheet.Range("A2:F6").SpecialCells(xlCellTypeVisible))
Set uniques = GetUniqueValues(source)