39
Version 1.0 Writing Macros and Programs in VBA This guide introduces the main features of Excel 2016 to create macros and manipulate VBA code to produce user input forms.

ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

  • Upload
    buiphuc

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Version 1.0

Writing Macros and Programs in VBAThis guide introduces the main features of Excel 2016 to create macros and manipulate VBA code to produce user input forms.

Page 2: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Document code: Title: Writing Macros and Programs in VBA Using Excel 2016Version: 1.0Date: 02/08/2016Produced by: University of Durham

Page 3: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Copyright © 2016 University of Durham

Conventions:

In this document, the following conventions are used:

A typewriter font is used for what you see on the screen. A bold typewriter font is used to represent the actual characters you type at the Keyboard. A slanted typewriter font is used for items such as filenames which you should replace with

particular instances. A bold font is used to indicate named keys on the keyboard, for example, Esc and Enter,

represent the keys marked Esc and Enter, respectively. A bold font is also used where a technical term or command name is used in the text. Where two keys are separated by a forward slash (as in Ctrl/B, for example), press and hold

down the first key (Ctrl), tap the second (B), and then release the first key

Page 4: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Contents1 Introduction.........................................................................................................12 Creating a Macro in Excel 2016.........................................................................2

2.1 The Developer Ribbon....................................................................................22.2 Using Excel’s Built-in Macro Recorder...........................................................3

2.2.1 Start the Macro Recorder......................................................................32.2.2 Name the Macro....................................................................................32.2.3 Carry out the Macro Steps.....................................................................32.2.4 Stop Recording......................................................................................42.2.5 Assign the Macro to a Button................................................................42.2.6 Test the Macro.......................................................................................4

2.3 Exercise 1.......................................................................................................4

3 Viewing the Code................................................................................................53.1 The Visual Basic Editor..................................................................................53.2 Understanding the MakeMeRed VBA Code...................................................63.3 Exercise 2.......................................................................................................6

4 Creating a New Subroutine................................................................................74.1 To Add a New Subroutine..............................................................................74.2 InputBox command.........................................................................................84.3 MsgBox command..........................................................................................84.4 Variables.........................................................................................................94.5 Data Types.....................................................................................................94.6 Concatenation................................................................................................94.7 Exercise 3.......................................................................................................94.8 Commenting your code................................................................................10

5 Using IF Statements.........................................................................................115.1 Simple IF Statements...................................................................................115.2 A more complex IF statement containing a calculation................................115.3 Using If to Create a Quiz..............................................................................125.4 Exercise 4.....................................................................................................13

6 Loops.................................................................................................................146.1 Creating a For…Next Loop...........................................................................146.2 Using a Counter............................................................................................146.3 Creating a Loop with a Calculation...............................................................156.4 Using Constants in a Program......................................................................156.5 Putting a Title on your Input Box..................................................................166.6 Exercise 5.....................................................................................................166.7 Using the Case statement............................................................................176.8 Exercise 6.....................................................................................................18

7 Creating a User Form.......................................................................................197.1 Setting up the form.......................................................................................197.2 Adding names to the User Form...................................................................21

7.2.1 Naming Controls..................................................................................217.2.2 Caption Property..................................................................................22

7.3 Attaching code to the User Form..................................................................237.3.1 Initialize command...............................................................................23

7.4 Test the Userform.........................................................................................247.5 Further Exercise 1........................................................................................257.6 Further Exercise 2........................................................................................25

Page 5: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

1 IntroductionVisual Basic for Applications (VBA) is the programming language which sits behind the macro functionality of Microsoft Excel 2016. Macros can be recorded within Excel 2016 or can be writing in the VBA language. This booklet will show who VBA can be manipulated to create macros and other functionality within Excel. The main elements covered include:

Excel’s built in macro recorder Viewing and manipulating code in the Visual Basic Editor Creating subroutines Using IF statements Creating loops User forms

VBA and Macros in Excel 2016 1

Page 6: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

2 Creating a Macro in Excel 2016The best way to start learning VBA (Visual Basic for Applications) is to record a macro. This generally means creating a set of steps by selecting normal Excel menu choices and button clicks. The steps recorded are saved as a simple VBA program which can be viewed and edited.

In the example below a simple macro will be created which will allow a selected cell to be coloured red. Macros are usually attached to a button on the Excel worksheet.

2.1 The Developer RibbonThe macro and VBA options are on the Developer ribbon. This should already be visible on the ribbon, if not, select File, Options, Customize Ribbon.

