VBA Dependent Combobox

时间:2016-04-21 19:11:36

标签: excel-vba vba excel

我有3个相互依赖的组合框。 cmb2上的列表取决于cmb1上的值。 cmb3列表取决于cmb2值。

我的问题是,当我删除/删除所有组合框上的值时,当我点击cmb2时,它仍会显示在cmb1&上选择的最后一个值的列表。与cmb3相同。

如果它所依赖的组合框没有任何值,那么显示为空的代码是什么?

1 个答案:

答案 0 :(得分:0)

编辑:我认为根据评论中添加的信息,您应该将子逻辑封装在子过程和函数中。为了做到这一点,命名范围和组合框中的值之间应该有一些逻辑。

在下面的示例中,我创建了一个函数来处理独立组合框中的值和命名范围的转换。您可以提供自己的连接器,但我认为任何空格都将更改为下划线(因此,“帐户信息”将替换为“Account_Information”)。

接下来,子过程检查以确认工作簿中存在与独立组合框中的转换值匹配的命名范围。如果是这样,则依赖框将该命名范围作为其List属性。如果没有,则清除从属组合框。

使用这种类型的系统的好处是可以在不重写代码的情况下重复其他组合框。请参阅以下代码,如果您需要帮助,请告诉我们。

Private Sub UserForm_Initialize()
    With Me.ComboBox1
        .AddItem "Account Information"
        .AddItem "Other Stuff"
    End With
End Sub
Private Sub ComboBox1_Change()
    With Me
        LoadDependentCBO Me.ComboBox1, Me.ComboBox2
    End With
End Sub

Private Function ConvertValueToNamedRange(sValue As String, sConnector As String) As String
    'This function takes values in the combobox and converts them to named ranges
    'The spaces are replaced with whichever connector is supplied to the function
    'NOTE: I created a separate function even though this only uses a built-in function
    'in case more implementation code is needed

    ConvertValueToNamedRange = Replace(sValue, " ", sConnector)
End Function

Private Sub LoadDependentCBO(cboIndependent As ComboBox, cboDependent As ComboBox)
    'This code looks to see if there is a match between the value of the independent combobox
    'and a named range in the workbook. If not, the dependent combobox is set to be empty

    Dim sTemp As String
    Dim rNamedRange As Range

    sTemp = ""
    On Error Resume Next
        sTemp = Names.Item(ConvertValueToNamedRange(cboIndependent.Value, "_")).Name
    On Error GoTo 0

    If sTemp = "" Then
        'There is no matching named range so clear the dependent combobox
        cboDependent.Clear
    Else
        cboDependent.List = Range(sTemp).Value
    End If
End Sub

旧帖子: 代码ComboBox1.ListIndex = -1会将组合框设置为空(更改框的名称以适应)。这样做的逻辑取决于更多细节。如果您需要实施方面的帮助,请告诉我们。