如何让VBA让用户仅能在指定单元格或单元格区域中输入数字
时间:2023-02-27 18:40:38
通常,我们可以使用Excel的“数据验证”功能来设置指定单元格或单元格区域仅能输入指定范围的整数或者小数,如下图1所示。
图1
设置好后,仅能在单元格C2中输入介于1至100之间的整数,如下图2所示。
图2
其实,使用VBA也能够实现上述功能且更灵活和强大。例如,我们想要限定用户在单元格区域B2:D6中仅能输入数字。在VBE中,双击单元格区域所在的工作表模块,输入下面的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Application.EnableEvents = False
For Each rng In Target
‘限定程序执行在单元格区域B2:D6
If Not Application.Intersect(rng,Range(“B2:D6”)) Is Nothing Then
‘判断是否为数字
‘如果不是数字则清空
If Not IsNumeric(rng.Value) Then
rng.Value = vbNullString
End If
End If
Next rng
Application.EnableEvents = True
End Sub
这样,在该工作表单元格区域B2:D6中,如果输入的是非数字,则会自动清空。并且,这个单元格区域可以输入整数或小数。
标签:excel图表制作,excel常用函数,excel数据透视表,Excel教程
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何快速去除word文字下方的底纹
2023-02-25 22:53:48
![](https://img.aspxhome.com/file/2023/0/33510_0s.png)
word2003文档如何设置左右页码
2023-02-28 09:36:10
Excel中如何插入重音字母
2022-07-01 19:44:55
Win10安装directplay错误代码0x80070057怎么处理?
2022-08-05 23:23:50
![](https://img.aspxhome.com/file/2023/0/52980_0s.jpg)
word设置底纹填充颜色的方法步骤
2023-02-24 09:45:57
win7升级win10会不会卡
2023-11-11 11:39:32
![](https://img.aspxhome.com/file/2023/6/48606_0s.jpg)
如何利用Word2016制作日历形式值班安排表
2023-10-27 04:24:30
Photoshop如何为段落文本自动换行
2023-10-25 04:46:54
word 表格中合并单元格的定位、居中设置图解教程
2023-07-18 14:03:13
![](https://img.aspxhome.com/file/2023/4/32504_0s.jpg)
如何将Office2010文档转换为Office2003格式
2023-10-29 22:11:40
Win10兼容模式设置在哪?Win10兼容模式怎么设置?
2023-12-13 20:28:06
![](https://img.aspxhome.com/file/2023/6/51336_0s.jpg)
Word2010中表格怎样拆分单元格
2023-12-13 04:44:26
![](https://img.aspxhome.com/file/2023/4/21344_0s.jpg)
word无法撤销怎么解决
2022-01-15 12:12:28
![](https://img.aspxhome.com/file/2023/8/32618_0s.png)
Win10电脑怎么查看版本信息?
2022-10-05 10:42:51
![](https://img.aspxhome.com/file/2023/8/51708_0s.png)
Win10系统基础快捷键有哪些?Win10系统基础快捷键攻略
2023-05-17 22:40:26
![](https://img.aspxhome.com/file/2023/7/52557_0s.png)
excel2019表格中输入时间和日期的技巧
2022-11-08 13:06:20
![](https://img.aspxhome.com/file/2023/9/a140269_0s.jpg)
编号与文字间距怎么调?
2022-04-29 13:24:01
![](https://img.aspxhome.com/file/2023/0/34440_0s.gif)
解决Excel表格输入数字变成日期
2022-10-03 01:55:13
![](https://img.aspxhome.com/file/2023/6/37256_0s.jpg)
Word2013如何快速清除文档中所有的超链接且不影响文章格式
2023-09-01 23:49:32
![](https://img.aspxhome.com/file/2023/9/29219_0s.png)
Win10电脑蓝屏出现一堆英文怎么解决?Win10电脑蓝屏出现一堆英文解决教程
2023-11-04 01:35:56
![](https://img.aspxhome.com/file/2023/8/51838_0s.png)