[英]Populate dynamic dropdown in Excel form with VBA
I have a dropdown on an Excel form which I want to populate with items listed in sheet "OR", however I need only unique entries from this dynamic list & then populate the dropdown. 我在一个Excel表单上有一个下拉菜单,我想用工作表“ OR”中列出的项目填充该表单,但是我只需要此动态列表中的唯一条目,然后填充该下拉列表。
Have searched many blogs, suggesting named ranges as Rowsource property, but my list have duplicate items & is dynamic. 搜索了许多博客,建议将命名范围作为Rowsource属性,但我的列表中有重复项,并且是动态的。
You can write this code: 您可以编写以下代码:
Dim s As String, r As Integer, nr As Integer, wr, v
Set wr = Range("A1:A10")
nr = wr.Rows.Count
For r = 1 To nr
v = wr(r, 1)
If InStr(s, v & ",") = 0 Then
s = s & v & ","
End If
Next
s = Left(s, Len(s) - 1)
With Range("D1").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Formula1:=s
End With
This uses data validation, I assume data is in A1:A10 and the ComboBox in D1. 这使用数据验证,我假设数据在A1:A10中,而ComboBox在D1中。 The ComboBox will contain only A1:A10 distinct values
ComboBox将仅包含A1:A10不同的值
If you prefer a ComboBox ActiveX Object try this: 如果您更喜欢ComboBox ActiveX对象,请尝试以下操作:
Dim s As String, r As Integer, nr As Integer, wr, v
Set wr = Range("A1:A10")
nr = wr.Rows.Count
With ComboBox1
.Clear
For r = 1 To nr
v = wr(r, 1)
If InStr(s, v & ",") = 0 Then
s = s & v & ","
.AddItem (v)
End If
Next
End With
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.