我正在使用带有多个文本框的用户窗体。我想知道在移动到下一个文本框之前是否有一种强制用户输入最小值或更高值的方法。
非常感谢,
答案 0 :(得分:0)
假设您的一个文本框名为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”并且包含无效数据(空白,小于最小值或非数字),则会显示消息框。