Module CheckTextbox<br /> '以下代碼控制TextBox控制項只能輸入數值型字串,具體內容如下:<br /> Public Sub CheckKeyPress(ByVal TargetTextBox As TextBox, ByVal e As System.Windows.Forms.KeyPressEventArgs, Optional ByVal Minus As Boolean = False, Optional ByVal DecimalCount As Integer = 0)<br /> Dim blnHandled As Boolean<br /> blnHandled = False<br /> Select Case Asc(e.KeyChar)<br /> Case Asc("-") ' 負號:只能在最前頭<br /> If Not (TargetTextBox.SelectionStart = 0 And Minus = True) Then blnHandled = True<br /> Case Asc(".") ' 小數點:小數位元大於0;在字串中沒有“.”,且加了“.”後小數位能滿足要求<br /> If DecimalCount <= 0 Then<br /> blnHandled = True<br /> Else<br /> If Not (InStr(TargetTextBox.Text, ".") = 0 And (Len(TargetTextBox.Text) - TargetTextBox.SelectionStart <= DecimalCount)) Then blnHandled = True<br /> End If<br /> Case 8 '退格鍵,<br /> Case 13 ' 斷行符號鍵<br /> SendKeys.Send("{TAB}") '轉為tab鍵<br /> Case Asc("0") To Asc("9") ' 0-9<br /> If InStr(TargetTextBox.Text, ".") > 0 Then<br /> If TargetTextBox.SelectionStart > InStr(TargetTextBox.Text, ".") - 1 Then<br /> ' 當前字元位置在小數點後,則小數點後的字元數必須小於小數位<br /> If Len(TargetTextBox.Text) - InStr(TargetTextBox.Text, ".") + 1 > DecimalCount Then blnHandled = True</p><p> End If<br /> End If<br /> Case Else<br /> blnHandled = True<br /> End Select<br /> e.Handled = blnHandled<br /> End Sub<br /> '調用如下:<br /> ' Private Sub txtJE_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtJE.KeyPress<br /> ' CheckKeyPress(sender, e, False, 0)<br /> ' End Sub<br />End Module