Check Developer and then click on OK. The Developer ribbon will appear at the right-hand side of the ribbon.

All Macro and VBA commands can be found in the Code group on the Developer ribbon:

VBA and Macros in Excel 2016 2

Page 7: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

2.2 Using Excel’s Built-in Macro RecorderIn order to write a VBA program (or Macro), it is important to understand the basic constructs of the language. The best way to learn this is by recording a macro and then viewing the code generated.

2.2.1 Start the Macro RecorderSelect any cell, go to the Developer Ribbon and click on the Record Macro button.

2.2.2 Name the MacroSpecify a name for the macro. For this exercise name the macro MakeMeRed. There must be no spaces or special characters in the name (except underscores).

Click OK when done.

A small blue square will be displayed next to the Ready indicator at the bottom left-hand corner of the screen.

This indicates that Excel is recording and every action carried out will be stored in the macro. The Record Macro button on the ribbon has changed and now says Stop Recording.

2.2.3 Carry out the Macro StepsFill the current cell with any shade of red from the palette.

VBA and Macros in Excel 2016 3

Page 8: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

2.2.4 Stop RecordingOnce the steps in the macro are recorded press Stop recording or click on the white Recording button at the bottom left of the worksheet.

2.2.5 Assign the Macro to a ButtonInsert a shape or button on the worksheet. Right-click the button and select Edit Text. Add the following text to the button, Select any cell and click to colour it red:

Right-click on the rectangle shape and select Assign Macro. Select the MakeMeRed macro from the list shown.

Click OK.

2.2.6 Test the Macro Select any cell on the worksheet and click on the button. The cell will be filled with red. Click another cell and the same thing should happen.

2.3 Exercise 1 Record a macro called BlueFillPinkBorder which formats a cell to match the

description. Add a button and assign the macro to the button. Test the macro works.

VBA and Macros in Excel 2016 4

Page 9: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

3 Viewing the CodeNow that the first macro is working, it’s time to have a look at the code generated when the macro was created.

3.1 The Visual Basic EditorTo view the code generated, right click on the current sheet name (bottom left) and click on View Code option. Pressing ALT+F11 does the same. This opens the Visual Basic Editor (VBE). The Visual Basic Editor will look like this:

To open up the macro to see what it looks like, double-click on Module1 in the list to the left-hand side of the window. This list is called the Project Explorer and Module1 is the name of the Module which stores all the macros in the current workbook. The macros will be displayed on the screen with a line between each one.

VBA and Macros in Excel 2016 5

Page 10: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

3.2 Understanding the MakeMeRed VBA CodeExamine the code one line at a time. This will help to make sense of the commands:

Sub MakeMeRed(): This line tells Excel that a new set of instructions is to follow. The word Sub indicates that the following lines of VBA are a sub-procedure (or sub-routine). Which generally means, a group of related instructions meant to be followed together to do something meaningful. The Sub-procedure ends when Excel sees the phrase “End Sub”

Lines starting with a single quote (‘): These lines are made available for you to add comments. Excel will ignore anything written after a single quote. These are meant to aid understanding by anyone who needs to work with the macros.

With Selection.Interior: While filling a cell with red colour may seem like one step it is in fact a lot of steps for Excel. Whenever an operations needs to be repeated on the same thing (in this case, selected cell), Excel puts them all together. This is where the With statement comes in. The statement With Selection.Interior means that all following operations are going to be performed on the interior of the selected cell until there is an End With line.

Lines starting with full stop (.): These are the lines that tell Excel to format the cell’s interior. In this case, the most important line is .Color = 255 which is telling Excel to fill the cell with a red colour.

End With: This marks the end of the With block.

End Sub: This marks the end of the macro named MakeMeRed().

3.3 Exercise 2A good way of becoming more familiar with the code at the beginning, is to experiment with changing some of the lines of code:

Change .color = 255 to .color = 62

Change .Pattern = xlPatternVertical

Change .TintAndShade = 0.5

Run the macro to see the result.

VBA and Macros in Excel 2016 6

Page 11: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

4 Creating a New SubroutineWhen the macro is recorded, Excel automatically creates a subroutine, giving it the name you used to create the macro. If you actually want to create the subroutine using VBA, it is easier to keep all the subroutines within the same Module. If Module1 is not currently open, open it.

