VBA在列表中显示唯一值

时间:2016-06-08 02:32:37

标签: excel vba

以下代码会过滤列中的唯一值。我试图在控制台中显示输出,但是,我得到一个超出范围的"下标"错误。函数的数组输出是否正确传递给变量?如果没有,问题是什么?非常感谢任何帮助。

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

2 个答案:

答案 0 :(得分:1)

另一个<div class="container"> <div class="parallelogram" style="background-color: red;"> 1 </div> </div> <div class="container"> <div class="parallelogram" style="background-color: green;"> 2 </div> </div> <div class="container"> <div class="parallelogram" style="background-color: blue;"> 3 </div> </div>候选人:函数名称为Option Explicit,但您返回的值为UnqiueMembers

这两个名字不一样; - (

答案 1 :(得分:0)

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

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

该集合不允许您添加任何重复值。 t将自动变为唯一。