在列表框中进行选择时更改文本框

时间:2016-03-02 17:10:13

标签: excel vba excel-vba

我有一个带有2个列表框和两个相应文本框的用户表单。当我在列表框中进行选择时,我希望其相应的文本框更新为具有相同的值。我已经安排了这样的函数来在我的用户表单中完成它:

Private Sub ListBox1_Click()
    TextBox1.Value = TopSelectedValue(ListBox1)
End Sub

Private Sub ListBox2_Click()
    TextBox2.Value = TopSelectedValue(ListBox2)
End Sub

Function TopSelectedValue(myBox As MSForms.ListBox) As String
    'Finds value of first selected item in ListBox
    Select Case myBox.MultiSelect
        Case fmMultiSelectSingle
            TopSelectedValue = myBox.Value
        Case fmMultiSelectMulti, fmMultiSelectExtended
            TopSelectedValue = myBox.List(TopSelectedIndex(myBox))
    End Select
End Function

Function TopSelectedIndex(myBox As MSForms.ListBox) As Integer  
    Dim k As Integer
    Select Case myBox.MultiSelect                        
        Case fmMultiSelectSingle                         
            TopSelectedIndex = myBox.ListIndex           
        Case fmMultiSelectMulti, fmMultiSelectExtended   
            For k = 0 To myBox.ListCount - 1             
                If myBox.Selected(k) = True Then         
                    TopSelectedIndex = k                 
                    Exit Function                        
                End If
            Next k
            TopSelectedIndex = -1                        
    End Select
End Function

注意:ListBox1是单选,ListBox2是多选。

问题是,ListBox1TextBox1更改时,ListBox1更新提示时,一切正常,但TextBox2ListBox2没有任何问题选择或更改。

我尝试通过添加此类代码以某种方式重置选择来修复它,但这也无法提供帮助:

Private Sub ListBox1_Click()
    TextBox1.Value = TopSelectedValue(ListBox1)
    Dim C As MSForms.Control
    For Each C In Me.Controls
        If TypeOf C Is MSForms.ListBox Then C.ListIndex = -1
    Next C
End Sub

为什么列表框/文本框关系的行为方式不同,我该怎么做才能解决这个问题?

0 个答案:

没有答案