用户表单validation

我有一个用户窗体与特定的文本框,我只想应用数字规则(没有string条目)。 我在创build适当的error handling程序方面遇到困难。 从本质上讲,因为这些文本框将被用来执行一个math函数,具有string值导致潜艇崩溃,我不能找出正确的语法来停止string条目。

我目前的代码是:

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 

我已经尝试了将另一个子文件从string值中去除,但是我继续得到一个跟踪到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代码,当我尝试inputstring值时出错…

有关我如何以不同的方式去思考的想法?

如果你真的需要这样做,你可以这样做:

 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