【问题标题】:Removing items from multiple comboboxes从多个组合框中删除项目
【发布时间】:2013-11-01 01:59:55
【问题描述】:

我有 7 个组合框。所有这些组合框都有相同的来源。

With Sheets("Data_Sheet")

Sheets("UI_Interface").ComboBox2.ListFillRange = "Data_Sheet!E2:E" & .Cells(Rows.Count, 5).End(xlUp).Row

End With

已为其他组合框编写了相同的代码。

Now when a value from combobx1 is selected it should not be present in other comoboxes. 当我尝试使用以下代码执行此操作但此代码出现错误时。

j = ComboBox1.ListIndex

ComboBox2.RemoveItem (j)

我也尝试了一些不同的属性来删除该值,但都给出了一些例外。

这段代码有什么不正确的地方?

【问题讨论】:

    标签: vba excel combobox


    【解决方案1】:

    除非我使用.ListFillRange 方法填充组合框,否则RemoveItem 方法对我来说可以正常工作。如果您改用 .List 方法,它应该可以工作。为此,您必须将范围转换为数组。

    修订

    感谢 enderland 指出您在工作表上使用表单控件,而不是在用户表单中。所以方法应该是相似的,但你不能使用ListFillRange 方法。没什么大不了的,我们可以轻松地获取该范围,将其转换为变量/数组,然后使用 List 方法。

    Option Explicit
    Private Sub Worksheet_Activate()
    '## Sets default list for ComboBoxes on this sheet
        SetComboBoxLists ComboBox1
        SetComboBoxLists ComboBox2
    
    End Sub
    Private Sub ComboBox1_Change()
    '## event handler for a combobox, repeat as needed
        '## Repopulate the list, otherwise you may get
        '    an Index out of Range error or Invalid Argument error,
        '    or the RemoveItem method will remove the wrong item
        SetComboBoxList ComboBox2
        '## Now, remove the item selected in ComboBox1
        ComboBox2.RemoveItem ComboBox1.ListIndex
    End Sub
    
    Private Sub SetComboBoxLists(cBox As MSForms.ComboBox)
    '## Subroutine to fill the list in each combobox as needed
    Dim lstRange As Variant
    
        '## Populate the array variable to use for the combobox.List method:
        '    double-check that I put the parentheses in the right place!
        With Sheets("Data_Sheet")
            lstRange = .Range("E2:E" & .Cells(Rows.Count, 5).End(xlUp).Row)
        End With
    
        '## Populate the combobox with the list
        cBox.List = lstRange
    
    End Sub
    

    请注意,如果您的任何代码操作(例如,调整大小、删除行等)该范围,您将需要重新应用 List 方法。

    【讨论】:

    • 我的猜测是组合框在工作表本身中并且与特定范围相关联(这就是为什么它们不能满足 OP 的要求)。
    • ...虽然我很确定这仍然可以解决问题,所以这里是 +1 :)
    • @enderland 不错。我稍后会测试一下。如果它不能立即工作,它可以快速修复 OP 的代码,首先将范围转换为变体,然后使用 .list 方法填充组合框,然后应该允许这样做。
    • 对不起,问题不清楚。我实际上是在工作表上使用 ActiveX 控件。组合框在第二张表中有一个范围的来源。
    猜你喜欢
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多