vba 在 DropButtonClick 中填充组合框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12065420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 17:25:46  来源:igfitidea点击:

Populate a combobox in DropButtonClick

excelexcel-vbavba

提问by David Doria

I am trying to populate a combobox as it is needed, by doing the population in the DropButtonClick function. As a simple example:

我正在尝试通过在 DropButtonClick 函数中进行填充来根据需要填充组合框。作为一个简单的例子:

Private Sub cmbAdvisor_DropButtonClick()
    cmbAdvisor.Clear

    cmbAdvisor.AddItem ("Test1")
    cmbAdvisor.AddItem ("Test2")
End Sub

This works fine, and the values are shown in the drop down list. However, when I click on one of them, the drop down list goes away, and the combobox now displays nothing/blank. I would expect it to display the item that I had selected. I'm guessing the problem is that I am doing a Clear inside of this function - but how else would I go about this?

这工作正常,并且值显示在下拉列表中。但是,当我单击其中之一时,下拉列表消失,组合框现在不显示任何内容/空白。我希望它显示我选择的项目。我猜问题是我在这个函数内部做了一个 Clear - 但我还能怎么做呢?

回答by wbit

For an ActiveX control embedded on a sheet:

对于嵌入在工作表中的 ActiveX 控件:

The activeX combobox processes the click event on item selection as if it were an actual dropbuttonclick - which means we need a state object.

activeX 组合框处理项目选择上的点击事件,就好像它是一个实际的 dropbuttonclick - 这意味着我们需要一个状态对象。

Dim dropbuttonclicked As Boolean

Private Sub ComboBox1_DropButtonClick()
  dropbuttonclicked = Not dropbuttonclicked
  If dropbuttonclicked = True Then
    ComboBox1.Clear
    ComboBox1.AddItem ("Test1")
    ComboBox1.AddItem ("Test2")
  End If
End Sub

For a VBA ComboBox on a VBA UserForm, you might want to use Enterinstead:

对于 VBA 用户窗体上的 VBA 组合框,您可能需要使用Enter

Private Sub cmbAdvisor_Enter()
    cmbAdvisor.Clear
    cmbAdvisor.AddItem ("Test1")
    cmbAdvisor.AddItem ("Test2")
End Sub