An InputBox example. Microsoft Excel VBA Programming
Pubblicità
Pubblicità
242
Part IV: Communicating with Your Users
Table 15-4
Argument
Prompt
Title
Default
InputBox Function Arguments
What It Means
The text displayed in the input box
The text displayed in the input box’s title bar
(optional)
The default value for the user’s input (optional)
An InputBox example
Here’s an example showing how you can use the InputBox function:
TheName = InputBox(“What is your name?”, “Greetings”)
When you execute this VBA statement, Excel displays the dialog box shown in Figure 15-5. Notice that this example uses only the first two arguments and does not supply a default value. When the user enters a value and clicks OK, the routine assigns the value to the variable TheName.
Figure 15-5:
The
InputBox function displays this dialog box.
The following example uses the third argument and provides a default value.
The default value is the username stored by Excel (the Application object’s
UserName property).
Sub GetName()
Dim DefName As String
Dim TheName As String
DefName = Application.UserName
TheName = InputBox(“What is your name?”, _
“Greetings”, DefName)
End Sub
The input box always displays a Cancel button. If the user clicks Cancel, the
InputBox function returns an empty string.
Chapter 15: Simple Dialog Boxes
243
VBA’s InputBox function always returns a string, so if you need to get a value, your code will need to do some additional checking. The following example uses the InputBox function to get a number. It uses the IsNumeric function to check whether the string is a number. If the string does contain a number, all is fine. If the user’s entry cannot be interpreted as a number, the code displays a message box.
Sub GetName2AddSheet()
Dim Prompt As String
Dim Caption As String
Dim DefValue As Integer
Dim NumSheets As String
Prompt = “How many sheets do you want to add?”
Caption = “Tell me...”
DefValue = 1
NumSheets = InputBox(Prompt, Caption, DefValue)
If NumSheets = “” Then Exit Sub ‘Canceled
If IsNumeric(NumSheets) Then
If NumSheets > 0 Then Sheets.Add Count:=NumSheets
Else
MsgBox “Invalid number”
End If
End Sub
Figure 15-6 shows the dialog box that this routine produces.
Figure 15-6:
Another example of using the
InputBox function.
The information presented in this section applies to VBA’s InputBox function.
In addition, you have access to the InputBox method, which is a method of the
Application object.
One big advantage of using the InputBox method is that your code can prompt for a range selection. The user can then select the range in the worksheet by highlighting the cells. Here’s a quick example that prompts the user to select a range:
Scarica
Pubblicità