使用 VBA Excel 同时添加到列表框和从组合框中删除

问题描述 投票:0回答:1

我想修改 ListBox 和 ComboBox 中的列表,使它们相互依赖。

在 Combo 中选择一个项目应将该项目添加到 ListBox。
该项目必须从组合中删除。
反之亦然 - 从列表框中删除应添加到组合列表中。

Private Sub ComboBox1_Change()
    With ComboBox1
        If .ListCount > 0 Then
            ListBox1.AddItem (.ListIndex) ' <<< it works
            .RemoveItem (ComboBox1.ListIndex)' <<< doesn't work
        End If
    End With
End Sub

Private Sub ListBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 46 Then ' <<< DEL key
        With Me.ListBox1
            If .ListIndex > 0 Then 'first item is unremovable
                ComboBox1.AddItem .List(.ListIndex)'<<<doesn't work
                .RemoveItem (.ListIndex)' <<<works
            End If
        End With
    End If
End Sub
excel vba combobox listbox
1个回答
0
投票

出现错误时点击“调试”按钮,然后将鼠标悬停在

ComboBox1.ListIndex
上,即可看到问题。值-1表示没有选择值。

将代码从

ComboBox_Change
事件移至
ComboBox1_Click
事件。然后您的
ComboBox1.ListIndex
将获得正确的值。

© www.soinside.com 2019 - 2024. All rights reserved.