Excel在一行中列出数组(不重复)
在Excel中,我有一个由A1到P30填充名称的数组。 一些单元格具有相同的名称(重复)。 有没有一个公式可能列出这个数组的所有内容在一个单一的列(在另一个表)? 该列表必须只收集唯一的名称(不重复)。
提前致谢。
尝试这个:
Function Unique(strRng As String) As Variant() Dim Arr() As Variant ReDim Arr(0) Dim rng As Range Dim c As Range Dim Duplicated As Boolean Dim i As Long Dim j As Long j = 0 Set rng = Range(strRng) For Each c In rng.Cells Duplicated = False If c.Value <> vbNullString Then For i = LBound(Arr) To UBound(Arr) If c.Value = Arr(i) Then Duplicated = True Exit For End If Next i If Not Duplicated Then ReDim Preserve Arr(j) Arr(j) = c.Value j = j + 1 End If End If Next c Unique = Arr End Function 'Unique
更新
似乎你坚持使用一个function。 简单。 创build一个用户定义函数 (UDF)如下:
Function Unique(rng As Range) As Variant() Dim Arr() As Variant ReDim Arr(0) Dim c As Range Dim Duplicated As Boolean Dim i As Long Dim j As Long j = 0 For Each c In rng.Cells Duplicated = False If c.Value <> vbNullString Then For i = LBound(Arr) To UBound(Arr) If c.Value = Arr(i) Then Duplicated = True Exit For End If Next i If Not Duplicated Then ReDim Preserve Arr(j) Arr(j) = c.Value j = j + 1 End If End If Next c Unique = Arr ' OR 'Unique = Application.Transpose(Arr) 'Use this when you want transpose your range from row to column or back. End Function 'Unique
如何使用该function?
请注意,这是一个array form
函数。
- 在VBA中编写第二个代码。
- select你想要返回你的唯一值的范围。 ( 在每张表格和列的每个部分 )
- 在编辑栏中写入
=Unique(A1:P30)
,然后按下键盘上的Ctrl + Shift + Enter键。 (不要按Enter键 )
现在,如你所说,你有一个公式可以返回一个范围的唯一值。
我更喜欢使用集合或字典来检查重复。
在这个例子中,我使用了一个ArrayList
Sub ProcessNames() Dim v As Variant Dim list As Object Set list = CreateObject("System.Collections.ArrayList") With Worksheets("Sheet1") For Each v In .Range("A1:P30").Value If Not list.Contains(v) Then list.Add v End With '1 Dimensional 0 Based Array which will span 1 Row v = list.ToArray '2 Dimensional 1 Based Array that will span 1 Column v = WorksheetFunction.Transpose(v) End Sub