比如我做一个表格,其中一项是“部门类型”,这一项中,选项有:财务部,人事部,开发部,销售部
用户在选择的时候,可以选择:人事部,开发部
那么在“部门类型”这个单元格中,应该显示:人事部,开发部
怎么用excel实现呢?
1. 首先做一个下拉框
2. 然后点击当前下拉框下的sheet页签,右键选择查看代码
输入以下代码
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 = newValIf Target.Column = 7 Then '这里规定好哪一列的数据有效性是多选的,A列是第1列,依次类推,如3就是C列,7就是G列If oldVal = "" Then'do nothingElseIf newVal = "" Then'do nothingElseIf InStr(1, oldVal, newVal) <> 0 Then '重复选择视同删除If InStr(1, oldVal, newVal) + Len(newVal) - 1 = Len(oldVal) Then '最后一个选项重复Target.Value = Left(oldVal, Len(oldVal) - Len(newVal) - 1)ElseTarget.Value = Replace(oldVal, newVal & ",", "") '不是最后一个选项重复的时候处理逗号End IfElse '不是重复选项就视同增加选项Target.Value = oldVal & "," & newVal'NOTE: you can use a line break,'instead of a comma'Target.Value = oldVal _' & Chr(10) & newValEnd IfEnd IfEnd IfEnd IfEnd IfexitHandler:Application.EnableEvents = TrueEnd Sub
注意第21行,其中If Target.Column = 7
表示下拉框所在的列数,如1表示A第一列,2表示B第二列,以此类推。
3. 最后测试
所有的多选项都会用逗号隔开,再次选择已选项会取消选择。