如何从Excel中的代码设置下拉select(VBA)

我正在尝试为Excel表进行过滤。 我有2个下拉框,项目列表dynamic地添加在一个macros被刷新时调用。

Set selectBook = Worksheets("Report").DropDowns("DropDownBook") selectBook.RemoveAllItems For Each b In books selectBook.AddItem (b) Next 

“书籍”是一个具有新价值的数组。 与“作者”其他下拉的代码是相似的。 运行此macros后,没有显示初始select。 我附加了一个macros到dropdownchange事件,它读取这两个下拉列表中的select

 Set books = Worksheets("Report").DropDowns("DropDownBook") bookSelect = books.List(books.ListIndex) 

并做必要的过滤。 问题是,如果我select一个作者,这个macros将在上面给出的第二行代码中断开

 Run time error '1004': Unable to get the List property of the DropDown class 

如果我select一本书,它将为作者做同样的事情。 我想这是因为没有在框中的初始select,但我似乎无法find一种方法如何使代码。 我努力了

 selectBook.ListIndex = 0, selectBook.Value=0 etc. 

,但没有任何工作。 我错过了什么明显的? 任何帮助将不胜感激。

我意识到自从发布这个问题已经有一段时间了,但由于没有答案,我会尽我所能提供一个答案。

您可以一次添加所有项目,而不是一次添加项目。 首先用逗号分隔所有选项创build一个“书单”,然后将其添加到单元格中。 看下面的例子。

 ' Create option list books = Array("The Very Hungry Caterpillar", "A Christmas Carol", "Ulysses") booklist = Join(books, ",") ' Set drop down list With Sheets("Books").Cells(1, 1).Validation .Delete .Add Type:=xlValidateList, Formula1:=booklist End With 

您可以将其封装到单独的过程中,只要您想要dynamic添加下拉列表,就可以调用该过程。

 Sub SetDropDown(cellRef As Range, valueArray As Variant) ' Declare variables Dim valueFormula ' Create formula valueFormula = Join(valueArray, ",") ' Set dropdown With cellRef.Validation .Delete .Add Type:=xlValidateList, Formula1:=valueFormula End With End Sub