4.1 To Add a New SubroutineMake sure the cursor is on the blank line underneath the MakeMeRed macro and type Sub Hello. A line has been added to the screen creating space for your new subroutine.

Sub MakeMeRed()'' MakeMeRed Macro' With Selection.Interior .Pattern = xlPatternVertical .PatternColorIndex = xlAutomatic .Color = 255 .TintAndShade = 0.5 .PatternTintAndShade = 0 End WithEnd SubSub hello()

End sub

The program must be typed between the Sub and the End Sub. Type the following, exactly as displayed on the picture below:

Sub hello()MsgBox (“Hello”)End sub

The command MsgBox is used to display a box on the screen which says Hello.

To try the program out, click on - the Run button. A box will be displayed on the screen which looks like this:

VBA and Macros in Excel 2016 7

Page 12: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

4.2 InputBox commandIt is possible, using VBA to create an InputBox which will ask for some data and then put that data into a specified cell in the worksheet.

The code is held in Modules. Notice that the code already entered is in Module 1. The modules hold procedures which are identifiable by the Sub and End Sub which surrounds the code. Modules can be referenced by Excel worksheets. To add a new module, click on Insert and then Module. Module 2 will appear at the bottom of the list.

Once Module 2 has been created in the current workbook, type in the following code:

Sub DataEntry()Range(“A2”) = InputBox(“Enter Number”)End Sub

4.3 MsgBox commandThe MsgBox command displays a message on the screen. The InputBox command allows the user to enter data in a box which is displayed on the screen. The MsgBox shows Output and InputBox takes in Input. Using the InputBox command is more complicated than MsgBox , first Variables must be Declared.

Type the following subroutine example into Module1 underneath the Hello Subroutine.

Sub hello()MsgBox (“Hello”)

End subSub firstname()Dim firstname As String

firstname = InputBox(“Enter your name.”)MsgBox “Hello “ + firstname

End Sub

It is worth noting at this point that there are some words which VBA does not allow in the naming of subroutines – these are “reserved” words and include:

name, first, last, date, time, now

Spaces and punctuation are also not allowed in naming subroutines.

VBA and Macros in Excel 2016 8

Page 13: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

4.4 VariablesIn order to use InputBox (and many other program commands) the variables that are going to use in the program must be declared. This needs to be done at the top of the program. Variables can be thought of like empty boxes which are waiting for data. In this example, a variable called firstname is declared into which whatever is typed into the input box will be placed. Dim is used to tell VBA that a variable is being declared. Dim actually stands for Dimension.

4.5 Data TypesWhen variables are declared, VBA must be told what type of variable to expect. The following 3 data types are the most common:

String This is a text variable and will hold a number of characters.Char This is a text variable and will hold a single character.Single Numbers with no decimalsDouble Numbers with decimals

4.6 ConcatenationNow enter this program and try it out:

Sub fullname()

Dim firstname As StringDim lastname As String

firstname = InputBox(“Enter your first name.”)lastname = InputBox(“Enter your last name.”)

MsgBox “Hello “ & firstname + “ “ + lastname

End Sub

You will notice the last line of the program looks like this:

MsgBox "Hello " & firstname + " " + lastname

This will actually display a message box which will display Hello followed by a space followed by firstname followed by another space, followed by lastname.

This is achieved through Concatenation. This simply means adding several strings of data together to create one string.

There are two methods of concatenation – as you can see in the example, you can use the & sign or the + sign. You can use either for text, but the + sign can also be used to add numbers together. It would therefore be good practice to use the & for concatenation and + for addition to ensure that they meaning is clear.

4.7 Exercise 3Now try creating another subroutine which will ask for two numbers and then add them together and display the answer with a message. Remember to use the correct data type.

VBA and Macros in Excel 2016 9

Page 14: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

4.8 Commenting your codeIt is good practice to add comments to your program, so that you can remember what it does later – also if someone else is going to work with your program, comments are useful to them. To add comments to your code you need to enter the comment on a new line (for comments applying to a whole program) or on the same line of the program. All comments need to have the ‘ symbol in front of them. The comment will be displayed in green on the screen.

Sub fullname()Dim firstname As StringDim lastname As String

‘Asks for firstname and lastname and then displays message

firstname = InputBox(“Enter your first name.”)lastname = InputBox(Enter your last name.”)

MsgBox “Hello “ & firstname + “ “ + lastname

End Sub

Try adding some comments to your program.

VBA and Macros in Excel 2016 10

Page 15: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

