You use the
Text
property to access the content of the
TextBox
control.
Even if you type a number, the
TextBox
control treats it like a string. VBA
automatically performs a conversion between a numeric variable and the
TextBox
control for you in many cases. For example,
the code in Listing 7-1
works just fine. (You can find the source code for this example on the
Dummies.com site at
http://www.dummies.com/go/vbafd5e
.)
Listing 7-1
Using the Text and Caption Properties
Private Sub btnTest_Click()
‘ Create the input variable.
Dim InputValue As Integer
‘ Tell VBA about the error handler.
On
Error GoTo NotANumber
‘ Get the string value and place it in the numeric
‘ variable.
InputValue = txtInput.Text
‘ Tell the user what they typed.
lblOutput.Caption = InputValue
‘ Exit the Sub.
Exit Sub
‘ Handle non-numeric input.
NotANumber:
MsgBox “You must type a number!”
End Sub
Figure 7-4:
Use a
standard
notation
for control
names.
162
Part II: Learning the Ropes
12_046500 ch07.qxp 12/5/06 5:35 PM Page 162
The example code places
the value contained in the
txtInput.Text
prop-
erty into
Input
. VBA performs the conversion automatically as long as the
user types a number. If you use this technique, always provide error handling,
as shown in the example code after the
NotANumber
label. Otherwise, if the
user types
something other than a number, the program displays an error
message.
The conversion process works in both directions. Notice that the
lblOutput.
Caption
property accepts
InputValue
as acceptable input. If you decide to
add
text to the output value, you still need to use the
CStr
function to con-
vert the number to a string. Otherwise, VBA displays a type mismatch error.
Executing tasks with command buttons
Command buttons are the main form of action. The default event (action) is
a click.
Whenever you click the button, it generates a special message known
as an
event.
See the later “Handling form events” section for details on events
and how they work.
Like the
Label
control, the
CommandButton
control has a
Caption
property
so that you can type text that appears on the button face when you start
the program.
In addition, you can use the
Accelerator
property to make
it easy to access the button by using an Alt+key combination. The example
in this section uses three command buttons to perform three different tasks.
Figure 7-5 shows the output of the example.
Listing 7-2 shows the code that you need to create this example. (You can
find the source code for this example on the Dummies.com site at
http://
www.dummies.com/go/vbafd5e
.)
Figure 7-5:
Command
buttons help
you
choose
actions to
perform
with your
program.
163
Do'stlaringiz bilan baham: