只允许文本框中输入数字值。

8

我想制作一个文本框控件,只能接受数字值。

在VB6中,我该怎么做?

13个回答

9

右键点击控制框 > 组件 > 控件 -> 微软掩码编辑控件 6.0。
或者使用普通文本框:

Private Sub Text1_Validate(Cancel As Boolean)
 Cancel = Not IsNumeric(Text1.Text)

End Sub

7
在文本框的“更改”事件中,检查输入的值是否为数字。如果不是数字,则将旧值设置回去。
Dim textval As String
Dim numval As String

Private Sub TextBox1_Change()
  textval = TextBox1.Text
  If IsNumeric(textval) Then
    numval = textval
  Else
    TextBox1.Text = CStr(numval)
  End If
End Sub

最好使用验证事件。 - pinichi
这要看情况。如果您希望仅在用户离开文本框控件并尝试将焦点设置到其他位置时触发验证已输入数字的验证,则应使用“Validate”事件。如果您选择这条路线,则只有在出现错误或通知时才会提供错误或通知。另一方面,如果您使用“Change”事件,用户将立即收到他们输入的非数字值无效的通知。 - Cody Gray

4
我通常使用这段代码:
Private Sub text1_KeyPress(KeyAscii As Integer)
    If Not IsNumeric(text1.Text & Chr(KeyAscii)) And Not KeyAscii = 8 Then KeyAscii = 0
End Sub

2

我让API为我完成它。我将这个函数添加到.bas模块中,并为需要设置为数字的任何编辑控件调用它。

Option Explicit

Private Const ES_NUMBER = &H2000&
Private Const GWL_STYLE = (-16)
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long


'set an editbox to numeric only - return the previous
'style on success or zero on error
Public Function ForceNumeric(ByVal EditControlhWnd As Long) As Long
    Dim lngCurStyle As Long
    Dim lngReturn As Long

    lngCurStyle = GetWindowLong(EditControlhWnd, GWL_STYLE)
    If lngCurStyle <> 0 Then
        lngReturn = SetWindowLong(EditControlhWnd, GWL_STYLE, lngCurStyle Or ES_NUMBER)
    End If

    ForceNumeric = lngReturn

End Function

要使用它,请使用文本框的句柄调用该函数。

Private Sub Form_Load()
    Dim lngResult As Long

    lngResult = ForceNumeric(Text1.hwnd)

End Sub

这虽然有它的问题。但你可以通过 (1) Ctrl-V,(2) Shift-Insert 和 (3) 文本框上下文菜单将任何非数字文本复制并粘贴到控件中。只有 (1) 可以通过 VB6 的 KeyPress 处理。 - user1889116
@Herb,你说得对,但是在VB中防止粘贴无效值到文本框的唯一方法是捕获系统消息。这是可能的,但在VB6中做起来很丑陋。这只能防止输入非数字值。如果我需要确保我的数据完整性,我会在使用它进行处理之前检查文本是否有效。同时,我让用户更难输入无效数据。在.Net中,我将此与监视WM_PASTE(我想是这个)消息流并在允许粘贴之前检查信息相结合。 - jac

2

我通常使用这段代码:

Private Sub text1_KeyPress(KeyAscii As Integer)
    If Not IsNumeric(Chr(KeyAscii)) And Not KeyAscii = 8 Then
        KeyAscii = 0
    End If
End Sub

希望这可以帮到您。

1
我在我的项目中使用了这段代码:

Private Sub txtReceiptID_KeyPress(KeyAscii As Integer)
Dim Keychar As String
If KeyAscii > 31 Then
    Keychar = Chr(KeyAscii)
    If Not IsNumeric(Keychar) Then
        KeyAscii = 0
    End If
End If

End Sub


1

1

以下内容可用于整数:

Private Sub text1_KeyPress(KeyAscii As Integer)
    If Not IsNumeric(text1.Text & Chr(KeyAscii)) And Not KeyAscii = 8 Then    KeyAscii = 0
    if (KeyAscii>=43) and (KeyAscii<=46) Then KeyAscii = 0 
    'it ignores '-', '+', '.' and ','
End Sub

0

只需选择控件和keyPress方法,IDE就会为您创建下一个方法。然后在方法内添加下一个代码即可。
Private Sub txtControl_KeyPress(KeyAscii As Integer)
   KeyAscii = RealKeyascii(txtControl, KeyAscii, 256 ^ 8)
End Sub

您是否想为您的代码回答添加一些解释?这将有助于打破 StackOverflow 是免费代码编写服务的误解。 - Yunnosch

0

只需编写简单的1行代码 在文本中更改 Text1.text1=val(text1.text)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接