excel - VBA Excel:将文本框限制为 60 到 100 之间的值
问题描述
我正在尝试验证用户窗体中的文本框。我在我的工作表上使用这个解决方案。
如何使用给定的解决方案向我的文本框添加验证以仅接受 60 到 100 之间的数字?我应该在之后添加一些东西If KeyAscii >= 48 And KeyAscii <= 57 Then
还是应该在其他地方?
用户窗体:
类代码:
Private WithEvents tb As MSForms.TextBox 'note the "WithEvents"
Sub Init(tbox As Object)
Set tb = tbox 'assigns the textbox to the "tb" global
End Sub
'Event handler works as in a form (you should get choices for "tb" in the
' drop-downs at the top of the class module)
Private Sub tb_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 48 And KeyAscii <= 57 Then
Debug.Print tb.Name, "number"
Else
MsgBox "The value should be in number only!", vbOKOnly + vbCritical, "Error"
Debug.Print tb.Name, "other"
KeyAscii = 0
End If
End Sub
用户窗体上的代码:
Private colTB As Collection 'holds your class instances
' and keeps them in scope
'This performs the setup
Private Sub UserForm_Activate()
Dim c As Object
Set colTB = New Collection
'loop all controls in the frame
For Each c In Me.Frame3.Controls
'look for text boxes
If TypeName(c) = "TextBox" Then
Debug.Print "setting up " & c.Name
colTB.Add TbHandler(c) ' create and store an instance of your class
End If
Next c
End Sub
' "factory" method
Private Function TbHandler(tb As Object) As clsTxt
Dim o As New clsTxt
o.Init tb
Set TbHandler = o
End Function
解决方案
我认为您无法使用 Class 轻松实现这一目标。您使用的解决方案将帮助您监控每次击键,但看起来您希望在用户完成该字段后验证输入,然后您需要验证他输入的内容是否在 60 到 100 之间。为此您可能正在查看 AfterUpdate 事件,但遗憾的是,该事件在课程中不可用。我认为您需要为每个 textbox_AfterUpdate 创建一个存根来进行验证。
推荐阅读
- awk - 如何在 gsub 中读取参数
- php - 如何使用 PHP 从 HTML 中提取表格
- sql - 触发器一直无法编译。表存在时未找到索赔表
- perl - perl hash ref return: { 'a' =>1, % { sub() } }
- android - Android:找不到符号变量错误
- linux - 创建 ssh 用户,始终登录文件夹
- android - 无法使用 Firebase 云消息向 Android 设备发送推送通知
- typescript - 当 myRecord 已经输入为 Record 时如何使用 `keyof typeof myRecord`
- dynamics-crm - 个人或公司拥有的 Dynamics CRM 实体
- java - Angular:具有多个参数的 HTTP POST 不起作用