组合框/列表框
选择列表框内容自动复制至文本框
2017-07-03 17:15:30

有网友问到如何把列表框上的内容选择后自动添加到文本框。然后我可以通过文本框的值去做其他处理

首选我们得做一个可以多选列表框的效果。在把选择的标题付给文本框。如下图所示:

详细代码:

Public Function strAllinList(ctlName As ListBox, Optional intField As Integer = 0, Optional chrSplit As String = ",") As String

        '返回多选listBox 第 intFiels 列的值,用 但引号和逗号分隔,未选则返回 "''"

    Dim sltRow

    strAllinList = ""   '初始化为空字符串

    For Each sltRow In ctlName.ItemsSelected    '循环处理每一个选中的行

        strAllinList = strAllinList & chrSplit & "'" & ctlName.Column(intField, sltRow) & "'"

            '得到 该行 指定 列的值,并分隔起来

    Next

    If Len(strAllinList) >= 1 Then  '对于空值进行处理

        strAllinList = Right(strAllinList, Len(strAllinList) - 1)

    Else

        strAllinList = "''"

    End If

End Function

Public Sub showMultiSelected(ctlListBox As ListBox, ctlTextBox As TextBox)

'从窗体文本框的值来控制多选列表框的选定值,

'文本的各项目用('')包含  例如 :  '1''5' 或者 '1','5'

'相关: strAllInList()

    Dim lstItem As Integer

    Dim inpos As Integer

    

    For lstItem = 0 To ctlListBox.ListCount - 1

        If IsNull(ctlTextBox.value) Or IsNull(ctlListBox.value) Then    '处理空值

            inpos = 0

        Else

            inpos = InStr(1, ctlTextBox.value, "'" & ctlListBox.ItemData(lstItem) & "'")

                '判断列表框该行的值 是否包含在文本值中。

Debug.Print ctlListBox.ItemData(lstItem), ctlTextBox.value, inpos

        End If

        If inpos = 0 Then   '如果该行的值 是否包含在文本中,显示为选择状态

            ctlListBox.Selected(lstItem) = False

        Else

            ctlListBox.Selected(lstItem) = True

        End If

    Next

End Sub