vba 下拉多选

方法一:有效性验证下拉多选

  • 建立下拉单选:https://jingyan.baidu.com/article/1876c85255d929890a13767d.html
  • 设置多选代码:
Sub Worksheet_Change(ByVal Target As Range)
    Dim xRng As Range
    Dim xValue1 As String
    Dim xValue2 As String

    ' 为了确保用户在Excel操作时只选中了单个单元格
    If Target.Count > 1 Then Exit Sub
    
    ' 当加上On Error Resume Next语句后,如果后面的程序出现"运行时错误"时,会继续运行,不中断。
    On Error Resume Next
    
    ' 定位含有验证条件的单元格
    Set xRng = Cells.SpecialCells(xlCellTypeAllValidation)
    
    If xRng Is Nothing Then Exit Sub
    
    Application.EnableEvents = False
    
    ' Intersect函数 返回两个或多个单元格重叠的部分 例子:Intersect(Range('a1:d5'), Range('c4:g9'))
    If Not Application.Intersect(Target, xRng) Is Nothing Then
        xValue2 = Target.Value
        ' 事件响应,假如工作表发生改变,Undo,撤销该表
        Application.Undo
        
        xValue1 = Target.Value
        
        Target.Value = xValue2
        
        If xValue1 <> "" Then
            If xValue2 <> "" Then
                ' InStr函数
                ' 第1个参数1代表从xValue1的第一个位置开始查找;
                ' 第2个参数 要搜索的字符串;
                ' 第3个参数 搜索到的字符串
                ' & 字符串连接符
                If xValue1 = xValue2 Or InStr(1, xValue1, "," & xValue2) Or InStr(1, xValue1, xValue2 & ",") Then
                    Target.Value = xValue1
                Else
                    Target.Value = xValue1 & "," & xValue2
                End If
            End If
        End If
    End If
    
    
    Application.EnableEvents = True
    
    
End Sub
注:上面的代码无法反选;
  • 参考1 https://blog.csdn.net/weixin_43564923/article/details/87193978 【亲测可用】(可以反选的代码)
  • 参考2 https://blog.csdn.net/T_amo/article/details/107039058 【亲测可用】

方法二:控件下拉多选

  • 参考1 https://itnoteshare.com/note/404/publicNoteDetail.htm 【亲测可用】

  • 参考2 https://zhuanlan.zhihu.com/p/55353022 【亲测可用】

  • 参考3 http://www.exceloffice.net/archives/3477 【亲测可用】

  • 20210625 下拉添加序号

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小镇学者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值