【问题标题】:Setting minimum value to a textbox将最小值设置为文本框
【发布时间】:2015-11-11 23:02:30
【问题描述】:

我正在使用带有多个文本框的用户表单。我想知道是否有一种方法可以强制用户在移动到下一个文本框之前输入最小值或更高的值。

非常感谢,

【问题讨论】:

  • 查看 TextBox1_KeyDown 或 Keypress 事件。在这种情况下,您可以检查其他文本框的值,如果尚未设置则保释。

标签: excel textbox minimum vba


【解决方案1】:

假设您的文本框之一被命名为TextBox1,您可以将此代码放在您的用户表单中:

Option Explicit

Dim blnClosing As Boolean

Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

        If blnClosing = False Then

                Dim iVal As Integer
                Dim minVal As Integer

                minVal = 10 'Change to your needs

                'Test for numeric characters
                On Error Resume Next
                iVal = CInt(Me.TextBox1.Value)

                'If characters are not numeric
                If Err.Number = 13 Then
                        MsgBox "Value must be numeric!", vbCritical, "Incorrect Value"
                        Me.TextBox1.Text = vbNullString
                        Cancel = True 'Retain focus on the textbox
                        Exit Sub
                End If

                'Reset error handling to normal
                On Error GoTo 0

                'Check if textbox value is less than the minimum
                If Me.TextBox1.Value < minVal Then
                        MsgBox "Value must be greater than " & minVal & "", vbCritical, "Incorrect Value"
                        Me.TextBox1.Value = vbNullString
                        Cancel = True 'Retain focus on the textbox
                End If
        End If
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
        blnClosing = True
End Sub

我也冒昧地检查了一个数值,因为您在询问文本框中的值是否需要为数字。如果不是这种情况,请从 'Test for numeric characters 注释中删除代码行到 On ErrorGoTo 0 行。

全局变量blnClosing 允许我们在表单关闭时跳过代码。如果这不包括在内,并且用户在表单的右上角按下了带有无效数据(空白、小于最小值或非数字)的“X”,则会显示消息框。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多