You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Excel ListBox选中项填入TextBox并覆盖原有内容?

实现ListBox选中项填充TextBox的VBA方案

要实现选中ListBox中的选项后,将对应服务器名称填入TextBox并覆盖原有内容,只需为lstdisplay控件添加Click事件过程即可,具体操作如下:

  1. 在VBA编辑器中选中目标用户窗体,双击lstdisplay控件(ListBox),自动生成事件框架
  2. 填入以下事件代码:
Private Sub lstdisplay_Click()
    ' 跳过表头行(索引0),仅处理数据行
    If Me.lstdisplay.ListIndex > 0 Then
        ' 将选中行的第一列(Server Name)填入TextBox,覆盖原有内容
        Me.txtSearch = Me.lstdisplay.List(Me.lstdisplay.ListIndex, 0)
    End If
End Sub

完整代码示例(包含原有事件)

Private Sub txtSearch_Change()
    Me.txtSearch = Format(StrConv(Me.txtSearch, vbLowerCase))
    Dim sh As Worksheet
    Set sh = Sheets("Sheet1")

    Dim j As Long
    Dim x As Long
    Dim p As Long
    Me.lstdisplay.Clear
    ' 设置ListBox表头
    Me.lstdisplay.AddItem "Server Name"
    Me.lstdisplay.List(lstdisplay.ListCount - 1, 1) = "vCenter"
    Me.lstdisplay.List(lstdisplay.ListCount - 1, 2) = "IP Address"
    Me.lstdisplay.List(lstdisplay.ListCount - 1, 3) = "OS"
    Me.lstdisplay.List(lstdisplay.ListCount - 1, 4) = "HW Version"
    Me.lstdisplay.List(lstdisplay.ListCount - 1, 5) = "VCPU"
    Me.lstdisplay.List(lstdisplay.ListCount - 1, 6) = "Memory"
    Me.lstdisplay.List(lstdisplay.ListCount - 1, 7) = "Disk Space"

    Me.lstdisplay.Selected(0) = True

    For j = 1 To sh.Range("A" & Rows.Count).End(xlUp).Row
        For x = 1 To Len(sh.Cells(j, 1))  
            p = Me.txtSearch.TextLength
            If LCase(Mid(sh.Cells(j, 1), x, p)) = Me.txtSearch And Me.txtSearch <> "" Then
                With Me.lstdisplay
                    .AddItem sh.Cells(j, 1)
                    .List(lstdisplay.ListCount - 1, 1) = Sheet1.Cells(j, 13)
                    .List(lstdisplay.ListCount - 1, 2) = Sheet1.Cells(j, 7)
                    .List(lstdisplay.ListCount - 1, 3) = Sheet1.Cells(j, 9)
                    .List(lstdisplay.ListCount - 1, 4) = Sheet1.Cells(j, 8)
                    .List(lstdisplay.ListCount - 1, 5) = Sheet1.Cells(j, 3)
                    .List(lstdisplay.ListCount - 1, 6) = Sheet1.Cells(j, 4)
                    .List(lstdisplay.ListCount - 1, 7) = Sheet1.Cells(j, 5)
                End With
            End If
        Next x
    Next j
End Sub

Private Sub lstdisplay_Click()
    ' 跳过表头行(索引0),仅处理数据行
    If Me.lstdisplay.ListIndex > 0 Then
        ' 将选中行的第一列(Server Name)填入TextBox,覆盖原有内容
        Me.txtSearch = Me.lstdisplay.List(Me.lstdisplay.ListIndex, 0)
    End If
End Sub

说明

  • 判断ListIndex > 0是为了避免点击表头行时触发不必要的填充操作
  • lstdisplay.List(ListIndex, 0)获取选中行的第1列(索引从0开始)内容,即服务器名称
  • 填入TextBox时会自动覆盖原有内容,无需额外清除步骤

内容的提问来源于stack exchange,提问作者Earl Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:06:24