الطريقة الأولى بأستخدام الحدث KeyPress ونلاحظ أيضا أنه يقبل أدخال الفارزة " . "
Private Sub Text1_KeyPress(KeyAscii As Integer)
' Only allow one occurrence of the period
If KeyAscii = 46 And InStr(Text1, ".") > 0 Then
KeyAscii = 0
Exit Sub
' Now carry out numerals and period check
ElseIf (KeyAscii < 48 Or KeyAscii > 57) And KeyAscii <> 46 Then
KeyAscii = 0
End If
End Sub
الطريقة الثانية باسخدام دوال API
' *** Declares
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" _
(ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias _
"SetWindowLongA" _
(ByVal hwnd As Long, ByVal nIndex As Long, _
ByVal dwNewLong As Long) As Long
'Used for forcing only numbers in a text box
Private Const GWL_STYLE = (-16)
Private Const ES_NUMBER = &H2000&
Private Sub TextBox_Numeric(ByRef txtNumeric As TextBox, ByVal bNumericOnly As Boolean)
Dim lReturn As Long
Dim lStyle As Long
lStyle = GetWindowLong(txtNumeric.hwnd, GWL_STYLE)
' Check if current style is present and bNumericOnly
If ((lStyle And ES_NUMBER) > 0) Xor bNumericOnly Then
' Style is opposed to bNumericOnly, reverse current style setting
lStyle = lStyle Xor ES_NUMBER
lReturn = SetWindowLong(txtNumeric.hwnd, GWL_STYLE, lStyle)
End If
End Sub
ويمكن استخدام هذا الكود مع حقل نص واحد أو عدد من حقول النص، وادناه أستخدم مع حقل نص واحد وهو Text1
Private Sub Form_Load()
Call TextBox_Numeric(Text1, True)
End Sub