excel利用VBA生成无重复无空值的数据有效性下拉列表
时间:2023-05-11 08:28:50
在Excel工作表的某个单元格中应用数据有效性设置来制作下拉列表时,如果引用的行或列区域中包含空单元格或重复项,那么在有效性下拉列表中会与原区域中的内容完全相同,也会包含空值或重复项,显得有些不够美观。例如下图是A1单元格的一个下拉列表。
通常可以去掉重复项和空单元格后再设置数据有效性,但如果不想改变单元格的结构,可以使用下面的VBA代码来解决这个问题,假如要设置下拉列表的单元格为D5,数据区域为K8:K38,步骤如下:
1.按Alt+F11,打开VBA编辑器。
2.在“工程”窗口中双击要包含数据有效性设置的工作表,在右侧代码窗口中输入下列代码:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim RowNum, ListRows, ListStartRow, ListColumn As Integer
Dim TheList As String
Dim Repeated As Boolean
If Target.Address <> "$D$5" Then Exit Sub
With Range("k8:K38")
ListRows = .Rows.Count
ListStartRow = .Row
ListColumn = .Column
End With
For RowNum = 0 To ListRows - 1
Repeated = False
If Not IsEmpty(Cells(ListStartRow + RowNum, ListColumn)) Then
For i = 0 To RowNum - 1
If Cells(ListStartRow + RowNum, ListColumn) = Cells(ListStartRow + i, ListColumn) Then
Repeated = True
Exit For
End If
Next i
If Not Repeated Then TheList = TheList & Cells(ListStartRow + RowNum, ListColumn) & ","
End If
Next RowNum
TheList = Left(TheList, Len(TheList) - 1)
With Range("D5").Validation
.Delete
.Add _
Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=TheList
End With
End Sub
3.关闭VBA编辑器返回Excel界面,选择D5单元格,单击下拉箭头即可看到不包含空值和无重复的下拉列表。
说明:上述代码使用了工作表的SelectionChange事件,当在工作表中重新选择单元格后会执行上述代码。需根据实际将代码中的单元格“D5”和区域“k8:K38”进行更改。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
搜狗输入法如何拼音纠错
![](https://img.aspxhome.com/file/2023/5/a318366_0s.jpg)
WPS应用技巧—如何批量更改错别字
在Word2007文档中编辑超链接的步骤
![](https://img.aspxhome.com/file/2023/8/30048_0s.jpg)
电脑中的Local Service是什么意思?
![](https://img.aspxhome.com/file/2023/6/a322569_0s.jpg)
PS新手教程-如何使用PS制作抖音风格图片
![](https://img.aspxhome.com/file/2023/10/a343960_0s.jpeg)
解决win7不能在同一窗口打开多个文件夹的方法
![](https://img.aspxhome.com/file/2023/29/a252749_0s.jpg)
Win7电脑中利用命令提示符拷贝硬盘数据图文教程
![](https://img.aspxhome.com/file/2023/28/a247538_0s.jpg)
Win10专业版安装不了战网客户端怎么办?
![](https://img.aspxhome.com/file/2023/1/a278058_0s.jpg)
Win11电脑系统设置用户权限的方法
![](https://img.aspxhome.com/file/2023/29/a261961_0s.jpg)
Win10应用商店更新不了软件怎么办?应用商店更新不了软件的解决方法
![](https://img.aspxhome.com/file/2023/25/a217869_0s.png)
以太网默认网关不可用_以太网默认网关不可用解决方法
![](https://img.aspxhome.com/file/2023/4/a307411_0s.jpg)
Camtasia Studio如何消除视频中杂音?Camtasia Studio消除视频中杂音的方法
![](https://img.aspxhome.com/file/2023/8/a333353_0s.jpg)
Excel隔行插入连续日期的方法
![](https://img.aspxhome.com/file/2023/3/a142823_0s.jpg)
fastcopy使用方法
![](https://img.aspxhome.com/file/2023/1/a281800_0s.png)
Win10显示器颜色异常怎么办 系统屏幕色彩不正常的解决办法
![](https://img.aspxhome.com/file/2023/2/a291775_0s.jpg)
Win10系统怎么开启系统自带的录屏功能?
![](https://img.aspxhome.com/file/2023/1/a279372_0s.jpg)
区块链核心技术体系架构的网络层主要包括什么
Excel 2019 如何求解二元一次方程图解
![](https://img.aspxhome.com/file/2023/0/a140960_0s.jpg)
觅食APP怎么添加美食?觅食APP添加美食的方法
![](https://img.aspxhome.com/file/2023/8/a335892_0s.jpg)