我在“H”列中有幾個名字。我想制作一個唯一的名稱串列并將其顯示在 Combobox 下拉串列中。這是我擁有的代碼,但它在串列中顯示了重復的名稱。
Sub Refresh_Customer_List()
Application.ScreenUpdating = False
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sale_Purchase")
Dim i As Integer
Me.cmb_Cust.Clear
Me.cmb_Cust.AddItem ""
If Application.WorksheetFunction.CountA(sh.Range("A:A")) > 1 Then
For i = 2 To Application.WorksheetFunction.CountA(sh.Range("A:A"))
Me.cmb_Cust.AddItem sh.Range("H" & i).Value
Next i
End If
End Sub
uj5u.com熱心網友回復:
請注意我如何在下面的代碼中通過幾個步驟創建可能包含您的下拉串列元素的范圍。我們定義感興趣的第一行(可能是第 2 行),然后查找包含任何資料的最后一行cells(rows.count,col).end(xlup)
如果您有 Office 365,則可以使用以下內容填充組合串列,而無需使用回圈:
Me.cmb_Cust.List = WorksheetFunction.Unique(Range(sh.Cells(2, "A"), sh.Cells(sh.Rows.Count, "A").End(xlUp)))
如果您沒有該Unique功能,您可以使用許多 VBA 物件來獲取不同的串列。這是使用 的一種方法ArrayList,但您也可以使用 Collection 或 Dictionary 物件。
有關 ArrayList 的資訊,當前有效的鏈接是VBA ArrayList - A complete guide
Dim AL As Object, v
Set AL = CreateObject("System.Collections.ArrayList")
For Each v In Range(sh.Cells(1, "A"), sh.Cells(sh.Rows.Count, "A").End(xlUp)).Value
If Not AL.contains(v) Then AL.Add (v)
Next v
Me.cmb_Cust.List = AL.toarray
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/504062.html
上一篇:通過回圈將一個動態陣列的值分配給另一個有變化的動態陣列(VBA)
下一篇:將范圍合并為CSV