5 Using IF StatementsOne of the most useful things in any programming language is to enable conditional processing – this means only performing certain actions if particular conditions are met.

If you are using Excel as a spreadsheet it is possible to create an =IF statement within a worksheet. Using VBA it is possible to control program flow using if.

5.1 Simple IF StatementsTry out the example below:

Sub results()

Dim Module1 As Single

Module1 = InputBox(“Enter Results for Module 1”)

If Module1 > 50 ThenMsgBox “Pass”ElseMsgBox “Fail”

End If

End Sub

Try creating this program. Remember to indent the commands within the statement, so that it is clear.

5.2 A more complex IF statement containing a calculationThe following example would allow you to enter results for 3 modules and add them together:

Sub results1()

Dim Module1 As SingleDim Module2 As SingleDim Module3 As Single

Module1 = InputBox(“Enter results for Module 1.”)Module2 = InputBox(“Enter results for Module 2.”)Module3 = InputBox(“Enter results for Module 3.”)

MsgBox “Total is “ & Module1 + Module2 + Module3

End Sub

A further modification to this program would allow you to work out whether the students have passed or failed. In order to do this, you need to include an If statement. You also need to be able to work out the Average. To calculate the Average, you need to be able to use a command called WorksheetFunction.

VBA and Macros in Excel 2016 11

Page 16: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Try this example.

Sub results2()Dim Module1 As SingleDim Module2 As SingleDim Module3 As Single

Module1 = InputBox(“Enter results for Module 1”)Module2 = InputBox(“Enter results for Module 2”)Module3 = InputBox(“Enter results for Module 3”)

If WorksheetFunction.Average(Module1, Module2, Module3) > 50 ThenMsgBox “Pass”ElseMsgBox “Fail”

End If

End Sub

5.3 Using If to Create a QuizYou are now going to use your knowledge of If statements to create a quiz with 5 questions. A correct answer will have a score of 1 and an incorrect answer will have a score of 0. Therefore, the maximum score will be 5. There will be only 1 correct answer for each question. This example will get you started.

Sub quiz()Dim answer1 As StringDim score1 As SingleDim answer2 As StringDim score2 As Single

answer1 = InputBox(“What is the capital of England?”)

If answer1 = “london” Or answer1 = “London” Thenscore1 = 1Elsescore1 = 0

End If

answer2 = InputBox(“What is the best university in England?”)

If answer2 = “durham” Thenscore2 = 1Elsescore2 = 0

End If

MsgBox score1 + score2

End Sub

VBA and Macros in Excel 2016 12

Page 17: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Notice that question 2 only has one viable option, typing in Durham will not score as the option for Durham with an uppercase ‘D’ is not present.

Using this example, the message at the end will just appear as a number. If you want the message to contain text as well – for example:

Your score is 5

You will need to change the MsgBox command. This will involve Concatenation (see section 6.2 below).

5.4 Exercise 4Correct question 2 so that both ‘Durham’ and ‘durham’ will be accepted.

Now add 3 more questions to the quiz – don’t forget to change the final calculation for the score.

VBA and Macros in Excel 2016 13

Page 18: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

6 Loops

6.1 Creating a For…Next LoopThe purpose of a loop, is to allow the program to run a certain number of times before stopping. This is called Iteration. The following example runs 5 times and puts a number in a cell each time:

Sub TestLoop()

Dim Loop1 As Double

For Loop1 = 1 To 5Cells(Loop1, 9) = InputBox(“Enter Number”)

Next Loop1

MsgBox “You have entered 5 numbers”

End Sub

Cells (Loop1, 9) refers to the column in the worksheet where the numbers will appear. Column 9 is actually Column I in the worksheet, because it is the 9th column.

6.2 Using a CounterIt is often the case that you need to examine the numbers that you have entered. For example, you might want to find out how many of the numbers you entered were greater than 5. To do this, you need to add a counter to your program:

Sub LoopWithCounter()

Dim Loop1 As DoubleDim Counter As Single

Counter = 0

For Loop1 = 1 To 5Cells(Loop1, 10) = InputBox(“Enter Number”)

If Cells(Loop1, 10) > 5 ThenCounter = Counter + 1End If

Next Loop1

MsgBox “You have entered “ & Counter & “ numbers greater than 5.”

End Sub

This is called a Count-Controlled Loop.

Notice that you need to set the Counter to 0 before you start.

VBA and Macros in Excel 2016 14

Page 19: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

