2017-03-09 108 views
0

獨特的價值觀,我有一個簡單的Excel/VBA問題:過濾列表框只包括在Excel

我想創造就是我想告訴我有數據的唯一值(單選)列表框在不同的工作表上。

到目前爲止,我有這樣的一個列表框中:

enter image description here

而且數據的命名選擇我想表明:

enter image description here

我使用的公式是這樣和用它作爲ListBox的輸入。

enter image description here

公式:= BEREICH.VERSCHIEBEN(TopicData $ C $ 1; 1; 0; ANZAHL2(TopicData $ C:!$ C)-1; 1)

現在的問題是:我怎樣才能讓列表框顯示唯一的值?我對vba很熟悉,所以包含這個的解決方案將會完全正常。事實上,我已經嘗試刪除vba中的重複條目,只要ListBox發生更改,但由於某些原因,似乎沒有任何工作。

這裏是我的VBA腳本,我試圖解決這個問題:

unfortunatley我總是得到一個「錯誤400」時,我對特里結構呼籲列表框的removeItem

' ... 
' filter listbox content so only unique values remain 
Dim i As Integer 

' find duplicates 
Dim inList As New Collection 
Dim indexesToRemove As New Collection 

For i = availableTopicsListBox.ListCount - 1 To 1 Step -1 
    If CollectionContains(inList, availableTopicsListBox.List(i)) Then 
     ' if it is already in the list, remove it 
     indexesToRemove.Add i 
    Else 
     inList.Add availableTopicsListBox.List(i) 
    End If 
Next i 

' remove duplicates 
Dim j As Integer 
For j = indexesToRemove.count To 1 Step -1 
    availableTopicsListBox.RemoveItem (indexesToRemove(j)) 
Next j 
'... 
+0

您應該逐步通過主題列,並有一個包含唯一值的數組。然後檢查Topic列中的單元格是否在數組中,如果沒有添加它,則檢查下一行。 – Luuklag

+0

嘗試使用oledb連接到sam eworkbook ...編寫一個查詢以獲取不同的值並將它們複製到表單中的一個範圍並對該範圍進行refference .....請確保將該範圍作爲列表對象... 。所以值得到更新....無論是唯一值的數量 –

+2

你應該使用一個'Dictionary'來存儲你的範圍內的所有唯一鍵(我認爲列C:C),然後只添加唯一的鍵到你的'availableTopicsListBox' –

回答

2

下面的代碼將使用Dictionary存儲從列C只有唯一值(在「TopicData」工作表),然後填充availableTopicsListBox列表框僅與Dictionary內的唯一的值。

代碼

Option Explicit 

Private Sub UserForm_Activate() 

Dim Dict As Object 
Dim Key As Variant 
Dim LastRow As Long 
Dim C As Range 

With Sheets("TopicData") '<-- I think this is your sheet's name 
    ' find last row with data in column "C" 
    LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row 

    Set Dict = CreateObject("Scripting.Dictionary") 
    For Each C In .Range("C1:C" & LastRow) 
     If C.Value <> "" Then ' <-- skip empty cells 
      If Not Dict.exists(C.Value) Then 
       Dict.Add C.Value, 1 
      End If 
     End If 
    Next C 
End With 

' loop through all unique keys, and add them to the listbox 
For Each Key In Dict.keys 
    availableTopicsListBox.AddItem Key 
Next Key 

End Sub 
+1

@Florian Baierl你上面試過我的代碼嗎?它按照你的意圖工作嗎? –

+0

今天我試了一下,它的工作原理。 :)非常感謝您的詳細解答!對此,我真的非常感激。 –