我有一个带有特定TextBox的userform,我只想应用数字规则(没有字符串条目)。我在为此创建适当的错误处理程序时遇到困难。本质上,因为这些文本框将用于执行数学函数,具有字符串值会导致sub崩溃,我无法找出正确的语法来停止字符串条目。
我目前的代码是:
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代码,当我尝试输入字符串值时它会出错...
关于我如何以不同的方式进行任何想法?
答案 0 :(得分:1)
如果你真的需要在跑步中这样做,你可以这样做:
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