6.3 Creating a Loop with a CalculationIt is possible to build a calculation into a loop – for example, we could incorporate a VAT calculation which could be carried out every time a number is entered. Try this example:

Sub VatCalculation()

Dim Price As Double

For Price = 1 to 5Cells(Price, 5) = InputBox(“Enter Number”) * 1.2

Next Price

End Sub

Remember to check the worksheet to see the output as there is no MsgBox command.

6.4 Using Constants in a ProgramEnter the following program in a new workbook and then run it, making sure you enter .2 when prompted to Enter VAT. This is a simple program, which will allow you to enter a Price and then enter a VAT rate, multiply them together and then produce the result.

Sub VAT()

Dim Price As DoubleDim VATRate As Double

Price = InputBox(“Enter Price”)VATRate = InputBox(“Enter VAT”)MsgBox Price * VATRate

End Sub

This program should work, but it is rather pointless, as VAT is a fixed amount of 20% (or .2) which should not need to be entered each time you run the program. In order to make VBA always use 20% as the VAT percentage, you can create a Constant called VAT and assign a value to it. This means that you do not have to enter the value every time you perform the calculation. Create a new sub called VAT2() typing in the code below and then run it again.

Sub VAT2()

Dim Price as DoubleConst VATRate = 0.2

Price = InputBox(“Enter Price”)MsgBox Price * VATRate

End Sub

VBA and Macros in Excel 2016 15

Page 20: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

6.5 Putting a Title on your Input BoxWe are now used to creating an Input box with a prompt. In the VAT example, the line used to display the InputBox is:

Price = InputBox("Enter Price")

This Input box which appears looks like this:

If you change the InputBox Statement so that it looks like this:

Sub VAT2()

Dim Price as DoubleConst VATRate = 0.2

Price = InputBox(“Enter Price”, “Price Entry Box”)MsgBox Price * VATRate

End Sub

You will see that you have added a title to your box, so that it looks like this:

6.6 Exercise 5Create a new sub called VAT3() .

Add a new Variable called Quantity to your program.

Add a new InputBox so that you can enter the quantity.

Change the message box so that it includes this variable, and calculates the price multiplied by the quantity plus the VAT. As the output is to be the total cost plus VAT you may need to alter one of the variables or constants.

Use the following data to check:

Quantity = 20, Price = £10 should give you a total of £240

VBA and Macros in Excel 2016 16

Page 21: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

6.7 Using the Case statementWe have used the If statement in several programs now. As we have seen the If statement gives us the ability to select between True and False answers. This is very useful, but sometimes does not go far enough. We used If to see if a student had passed or failed, given the results of three modules. However, if we wanted to give grades, depending on these results, this would be difficult to do using If. For example:

Mark GradeLess than 40 E

Between 40 and 49 D

Between 50 and 59 C

Between 60 and 69 B

70 or over A

We could probably carry this out by using an If statement, but it would be confusing. It would be better to use another type of statement – this is called Case. Try this example of the Case Statement:

Sub Grades()Dim Marks As Single, Grade As String

Marks = InputBox(“Enter Marks”, “Marks Entry”)

Select Case MarksCase Is < 40

Grade = “E”Case 40 to 49

Grade = “D”Case 50 to 59

Grade = “C”Case 60 to 69

Grade = “B”Case Is >= 70

Grade = “A”End SelectMsgBox “Your Grade is “ & grade

End Sub

You will notice that the variable declaration here is done all on one line – this is another way of doing it and is correct.

VBA and Macros in Excel 2016 17

Page 22: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

6.8 Exercise 6You are the manager of a Sports club. You offer a range of membership fees, depending on the age of the members. The three bands of fee are:

Type of Membership Age Range PriceJunior Under 16 £100

Adult Between 16 and 64 £200

Senior 65 and Over £150

Write a program, using Case to work out the price of a membership, once the Age has been entered. You do not need to include Type of Membership – this is just for explanation.

VBA and Macros in Excel 2016 18

Page 23: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

7 Creating a User FormIt is sometimes necessary to use VBA to collect and process data through a form. This example will enable you to try this out.

We are going to create a form which will allow us to collect some data and display it on a worksheet. The information is concerned with an office dinner. Staff will complete a form, allowing them to enter their name and phone number plus their choice of Restaurant and whether or not they have a car. The completed form will look like this:

7.1 Setting up the formOpen up a new workbook and immediately View Code.

Select Insert, UserForm from the VBA menu:

