Sei sulla pagina 1di 13

Online PC Learning

(http://www.onlinepclearning.com

VBA for Beginners: VBA Input Box


Examples

(http://www.onlinepclearning.com/vba-beginners-vba-input-box-examples/)

 Chapter 10: Understanding the Input


Box Construct
Contents [show]

OVERVIEW.
1. Syntax
2. Input Function
3. Input Method
4. Type argument
5. A Simple Input Box
6. VBA Examples
7. Create a User Login
1. Example 1 Add a name
2. Example 2 Create a login
3. Example 3 Create a login dynamic
4. Example 4 Login with 3 attempts (Download)
8. Collect employee age
1. Example 1 Age list
2. Example 2 Age calculator (Download)
9. BMI Calculator
1. Example    Basic BMI Calculator (Download)
10. Working with Ranges
1. Example    Dynamic print area

Decision making tool – Number 4


We can let the end users of our applications interact with the data flow with
Input Boxes. They are quick, effective and easy to construct and modify.
Putting this function into your box of tricks will add greater flexibility to your
work

We can let the end users of our applications interact with the data flow with
Input Boxes. They are quick, effective and easy to construct and modify.
Putting this function into your box of tricks will add greater flexibility to your
work

Open the resource file


Open the resource file that came with this eBook and navigate to the Input Box
worksheet. This will enable you to test each of these examples.

(http://www.onlinepclearning.com/wp-content
/uploads/2013/10/resourse-Input.png)

VBA Input Box Video Overview

VBA for Beginners - VBA Input Box

Why use an Input Box


We can gather some information from our users with the message box
function. However there are times when we want to collect more detailed
information. To accomplish this task we can use the InputBox function. As you
will see in this chapter we can collect information from a spreadsheet or
gather details for processing directly from our user with the use of the VBA
Input Box Function. We can allow the user to enter data in the form of text,
numbers or even a formula by using an InputBox function.

Syntax
Let’s have a look at the syntax.

Open the VBA editor by holding down the ALT key and press F11. On the insert
tab choose Insert module. Type in Sub Test and hit the enter key.

Then type any single word followed by an equal sign. Type InputBox(

The syntax will then be available as shown below. The Microsoft table below
explains each parameter. You will notice that the Prompt is mandatory and is
inserted between double quotes.
You will rarely use [Xpos] (4) and [Ypos] (5) which are the left and top positions
for the Input box. Helpfile  (6) and ContextID (7) are seldom used.

Prompt (1), Title (2), Default (3) and Type (8) are the parameters we will use
the most.

(http://www.onlinepclearning.com/wp-content/uploads/2013/10/input-box-
syntax.png)

expression .InputBox(Prompt, Title, Default, Left, Top, HelpFile,


HelpContextID, Type)
The expression is a variable that represents an Application object. In the Input
Box above it is the variable Var=

Input Function
The input box function will allow the user to enter a value into the input box;
however the data is always coerced to text and would return a string value.

Input Method
If we add the word application before the InputBox syntax we turn the Function
into a Method. Option Type (8) now appears. This will allow us to set the data
type for the input box. No other type will be allowed. Below is a list of type
values and their respective meanings.

Type argument

Type 8 refers to the range object and there are 2 options.

1.       If we want a cell reference, then we must use the Set keyword to show    
we are referring to the cell object.

2.       If we omit this, the value in the range will be returned.

Set myRange = Application.InputBox(prompt := "Sample", type := 8)

So if you do not use the Set statement, the variable is set to the value in the
range, rather than the Range object itself.

Set myRange= Application.InputBox =Cell or range address


myRange= Application.InputBox =Value in cell

That is the theory behind the Input Box. Now  we will look at some practical
examples.

A Simple Input Box


This InputBox will display a simple dialog box into which information can be
added. You will be presented with an OK button and a Cancel button. If OK is
chosen then the value entered is returned. If Cancel is clicked then False is
returned.

Sub InputSimple()

'Input variable

ShowBox = InputBox("Type Your first name", "Add Name", "Type name


here")

End Sub
VBA Examples
I have added the four examples below to help with the understanding of the
InputBox function and Method. After these four examples I have included four
small practical projects that I think you will find very helpful.

You will also be able to download two workbooks containing three of the
projects.

1. A user login
2. An age calculator
3. The BMI calculator
4. Print area range tool

Create a User Login


I have added four examples for a user login. Each example builds on the
previous with the last example developing a small login application.

Creating a user login with the Input box is relatively easy. We can use the Input
box Function in order to accomplish this. In the example below we are adding
the value of the Input box into the active sheet range A1.

       Example 1    Add a name


Notice in this example that we are using the Prompt, Title and Default
parameters of our syntax.

Sub InputName()

'Declare the variable

Dim AddName As String

'Input variable

AddName = InputBox("Type Your first name", "Add Name", "Type name


here")

'Add name to the worksheet

Range("A1").Value = AddName

End Sub

Example 2            Create a login


We can extend the flexibility of this simple login by adding the user name and
in the next column adding the date and time that the login occurred. All those
who login are recorded.

In this example we are adding a variable that finds the next available row to
into which we will add our data.

Sub Login()

'Declare the variables

Dim AddData As Range


Dim AddName As String

'Copy location

Set AddData = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)

'Input variable

AddName = InputBox("Type Your first name", "Add Name")

'Check for a value

If AddName = Empty Then Exit Sub

'Add data to the worksheet

AddData.Value = AddName

AddData.Offset(0, 1).Value = Now

End Sub

Example 3            Create a login dynamic


Let us take this one step further by adding a Select Case statement that
requires that the user uses a passcode to be able to login. If the user fails to
select the right pass code then a message box is sent telling them that they
are not authorised to login to the workbook.

With this login code we need to add the names of those allowed to login
directly into the VBA procedure. In this instance it is, Trevor, Harry and Mary.

Sub Login2()

'Declare the variables

Dim AddData As Range

Dim AddName As String

'Copy location

Set AddData = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)

'Input variable

AddName = InputBox("Type Your first name", "Add Name")

'Check for a value

If AddName = Empty Then Exit Sub

'Check for the right name

Select Case AddName

Case "Trevor"

AddData.Value = AddName

AddData.Offset(0, 1).Value = Now

MsgBox "Welcome: – " & AddName

Case "Harry"

AddData.Value = AddName

AddData.Offset(0, 1).Value = Now

MsgBox "Welcome: – " & AddName

Case "Mary"
AddData.Value = AddName

AddData.Offset(0, 1).Value = Now

MsgBox "Welcome: – " & AddName

Case Else

MsgBox "Name not authorised"

End Select

End Sub

            Example 4     VBA Input Box Login with 3


attempts
Watch this brief video to show how this works

Excel VBA Input Login Box

Here is a practical example of all of the features we have just mentioned plus
extending the flexibility by allowing the number of users to login to be as many
as we require.

To do this we loop through the range of valid users and compare this with the
value that is typed into the Input box.

This illustration shows how the worksheet should be structured. In practice


you would not put the list of users where they could be visible. In fact all of
this information should really be hidden.

If the wrong password is added three times, the workbook will close and not
be saved.

Note:
Be careful if you edit this code because it is possible to create a procedure
that cannot be exited.
Sub LoginCheck()

'Declare the variables

Dim AddData As Range, Check As Range

Dim Nme As String

'Count attempts

Set Check = Sheet1.Range("E2")

'Destination location

Set AddData = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)

'Input variable

Nme = Application.InputBox("Add your login code name:- You have 3


attempts", Type:=2)

'Variable for authorise

Auth = 0

'Loop through range of names

For Each cName In Sheet1.Range("D2:D14")

If cName.Text = Nme Then

AddData.Value = Nme

AddData.Offset(0, 1).Value = Now

MsgBox "Welcome: – " & Nme

Auth = 1

Exit For

End If

Next cName

'Not authorised after 3 attempts and close workbook

If Auth = 0 Then

If Check.Value = 3 Then ActiveWorkbook.Close False

MsgBox "You are not authorised"

Check.Value = Check.Value + 1

'Call macro again

LoginCheck

End If

End Sub
Collect employee age
            Example 1     Age list
In this example we are just simply collecting the age of the employee and
adding it to a list on the worksheet. The ages are added one after the other in
column five.

Sub InputAge()

'Declare the variable

Dim AddAge As Long

'Input variable

AddAge = InputBox("Type Your Age", "Add Age", "Type your age")

'Copy location

Cells(Rows.Count, 5).End(xlUp).Offset(1, 0) = AddAge

End Sub

            Example 2     Age calculator  (Input Method)


Let’s use the
Import box
method once
again, this time to
calculate the age
of an individual
based on the date
of birth entered
into the Input box.
The Type will now
appear as a
parameter. In this
procedure we are
setting the Type
to (1). This
restricts the entry
into the Input box
to a number.
Dates are
numbers!  If the user enters text it will be rejected.

You will notice that we do all of the calculations on the worksheet and return
the calculated value to the user in a message box at the end of the procedure.

You will find this in the resource file.

Note:

A formula needs to be added to cell G8 to calculate the age.


G8 formula   =If(F8="","",DATEDIf(F8,TODAY(),"Y")&" Years,
"&DATEDIf(F8,TODAY(),"YM")&" Months, "&DATEDIf(F8,TODAY(),"MD")&" Days")

The result will appear in the message box. Notice we are adding this cell
values to the message box content.

Sub InputAge()

'Declare the variables


Dim AddAge As Long

Dim mMyAge As Range

'Set the the result range

Set MyAge = Sheet1.Range("G8")

'Variable for input box

AddAge = Application.InputBox("Type Your Age", "Add Age", "Type your


date of birth", Type:=1)

'Check for value

If IsNumeric(AddAge) And AddAge <> 0 Then

'Add date of birth to worksheet

Sheet1.Range("F8") = AddAge

'Show formula result in a message box

MsgBox "Your age is:-   " & MyAge

End If

End Sub

BMI Calculator
Example:  Basic BMI Calculator (Input Method)
Two input boxes
are called one
after the other
and the data is
stored on the
worksheet.

In this example
we are using the
Input box Method
by inserting
Application
before the
keyword
InputBox. The
data type that we
have chosen is
(1) indicating that
we are limiting
this to numbers only. We show two input boxes one after the other to collect
the Height and then the Weight which is necessary to calculate our BMI.

Height is added to F8 and Weight is added to G8 on the worksheet.

A formula is added to cell H8 to calculate the BMI for us. This is stored as a
variable and shown in the message box result.

H8 formula     =G8/((F8/100)*(F8/100))

Sub BMI_Calculator()

'Declare the variables


Dim Height As Long

Dim Weight As Long

Dim BMI As Range

'Variable for result

Set BMI = Sheet2.Range("H8")

'Input variable for height

Height = Application.InputBox("Add your height in centermetres:",


Type:=1)

'Check for value and add value

If IsNumeric(Height) And Height <> 0 Then

Sheet2.Range("F8") = Height

Else

MsgBox "You must add a Height"

Exit Sub

End If

'Input variable for weight

Weight = Application.InputBox("Add your weight in kilograms:", Type:=1)

'Check for value and add value

If IsNumeric(Weight) And Weight <> 0 Then

Sheet2.Range("G8") = Weight

Else

MsgBox "You must add a Height"

Exit Sub

End If

'Show the BMI result in a message box

MsgBox "Your BMI is:   " & Format(BMI, "#,##0.0")

End Sub

BMI = (Weight in Pounds / (Height in inches x Height in inches)) x 703

BMI = (Weight in Kilograms / (Height in Meters x Height in Meters))

A healthy BMI for an adult is between 20 and 25.

Working with Ranges (Input Method for


Objects)
This is our final working example. You will find this piece of code very useful in
setting up a variable print area and then opening the print dialogue box to
enable the user to print that selected piece of the worksheet.

Note:
Type (8) is used for the data type. A cell reference as a range object>

       Example:      Dynamic print area

Sub InputPrint()
'Declare the variable

Dim PrintArea As Range

'Set error handler

On Error Resume Next

'Input variable

Set PrintArea = Application.InputBox("Select the area to print", "Print


area", "Scroll over print area", Type:=8)

'Check for value

If PrintArea Is Nothing Then Exit Sub

'Set the print area

ActiveSheet.PageSetup.PrintArea = PrintArea.Address

'Show the print dialog box

Application.Dialogs(xlDialogPrint).Show

'Reset error handler

On Error GoTo 0

End Sub

Conclusion
The Input box function and the Input box Method are awesome tools for
collecting data from a user and then using that in our calculations and
decisions in our applications. It presents us with the opportunity to very allow
the user to interact with the processes we have set.

We have now discussed the four decision modelling tools at our disposal.

The functions are:

1. If function
2. Select Case function
3. Message box function
4. Input box function and method.

With these functions we can help the end user to make effective decisions as
they use our applications.

Related
Comments are closed.

Potrebbero piacerti anche