Novice code question

wekurn
09-17-2002, 09:54 AM
This week I am studying input boxes. I have a form with a text box, a command button and a label for the sum to be displayed.
Here is the code:

Private Sub Command1_Click()
Dim first As Single
Dim last As Single
Dim result As Single
first = Text1.Text
last = InputBox("Insert a value", "Value insertion")
result = first + last
Label1.Caption = result
End Sub

Private Sub Form_Load()
Text1.Text = ""
End Sub

I can get the text box and input box to add the values, but if I enter nothing, or press "cancel", I get the "type mismatch" error.
Where am I going wrong here?
Are errors handled later in the code? Is that what is meant by "error handling"

Iceplug
09-17-2002, 09:58 AM
The InputBox returns a String.
You have last as a Single.
You will have to surround your InputBox with CSng(...) or Val(...)
CSng converts to a Single
and Val is the "generic" string to number convertor.

I suggest using Val(...) as it returns zero for an empty string.

wekurn
09-17-2002, 10:36 AM
Like this?:

last = CSng(InputBox("Insert a value", "Value insertion"))

It's still returning an error when the cancel button is pressed.

I have changed the code to this:

Private Sub Form_Load()
Text1.Text = "0"
End Sub

Private Sub Command1_Click()
Dim first As Single
Dim last As Single
Dim result As Single
If Text1.Text = "" Then
MsgBox ("sorry, try again")
End If
last = CSng(InputBox("Insert a value", "Value insertion", "0"))
first = Text1.Text
result = first + last
Label1.Caption = result
End Sub

This has cured the "type mismatch" error when the text box and input boxes are left null, but still the cancel button returns the mismatch error. I'm wondering if I'm beginning to create code that fixes code that fixes code that...

THANKS ICEPLUG!!!

BK

iowahawk43
09-17-2002, 10:59 AM
Or after your INPUT line, check for a valid valid before causing an error in your math!

If IsNumeric(Last) then
continue math
End if

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum