当前位置:   article > 正文

Excel做下拉框单选、多选功能(多选支持取消选择)_vba下拉单选

vba下拉单选

下拉框其实很简单,跟着我操作起来

一、单选框

Excel表格中选中数据-有效性-序列-选中数据来源-生成单选下拉框
来源可以框选也可以手动填写,手动填写多个值用英文逗号分隔即可
在这里插入图片描述
在这里插入图片描述
至此单选框已经可以用了我们来看看成果
在这里插入图片描述

二、多选

多选用到了 宏定义,文件格式也不能用xlsx 、xls ,必须要支持宏声明的文件格式 如xlsm ,不然会保存不上
在这里插入图片描述

在单选的基础上继续操作,打开VBA编辑界面

选择表格名称(比如sheet1),鼠标右击下面的工作表。选择“查看代码”,就可打开VBA编辑界面。
在这里插入图片描述

代码中 Target.Column = 6 把6替换成自己文件中下拉所在的列
如果有多列 可以用or 连接
Target.Column = 4 Or Target.Column = 5
代码如下

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
If Target.Count > 1 Then GoTo exitHandler

On Error Resume Next
Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
On Error GoTo exitHandler
If rngDV Is Nothing Then GoTo exitHandler
If Intersect(Target, rngDV) Is Nothing Then
'do nothing
Else
Application.EnableEvents = False
newVal = Target.Value
Application.Undo
oldVal = Target.Value
Target.Value = newVal
If Target.Column = 6 Then
If oldVal = "" Then
Else
If newVal = "" Then
Else
If InStr(oldVal, newVal) = 1 Then
If oldVal = newVal Then
Target.Value = ""
Else
Target.Value = Replace(oldVal, newVal & ",", "")
End If
Else
If InStr(oldVal, newVal) > 1 Then
Target.Value = Replace(oldVal, "," & newVal, "")
Else
Target.Value = oldVal & "," & newVal
End If
End If
End If
End If
End If
End If

exitHandler:
    Application.EnableEvents = True
End Sub

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

至此,大功告成!上述代码实现的功能是,

  1. 点击下拉选项时,选中的会加入到单元格中,多项用逗号分隔;
  2. 如果单元格中有A,再次选中A时,则会在单元格中删除A,达到了取消选择的效果
    在这里插入图片描述

温馨提示:
如果从服务器上下载的xlsm文件,会有警告,
1. 如果单个文件,右键该文档-属性,勾选“解除锁定” 即可
在这里插入图片描述
在这里插入图片描述
2. 如果从改网站下载的文件很多,可以使用如下方法
打开IE-Internet 选项-Internet 属性-安全-受信任的站点-网站,添加受信任的站点(Excel下载的源地址)
在这里插入图片描述

以上教程内容希望可以帮助大家解决Excel下拉框多选的问题,另外如果大家运行EXCEL代码中遇到问题,随时留言即可。

参考链接:
Excel函数运用
ExcelVBA字符串函数大全
解决Microsoft已经阻止宏运行,因为此文件的来源不受信任

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/513074
推荐阅读
相关标签
  

闽ICP备14008679号