用户表单输入验证

Userform entry validation

我有一个带有特定文本框的用户窗体,我只想应用数字规则(无字符串条目)。我很难为此创建足够的错误处理程序。本质上,因为这些文本框将用于执行数学函数,所以具有字符串值会导致 subs 崩溃,我无法找出在字符串条目处停止的正确语法。

我当前的代码是:

Private Sub TextBox12_Change()
    Sumdatup
End Sub

Private Sub TextBox16_Change()
Sumdatup
End Sub

Private Sub TextBox21_Change()
Sumdatup
End Sub

Private Sub Sumdatup()
Dim Total As Double
Total = 0
If Len(TextBox12.Value) > 0 Then Total = Total + CDbl(TextBox12.Value)
If Len(TextBox16.Value) > 0 Then Total = Total + CDbl(TextBox16.Value)
If Len(TextBox21.Value) > 0 Then Total = Total + CDbl(TextBox21.Value)
' Add more for the rest of your text boxes
TextBox26.Value = Total
End Sub

我曾尝试合并另一个 sub 来阻止字符串值通过,但我继续得到一个错误,可以追溯到 Sumdatup 程序中的第一个 If 子句。

这是我尝试过但出现错误的方法:

Private Sub TextBox12_Change()
NumbersOnly
Sumdatup
End Sub

Private Sub TextBox16_Change()
NumbersOnly
Sumdatup
End Sub

Private Sub TextBox21_Change()
NumbersOnly
Sumdatup
End Sub

Private Sub NumbersOnly()

If TypeName(Me.ActiveControl) = "TextBox" Then
With Me.ActiveControl
If Not IsNumeric(.Value) And .Value <> vbNullString Then
MsgBox "Only numeric values allowed."
.Value = vbNullString

End If
End With
End If
End Sub

Private Sub Sumdatup()
Dim Total As Double
Total = 0
If Len(TextBox12.Value) > 0 Then Total = Total + CDbl(TextBox12.Value)
If Len(TextBox16.Value) > 0 Then Total = Total + CDbl(TextBox16.Value)
If Len(TextBox21.Value) > 0 Then Total = Total + CDbl(TextBox21.Value)
' Add more for the rest of your text boxes
TextBox26.Value = Total
End Sub

该代码似乎从不检查 NumbersOnly 子程序,而是直接转到 Sumdatup 代码,当我尝试输入字符串值时出错...

关于我如何以不同的方式进行此操作有什么想法吗?

如果你真的需要在运行上做,你可以这样做:

Private Sub TextBox12_Change()
  If chkNum Then Sumdatup
  If IsNumeric(TextBox12.Value) Then TextBox12.BackColor = 16777215 Else TextBox12.BackColor = 255
End Sub

Private Sub TextBox16_Change()
  If chkNum Then Sumdatup
  If IsNumeric(TextBox16.Value) Then TextBox16.BackColor = 16777215 Else TextBox16.BackColor = 255
End Sub

Private Sub TextBox21_Change()
  If chkNum Then Sumdatup
  If IsNumeric(TextBox21.Value) Then TextBox21.BackColor = 16777215 Else TextBox21.BackColor = 255
End Sub

Private Function chkNum() As Boolean
  If IsNumeric(TextBox12.Value) And IsNumeric(TextBox16.Value) And IsNumeric(TextBox21.Value) Then
    chkNum = (Len(TextBox12.Value) * Len(TextBox16.Value) * Len(TextBox21.Value)) > 0
  End If
End Function

Private Sub Sumdatup()
  TextBox26.Value = TextBox12.Value + TextBox16.Value + TextBox21.Value
End Sub