如何在工作表VBA中的组合框中添加项目?

时间:2017-01-20 09:15:25

标签: excel vba excel-vba combobox

我需要在用户表单中的工作表中添加组合框中的项目。数据是基于指定范围的动态数据。这是我的代码,它不起作用。有多种标准,例如standard1,standard2,直到standardiLast。

Private Sub AvailStd_DropButtonClick()

Dim choicesheet As Object, iLast As Integer, iCount As Integer

Set choicesheet = Worksheets("Test")

iLast = choicesheet.Range("LastLine").Cells(1, 1)


For iCount = 1 To iLast
With choicesheet.OLEObjects("AvailStd").Object

    .AddItem_

     iCount& "." & choicesheet.Range("Standard" & iCount).Cells(1, 1)

End With
Next iCount




End Sub        

1 个答案:

答案 0 :(得分:1)

试试这个

Private Sub AvailStd_DropButtonClick()
    Static filled As Boolean '<--| static variable to last between events

    Dim iLast As Long, iCount As Long
    Dim cb As ComboBox

    If filled Then '<--| if combobox already filled up then exit and let the user selection be taken into account
        filled = False '<--| next time fill the combobox up
        Exit Sub
    Else '<--| otherwise fill the combobox up
        With Worksheets("Test")
            iLast = .Range("LastLine").Cells(1, 1)
            Set cb = .OLEObjects("AvailStd").Object
            cb.Clear
            For iCount = 1 To iLast
                cb.AddItem .Range("Standard" & iCount).Cells(1, 1)
            Next
            filled = True '<--| mark combobox is already filled up
        End With
    End If
End Sub