next up previous
Next: 7. TextBoxes and Labels Up: VisualBasic Previous: 5. IF/THEN/ELSE (and End)


6. Message Boxes

In the example in the previous section where the solution of a quadratic equation was calculated, we had to take care when we took the square root of a negative number. In cases like this, it may be convenient, or just more pretty, if the warning message appeared in a separate box, rather than in the main form itself.

In VisualBasic, the way of doing this is with the Message Box.

The Syntax for this is very simple:

MsgBox "Error - Imaginary Solution"

So the whole of the quadratic formula code would now look like:

Private Sub Command1_Click()
a = 1 ' Setting the values of the coefficients of the quadratic
b = 2
c = 8
If b^2 - 4 * a * c < 0 Then
   MsgBox "Error - Imaginary solution!"
Else
   x = ( -b + Sqr( b^2 - 4 * a * c ) ) / ( 2 * a )
   Print "x = "; x
End If
End Sub

Try the above code out to see how the Message Box works. You may find Message Boxes useful in the future when you code some more complex programmes.

You can make the output of Message Boxes more complex. Try replacing the MsgBox line in the programme above with:

   MsgBox "Error - Imaginary solution!" & vbNewLine & "b = " & Str(b) & " is too small"

You'll see that using the ampersand character & is a way of joining text together in the output of the Message Box. Note also that to output a number to a Message Box, you have to convert it to a string (or text) using the Str function. We'll talk more about this function very soon...

Message Boxes allow the programme to interact very usefully with the user. In particular they are useful to give warning messages, or to display the results of a calculation.


next up previous
Next: 7. TextBoxes and Labels Up: VisualBasic Previous: 5. IF/THEN/ELSE (and End)
Chris Allton 2006-10-27