You now have a blank form which has, by default been named UserForm1 and also the Toolbox which will help you to place Controls on the form.

The Toolbox contains a variety of Controls. In this exercise you will not use all of them, but you will gain a good understanding of how they work.

In order to place a control on the form, you need to drag it onto the form, from the Toolbox.

VBA and Macros in Excel 2016 19

Page 24: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

The Controls you will need for this exercise are as follows:

Try and set up your form, using this guide to help you:

LabelsThese can be named properly later.

Text Boxes

Combo BoxOption Buttons

Command Buttons

We now need to add some code to make the example work. The first thing to do is to put a command button on your worksheet so that the Form will open. To do this, go to Sheet 1 of your worksheet and take the following steps:

Click on the Developer ribbon. You should notice the Controls group. Click on Insert within that group and you should see the following set of buttons these are in a different order to those on the Visual Basic Editor:

Click on the first one, which is the Button Control and then use the mouse to draw a button on your worksheet. The following dialog box will appear:

VBA and Macros in Excel 2016 20

Combo BoxText Box

Label

Option Button

Command Button

Page 25: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

The button has automatically been named as Button1 and therefore the associated program will be called Button1_Click. You could change this, but for the moment it is easier to leave it. Click on New.

You will be taken into the Visual Basic Editor with an empty program to complete.

Sub Button1_Click()

End Sub

Add a command to this program, as follows:

Sub Button1_Click()UserForm1.Show

End Sub

Clicking on this button will now show the user form. The next step is to modify your form and add some code so it will work.

7.2 Adding names to the User Form

7.2.1 Naming ControlsIn order to refer to your controls in programs, it is useful to give them useful names. In order to do this ensure you have selected UserForm1, then you need to view the Properties box. Do this by either pressing F4 or by clicking on the View ribbon and then Properties Window.

The Properties box allows you to assign extra pieces of information to your controls. For the moment you do not need to worry about most of them. However, you do need to be able to use the Name and Caption properties.

VBA and Macros in Excel 2016 21

Page 26: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Name PropertyWe need to name each of the controls on our form – simply click on each one in turn and then edit the Name in the Properties Box, as follows

NameTextBox

PhoneTextBox

FoodComboBox

CarOptionButton1

CarOptionButton2

7.2.2 Caption PropertyThe Caption property is used to display the name of the control on the screen. Change the Captions on your form to match the diagram on the previous page – don’t forget to set Yes and No Captions for the two Option Buttons! Also change the Captions for the three command buttons to match those is the diagram.

VBA and Macros in Excel 2016 22

Page 27: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

7.3 Attaching code to the User Form

7.3.1 Initialize commandIn order to make a form display and work properly it is necessary to write some code which will run when the form opens.

Open the Visual Basic Editor:

Click on UserForm1 in the Project Explorer and then right-click and select View Code.

Look at the two drop-down lists at the top of the window. In the left-hand one select UserForm and in the right-hand one select Initialize. A new program will automatically be created. Complete this program so it looks like this:

Private Sub UserForm_Initialize()‘Empty NameTextBoxNameTextBox.Value = “”

‘Empty PhoneTextBoxPhoneTextBox.Value = “”

‘Fill FoodComboBoxWith FoodComboBox

.AddItem “Italian”

.AddItem “Chinese”

.AddItem “Indian”End With

‘Set no car as defaultCarOptionButton2.Value = True

‘Set focus on NameTextBoxNameTextBox.SetFocus

End Sub

Code now needs to be added to the buttons on UserForm1.

To view UserForm1 right-click on it in the Project Explorer and select View Object.

Now double-click on the first button (New Entry) and create the following code:

VBA and Macros in Excel 2016 23

Page 28: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Private Sub CommandButton1_Click()Dim EmptyRow As Long

‘Make Sheet1 activeSheet1.Activate

‘Determine empty rowEmptyRow = WorksheetFunction.CountA(Range(”A:A”)) + 1

Cells(EmptyRow, 1).Value = NameTextBox.ValueCells(EmptyRow, 2).Value = PhoneTextBox.ValueCells(EmptyRow, 3).Value = FoodComboBox.Value

If CarOptionButton1.Value = True ThenCells(EmptyRow, 4).Value = “Yes”ElseCells(EmptyRow, 4).Value = “No”

End IF

End Sub

Double-click on the second button and create the following code:

Private Sub CommandButton2_Click()Call UserForm_InitializeEnd Sub

