2015-08-18 150 views
0

我正在使用具有多個文本框的用戶窗體。我想知道在移動到下一個文本框之前是否有強制用戶輸入最小值或更高的值的方法。將最小值設置爲文本框

非常感謝,

+0

看看TextBox1_KeyDown或Keypress事件。在這種情況下,您可以檢查另一個文本框的值,如果尚未設置,則保釋。 – MatthewD

回答

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」,並顯示無效數據(空白,小於最小值或非數字),則會顯示消息框。

相關問題