[英]Filtering a ListBox to only include unique values in Excel
我有一個簡單的Excel / VBA問題:
我要創建的是一個(單選)列表框,我要在其中顯示我在其他工作表上具有的數據的唯一值。
到目前為止,我有一個像這樣的ListBox:
以及要顯示的數據的命名選擇:
我使用了這樣的公式,並將其用作ListBox的輸入。
公式:= BEREICH.VERSCHIEBEN(TopicData!$ C $ 1; 1; 0; ANZAHL2(TopicData!$ C:$ C)-1; 1)
現在我的問題是:如何獲取僅顯示唯一值的ListBox? 我對vba很熟悉,因此包括此解決方案將是完全可以的。 實際上,每當ListBox發生更改時,我已經嘗試在vba中刪除重復的條目,但是由於某種原因,似乎沒有任何效果。
這是我嘗試解決此問題的vba腳本:
不幸的是,當我嘗試在ListBox上調用RemoveItem時,總是收到“錯誤400”。
' ...
' 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
'...
下面的代碼將使用Dictionary
來僅存儲C列中的唯一值(在“ TopicData”工作表中),然后在Dictionary
僅使用唯一值填充availableTopicsListBox
列表框。
碼
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.