Excel下拉列表值多选,用到宏代码

第一步:首先设置列的下拉框值
第二步:下拉框值设定
第三步:打开VBA编辑界面,选择表格名称(比如),鼠标右击下面的工作表 。选择“查看代码”,就可打开VBA编辑界面 。
步骤3:输入代码-生成下拉框多选

Excel下拉列表值多选,用到宏代码

文章插图
在下图中,5 Then代表的意思为 “第五列”,修改为目标列数即可 。
比如下述案例选中的那行,下拉框在第五列,则改为5 Then即可
往下看有图文代码合集(可复制直接使用)
Private Sub Worksheet_Change(ByVal Target As Range)Dim rngDV As RangeDim oldVal As StringDim newVal As StringIf Target.Count > 1 Then GoTo exitHandlerOn Error Resume NextSet rngDV = Cells.SpecialCells(xlCellTypeAllValidation)On Error GoTo exitHandlerIf rngDV Is Nothing Then GoTo exitHandlerIf Intersect(Target, rngDV) Is Nothing Then'do nothingElseApplication.EnableEvents = FalsenewVal = Target.ValueApplication.UndooldVal = Target.ValueTarget.Value = http://www.kingceram.com/post/newValIf Target.Column = 5 ThenIf oldVal ="" ThenElseIf newVal = "" ThenElseTarget.Value = http://www.kingceram.com/post/oldVal &", " & newValEnd IfEnd IfEnd IfEnd IfexitHandler:Application.EnableEvents = TrueEnd Sub
到了这一步已经设置完成了,可以正常使用 。
Excel下拉列表值多选,用到宏代码

文章插图
题外话:如果出现报错,代表excel表类型不正确选择 【否】然后重新选择文件类型未xlsm类型文件,重新打开xlsm文件就可以啦!
另外,如果像设置为多选框值不可重复的话,需要修改下列部分代码黄框里面直接复制修改,主要改动在箭头处,因为有if -else闭环整个复制代码也贴出来了:
整部分代码复制:
【Excel下拉列表值多选,用到宏代码】Private Sub Worksheet_Change(ByVal Target As Range)Dim rngDV As RangeDim oldVal As StringDim newVal As StringIf Target.Count > 1 Then GoTo exitHandlerOn Error Resume NextSet rngDV = Cells.SpecialCells(xlCellTypeAllValidation)On Error GoTo exitHandlerIf rngDV Is Nothing Then GoTo exitHandlerIf Intersect(Target, rngDV) Is Nothing Then'do nothingElseApplication.EnableEvents = FalsenewVal = Target.ValueApplication.UndooldVal = Target.ValueTarget.Value = http://www.kingceram.com/post/newValIf Target.Column = 5 ThenIf oldVal ="" ThenElseIf newVal = "" ThenElseIf InStr(oldVal, newVal) > 0 ThenTarget.Value = oldValElseTarget.Value = http://www.kingceram.com/post/oldVal &", " & newValEnd IfEnd IfEnd IfEnd IfEnd IfexitHandler:Application.EnableEvents = TrueEnd Sub
完成!