And the third button:

Private Sub CommandButton3_Click()Unload MeEnd Sub

The second button simply re-initialises the form and the third button closes the form down.

7.4 Test the UserformExit the Visual Basic Editor, enter the following labels into Row 1, Sheet 1 of your workbook and click on the button to test it out.

Note: You can also change the text which appears on the button by right-clicking on it and selecting Edit Text.

VBA and Macros in Excel 2016 24

Page 29: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

7.5 Further Exercise 1Open a new workbook and create a user input form to record student results called June2015. Include the following fields:

Student No. (text box) Name (text box) Department (combo box) which includes 5 different subjects, Archaeology, Biology,

Chemistry, Computing and History Module 1 (text box) Module 2 (text box) Module 3 (text box) Total (text box) – this will be worked out using a formula Average (text box) - this will be worked out using a formula Grade (text box) – this will be worked out using a case statement

Write code to ensure that this information is saved to the next available line in the worksheet when the save button is pressed.

Add a button to close the form.

7.6 Further Exercise 2Look at the code below and try to work out what it is doing.

Private Sub CommandButton1_Click()item_in_review = 0row_number = 0Dim Module1 As LongDim Module2 As LongDim Module3 As LongDim Total As Long

DoDoEventsrow_number = row_number + 1item_in_review = Sheets("Records").Range("A" & row_number) If item_in_review = StudNoTextBox.Text Then StudNameTextBox.Text = Sheets("Records").Range("B" & row_number) DeptComboBox.Text = Sheets("Records").Range("C" & row_number) Module1TextBox.Value = Sheets("Records").Range("D" & row_number) Module2TextBox.Value = Sheets("Records").Range("E" & row_number) Module3TextBox.Value = Sheets("Records").Range("F" & row_number) Module1 = Module1TextBox.Value Module2 = Module2TextBox.Value Module3 = Module3TextBox.Value Total = Module1 + Module2 + Module3 TotalTextBox.Value = Total AverageTextBox.Value = TotalTextBox.Value / 3 Select Case AverageTextBox Case Is < 40 GradeTextBox = "Fail" Case 40 To 49 GradeTextBox = "D" Case 50 To 59 GradeTextBox = "C" Case 60 To 69 GradeTextBox = "B"

VBA and Macros in Excel 2016 25

Page 30: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Case Is >= 70 GradeTextBox = "A" End Select End If

Loop Until item_in_review = ""

End Sub___________________________________________________________________________

Private Sub CommandButton2_Click()item_in_review = 0row_number = 0Dim Module1 As LongDim Module2 As LongDim Module3 As LongDim Total As Long

DoDoEventsrow_number = row_number + 1item_in_review = Sheets("Records").Range("A" & row_number) If item_in_review = StudNoTextBox.Text Then Module1 = Module1TextBox.Value Module2 = Module2TextBox.Value Module3 = Module3TextBox.Value Total = Module1 + Module2 + Module3 TotalTextBox.Value = Total AverageTextBox.Value = Round(TotalTextBox.Value / 3, 0) Select Case AverageTextBox Case Is < 40 GradeTextBox = "Fail" Case 40 To 49 GradeTextBox = "D" Case 50 To 59 GradeTextBox = "C" Case 60 To 69 GradeTextBox = "B" Case Is >= 70 GradeTextBox = "A" End Select Sheets("Records").Range("B" & row_number) = StudNameTextBox.Text Sheets("Records").Range("C" & row_number) = DeptComboBox.Text Sheets("Records").Range("D" & row_number) = Module1TextBox.Text Sheets("Records").Range("E" & row_number) = Module2TextBox.Text Sheets("Records").Range("F" & row_number) = Module3TextBox.Text Sheets("Records").Range("G" & row_number) = TotalTextBox.Value Sheets("Records").Range("H" & row_number) = AverageTextBox.Value Sheets("Records").Range("I" & row_number) = GradeTextBox.Text End If

Loop Until item_in_review = ""End Sub___________________________________________________________________________

Private Sub CommandButton3_Click()Unload Me

End Sub___________________________________________________________________________

Type in the code to test it out.

VBA and Macros in Excel 2016 26

Page 31: ITS Guide Template for Word 2007 - dur.ac.uk€¦ · Web viewVersion 1.0. Writing Macros and Programs in VBA. This guide introduces the main features of Excel 2016 to create macros

Space for notes:

VBA and Macros in Excel 2016 27