VBA 运用LISTBOX插件,选择多个选项,并将选中的选项回车录入当前选中的单元格

发布于:2025-07-20 ⋅ 阅读:(11) ⋅ 点赞:(0)

维护好数据,并新增一个activeX列表框插件
在这里插入图片描述


Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.Count > 1 Then Exit Sub
    If Target.Row >= 2 And Target.Row <= 10 And Target.Column = 2 Then '选择操作范围
        With ListBox1
            .MultiSelect = 1 '多选模式
            .ListStyle = 1
            .List = ActiveSheet.Range("F1:F7").Value
            .Top = Target.Top
            .Left = Target.Left + Target.Width
            .Height = Target.Height * 5
            .Width = 90
            .Visible = True
        End With
    Else
        ListBox1.Clear
        ListBox1.Visible = False
    End If
End Sub

' 双击切换选中状态
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    Dim clickedIndex As Integer
    clickedIndex = ListBox1.ListIndex ' 获取双击的选项索引
    
    If clickedIndex >= 0 Then ' 确保双击的是有效选项
        ' 切换选中状态
        ListBox1.Selected(clickedIndex) = Not ListBox1.Selected(clickedIndex)
    End If
End Sub
 
' 回车键录入 Excel 单元格
Private Sub ListBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = vbKeyReturn Then
        Dim selectedItems As String
        Dim i As Integer
        
        selectedItems = ""
        '遍历选中的项目
        For i = 0 To ListBox1.ListCount - 1
            If ListBox1.Selected(i) Then
                If selectedItems = "" Then
                    selectedItems = ListBox1.List(i)
                Else
                    selectedItems = selectedItems & ", " & ListBox1.List(i)
                End If
            End If
        Next i
        ActiveCell.Value = selectedItems
    End If
End Sub

效果
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到