The following example assumes the use of
the text field's change event to trigger the calculations. This means that every time the data in any
input field involved in the calculation changes, the code for the calculation runs.
For this example, put three text boxes and a label on your
form, and put the following code in each of the input field's change
events.
Private Sub Text1_Change()
TheAnswer = Text1 + Text2 + Text3
lblOut.Caption = CStr(TheAnswer)
End Sub
Now try typing some values into the input fields. It
works ok until
you try something like typing in a decimal only value, starting with the
decimal as the first character typed into one of the fields, or hit the
wrong key and enter a text character instead of a numerical digit. How
do we fix this?
Simple, just add an error trap and clear the error in
the error handling
routine. Rewrite the change event code blocks for each of the text
fields to look like the following one, and give it a try.
Private Sub Text1_Change()
On Error GoTo Clear
TheAnswer = Text1 + Text2 + Text3
lblOut.Caption = CStr(TheAnswer)
Exit Sub
Clear:
On Error GoTo 0
Resume Next
End Sub
Now if the attempt to calculate raises an error, it is
cleared by the On Error GoTo 0 in the error handling routine, and the Resume Next
causes execution of your program to continue with the code after the statement
which caused the error. The assignment of the value of the
calculation's result is the next statement in this case.
The preceding example code assumes the use of a Public
variable TheAnswer explicitly declared in the declarations section of the form the text
boxes are on. For purposes of this example, declare it to be be of type
Double.
|