VBA Excel:将文本框的值限制在 60 到 100 之间

VBA Excel: Limit the textboxes to a value between 60 to 100

我正在尝试验证用户窗体中的文本框。我在我的工作表上使用这个

如何使用给定的解决方案向我的文本框添加验证以仅接受 60 到 100 之间的数字?我应该在 If KeyAscii >= 48 And KeyAscii <= 57 Then 之后添加一些东西还是应该在其他地方?

用户窗体:

Class代码:

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 事件,但遗憾的是,它在 class 中不可用。 我认为您需要为每个 textbox_AfterUpdate 创建一个存根来进行验证。

试试这个:

Private Sub tb_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Not IsNumeric(tb.Value) Then
        'MsgBox "only numbers between 60 and 100 are allowed"
        tb.Value = ""
    ElseIf tb.Value >= 60 And tb.Value <= 100 Then
        'MsgBox "OK!"
    Else
        'MsgBox "only numbers between 60 and 100 are allowed"
        tb.Value = ""
    End If
End Sub