首页 > 解决方案 > 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

标签: excelvbatextbox

解决方案


我认为您无法使用 Class 轻松实现这一目标。您使用的解决方案将帮助您监控每次击键,但看起来您希望在用户完成该字段后验证输入,然后您需要验证他输入的内容是否在 60 到 100 之间。为此您可能正在查看 AfterUpdate 事件,但遗憾的是,该事件在课程中不可用。我认为您需要为每个 textbox_AfterUpdate 创建一个存根来进行验证。


推荐阅读