简体   繁体   中英

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.

Have searched many blogs, suggesting named ranges as Rowsource property, but my list have duplicate items & is dynamic.

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. The ComboBox will contain only A1:A10 distinct values

If you prefer a ComboBox ActiveX Object try this:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM