2016-06-08 67 views
0

以下代碼過濾來自列的唯一值。我試圖在控制檯中顯示輸出,但是,我收到「下標超出範圍」錯誤。函數的數組輸出是否正確地傳遞給變量?如果不是,那麼問題是什麼?任何幫助是極大的讚賞。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 
+1

簡單'UniqueMembers = uniqueList'不帶括號就可以了; ) –

+0

不幸的是,我仍然收到錯誤 – dfj328

+1

工作簿中是否有名爲** Input Data **的工作表? – MutjayLee

回答

0

如果我正確地閱讀本。如果你想要這個唯一的列表。使用集合。並拒絕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 

該集合將不允許添加任何重複值。 t會自動變得獨一無二。

1

另一個Option Explicit候選人:函數名稱是UnqiueMembers,但你被UniqueMembers = uniqueList()

這兩個名字都沒有返回值相同;-(