VBA显示列表中的唯一值

以下代码过滤来自列的唯一值。 我试图在控制台中显示输出,但是,我得到一个“下标超出范围”的错误。 函数的数组输出是否正确传递给variables? 如果不是,这是什么问题? 任何帮助是极大的赞赏。

Sub test1() Dim Member() As String Member = UnqiueMembers() Debug.Print Member(1) End Sub 

 ' get unique members from input data Public Function UnqiueMembers() As String() Const inputSheetName = "Input Data" Const inputRange = "A3:A9" Dim productWS As Worksheet Dim uniqueList() As String 'dyanmic array Dim productsList As Range Dim anyProduct Dim LC As Integer ReDim uniqueList(1 To 1) Set productWS = Worksheets(inputSheetName) 'Set outputWS = Worksheets(outputSheetName) Set productsList = productWS.Range(inputRange) Application.ScreenUpdating = False For Each anyProduct In productsList If Not IsEmpty(anyProduct) Then If Trim(anyProduct) <> "" Then For LC = LBound(uniqueList) To UBound(uniqueList) If Trim(anyProduct) = uniqueList(LC) Then Exit For ' found match, exit End If Next If LC > UBound(uniqueList) Then 'new item, add it uniqueList(UBound(uniqueList)) = Trim(anyProduct) 'make room for another ReDim Preserve uniqueList(1 To UBound(uniqueList) + 1) End If End If End If Next ' end anyProduct loop If UBound(uniqueList) > 1 Then 'remove empty element ReDim Preserve uniqueList(1 To UBound(uniqueList) - 1) End If UniqueMembers = uniqueList() End Function 

另一个Option Explicit候选:函数名称是UnqiueMembers但是您通过UniqueMembers = uniqueList()返回值

这两个名字不一样;-(

如果我正确阅读这个。 如果你想要这个唯一的列表。 使用集合。 并拒绝dups。

 Dim t As Collection Set t = New Collection Dim t As Collection Set t = New Collection On Error Resume Next t.Add "product name", "product name" t.Add "product name", "product name" t.Add "product name", "product name" t.Add "product name", "product name" t.Add "product name", "product name" t.Add "product name", "product name" On Error GoTo 0 

该集合将不允许您添加任何重复的值。 吨会自动变得独特。