1. Getting Started Learning Outcomes Introduction Starting up Visual Basic for Applications Exercise 1...

Size: px
Start display at page:

Download "1. Getting Started Learning Outcomes Introduction Starting up Visual Basic for Applications Exercise 1..."

Transcription

1 1. Getting Started... 6 Learning Outcomes... 6 Introduction... 6 Starting up Visual Basic for Applications... 7 Exercise Writing your first programme... 9 Learning Outcomes... 9 Introduction... 9 Variables... 9 A simple programme Exercise Assignment: Part Interacting with the User Learning Outcomes Introduction The InputBox Function Exercise Asssignment Part Decisions Learning Outcomes Introduction Calculating different Tax Regimes Exercise Assignment Part More Complex Decisions Learning Outcomes The case construct Visual Basic for Applications

2 Summary Practice Exercises Assignment Part Loops Learning Outcomes Introduction The for loop The while loop The do..loop until Summary Practice Exercise Assignment Part Functions & Procedures Learning Outcomes Introduction Functions and procedures A revisit to the Payroll Summary Practice Exercise Assignment Part Using Strings Learning Outcomes Introduction Using String variables in a programme Visual Basic for Applications

3 Exercise Assignment Part Debugging a programme Learning Outcomes Introduction Breakpoints Practice Exercise File Processing Learning Outcomes Introduction A file writing programme Practice Exercise Assignment Part Objects, Properties & Events Learning Introduction A look at Forms The Textbox, Label and Command Button controls Creating and running Code in a Form Summary Practice Assignment Part More Events Learning Outcomes Introduction Visual Basic for Applications

4 More Controls Checkbox, Option Button and Frame Macros Learning Outcomes Introduction Creating an Excel Macro Using Macro Code as part of a general Visual Basic application Spreadsheet Components coded in VB Learning Outcomes Using a Form to interact with a Worksheet Learning Outcomes Introduction Using a Form as a Switchboard Adding Data using a Form Modifying existing Data using a Form Deleting Records Browsing the Data Visual Basic for Applications

5 Programming Basics 5 Visual Basic for Applications

6 1. Getting Started Learning Outcomes On completion of this chapter you will know: The range of applications where you can use VB for Applications How to use VB for Applications for customising those applications How to create a code window How to create a form that will act as a user interface Introduction The most commonly used Microsoft products are Word Excel Access PowerPoint Each of those application have attached to it a version of VB for Applications. This is a programming language based on the standalone language Visual Basic and contains all of the programming facilities of the parent language. As well as those original features each version of VB for Applications has extra features attached to it that allows it to manipulate the features of the application to which it is attached. To explain the above statement let us take the language that is attached to Excel. As a spreadsheet Excel deals with such items as cells, columns, rows, ranges, worksheets, workbooks etc. The VB for Applications that is attached to Excel has special features attached to it that allow it to manipulate the items that are unique to a spreadsheet. A small example of what those features are: 1. Adding/deleting rows and columns 2. Adding/deleting worksheets 3. Altering the format or values of cells All of these actions will happen automatically under programme control. Similarly the VB for Applications attached to Access has extra features that allow us to manipulate the contents of tables. This includes opening and closing tables, modifying data 6 Visual Basic for Applications

7 in those tables, adding new records to tables or deleting records from the same. Needless to say the VB attached to Word has special code for controlling such features as font type and size, paragraph formatting, manipulation of tables. In fact anything that you can do with Word manually, can also be done to it using programme control. This book is divided into three parts. In the first part we concentrate on how to programme using Visual Basic. This will be done with no reference to any of the applications that it is attached to. What you learn here can be applied to all versions of VB for Applications as well as to the standard Visual Basic itself. Thus you can use either Visual Basic itself or one of the application versions of it. Once we have mastered the programming techniques we can then look at how those technique be applied in order to manipulate Excel and Access. As those are two very different applications the programming for each will be in two separate parts. Starting up Visual Basic for Applications Figure 1-1 In this book we shall be using the Excel version of VB for Applications in order to teach programming techniques. For this reason our first task is to learn how to start up Visual 7 Visual Basic for Applications

8 Basic from within Excel. This is in fact very simple. We simply open up an Excel workbook and then use Alt+F11. This will bring up a window as shown in Figure 1-1 above. This is the window that you will be using for writing your programming code. Using Alt+F11 in either Word or Access will also bring up and identical code window in the same applications. Exercise 1 1. What is Visual Basic for Applications? 2. What is the difference between it and standard Visual Basic? 3. What are the steps for starting up VB for Applications? 4. Name the three windows that make up the VBA programming interface. 8 Visual Basic for Applications

9 Learning Outcomes 2. Writing your first programme On completion of this chapter you will know: How to enter simple programme code How to run this programme and view the output How to interact with the user of the programme The meaning and use of computer variables The use of the Immediate Window Introduction When dealing with computers, programming means giving the computer instructions on how to perform a particular task. All applications that you work with on a computer such as Word, Excel, Gimp, Inkscape etc are all computer programmes. Of course those programmes are a lot more complex than the simple programmes that you will start with, but by the end of the course you may have an idea on how to tackle one of them. Also programmes such as those mentioned above were not written by one person but by a team of perhaps one hundred programmers. In fact big applications such as those mentioned are strictly not programmes but a group of hundreds of small programmes that interact with each other. In this course you will start by building very small and simple programmes that will get bigger and more sophisticated as you learn more techniques, until eventually you will have a small business application that will be similar to an accounting application. Variables The manipulation of variables is at the heart of computer programming. To the nonprogrammer variables are associated with algebra. A typical algebraic problem would be as follows: If x = 5, y = 9 and z=3, what is the value of 2x+3y-5z? The solution to this of course is that if x is 5 then 2x is 10, if y is 9 then 3y is 27 and if z is 3 then 5z is 15. Thus the expression 2x+3y-5z equates to which is 22. We shall look at one more example of algebraic expression. In calculating a person s pay we multiply the number of hours the person has worked with his hourly rate. Thus if a person 9 Visual Basic for Applications

10 has worked x hours and if his hourly rate is y, then his pay is xy. On a particular week if the person has worked 30 hours and if his rate is K8 per hour then we can state the problem as follows: If x = 30 and y = 8, what is the value of xy? In this case the solution is the same as above, i.e. if x is 30 and y is 8 then xy is 30 multiplied by 8, which is 240. As stated earlier, programming a computer involves the manipulation of variables and they are manipulated in exactly the same way as they are manipulated in algebra. This means that we assign a value to each variable in the expression and then perform the calculation specified in that expression. There are, however, a few differences between how we use variables in algebra and how we use them in programming. Some of the differences are as follows: 1. In algebra we use a single letter to denote a variable. The most common letters are x, y, z followed by a, b, c. In programming the names of the variables can be as long as we want them to be. Thus in our payroll example above, instead of If x = 30 and y = 8, what is the value of xy we would have the following: if hours = 30 and rate = 8, what is the value of hours * rate? A computer programme would solve the problem as follows: 1 Hours = 30 2 Rate = 8 3 Gross = Hours * Rate 4 Print Gross 2. In algebra we assign only numeric values to variables and we don t care whether they are integers or real numbers. In programming we must be more precise. We must specify whether a variable is to hold an integer or a real number. In fact, order to make better use of the computer s memory, we can specify whether the integers are long or short and whether the real numbers are double or single precision, or currency. This will be dealt with in more detail in the next chapter. 3. In algebra, variables represent only numeric values. In programming, variables can certainly represent numeric values, but they can also represent text and a variety of other objects such as data stored in databases etc. We need not concern ourselves with this use of variables until later in the course. 10 Visual Basic for Applications

11 A simple programme Figure 2-1 In order to start writing a programme you must create a module into which you enter your code. To do this click on Insert in the main menu and from the drop down list click on Module. Your display will now alter to that shown in Figure 2-1 above. You are now ready to enter your code. For our first programme we shall use the code shown in Listing 2-1 below. Type in this code apart from the numbers on the left. Those numbers are not part of the code, they are there as reference for the lines of the code so that when we are explaining the code the lines will be easy to refer to. Listing Sub payroll() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim curgross As Currency 5 Dim curtax As Currency 6 Dim curnet As Currency 7 snghours = 30 8 currate = 8 11 Visual Basic for Applications

12 9 curgross = snghours * currate 10 curtax = curgross * curnet = curgross - curtax 12 Debug.Print curgross 13 Debug.Print curtax 14 Debug.Print curnet 15 End Sub When you have finished entering the code, save your work. The next step is to run the programme. To do this simply click anywhere inside the code area and press F5. If you have entered the code correctly then your screen will look as in Figure 2-2 below. Figure 2-2 Let us spend some time examining what we have here. Firstly, in the Code window we have the code almost as we entered it with one exception. Some words are in blue while the rest are in black. What s the difference between them? The words in blue are Sub, Dim, As, Single, Currency, End and Debug.Print. Those are referred to as Reserved Words. They mean something special to Visual Basic and we are allowed to use them only in certain circumstances. We shall discuss this in more detail shortly when we will examine the code itself. 12 Visual Basic for Applications

13 The Project window has altered from what it looked like in Figure 2-1. It now has a Module folder with one module whose name is Module 1. The window we most need to look at is the Immediate Window at the bottom right of the main window. (If this window is not visible then click on View/Immediate Window.) If you have entered the code exactly as it is shown in Listing 2-1 then this window should show the values 240, 60, 180. Now let us examine the code itself as shown in Listing 2-1 The first lines we need to look at are lines 1 and 15. Line 1 has Sub payroll in it. As stated above the word Sub is a reserved word in Visual Basic. It is a short form of the word subroutine, which in programming terms means a group of lines of programme code that are executed together. Every subroutine must have a name, which the user chooses. Since, in our case, we are dealing with a very simple pay application we have named the subroutine payroll. Line 15 has the words End Sub. Clearly this means the end of the subroutine. Thus our entire application is contained within the keywords Sub and End Sub. This means that when we run a subroutine it starts at the line following Sub and it stops at the line immediately before End Sub. Thus the lines in our programme that run at the lines 2 14 inclusive. Lines 2 6 all begin with the keyword Dim. This is an abbreviation of the word dimension. These are the lines where we declare our variables. The word Dim indicates to Visual Basic that we are creating a variable. This is followed directly by the name off the variable itself. In line 2 the name is snghours. The name of the variable is followed by the keyword As, which is itself followed by Single in line 2. Recall that in Chapter 1 we stated that computer variables, as well as having long names, can also have different data types assigned to them. The data type assigned to snghours is Single. This again is an abbreviation of single precision floating point number. In simple terms it is a real number or a number with decimal places. Line 3 is similar to line 2 except for the word Currency. For a change it is quite clear what this variable will hold monetary values. Lines 4, 5 and 6 follow the same logic as lines 2 and 3. Here we need to say a few words about the convention of naming variables. Firstly we can give a variable any name we wish as long as it is not one of the reserved words of Visual Basic. However, in order to make the programme easier to understand we should give the 13 Visual Basic for Applications

14 variables meaningful names. In our case we are dealing with a payroll application. The data items we need to know are the hours worked and the hourly rate. Once we know those we can work out the gross by multiplying the hours by the rate. Once we know the gross we can work out the tax. Finally once we know the gross and tax we can work out the net pay. Our variables then could have been named Hours, Rate, Gross, Tax and Net. There is nothing wrong with this and the programme would run perfectly well with those names. However to be more precise the variable name must also specify the type of data that is to be stored in that variable. In the case of Hours the data stored there is of type Single. For this reason we put the abbreviation sng in front of the name, thus ending up with the full name of snghours. The variable to hold the rate is of type Currency and thus the abbreviation cur must appear at the front, thus giving the full name of curate. One further point regarding naming of variables. A variable name always starts with a lowercase letter. However, if the name contains more than one word then the first letter of each subsequent word must be capitalised. Hence we have snghours instead of snghours. Of course we can have as many words in our variable name as we wish. Thus in our case we could have the first two variables named snghoursworkedbyempoyee and curhourlyrateofemployee. Now let us look at the rest of the code. As stated above we need to know the value of the hours and rate if we are to work out the values of the gross, tax and net. Thus in line 7 we give the value of 30 to snghours while in line 8 we give the value of 8 to currate. These two lines have exactly the same logic as the algebraic statements: x = 30 y = 8 Line 9 multiplies the values stored in the variables snghours and currate and stores the result in curgross. Again this line has the same logic as z = xy. Based on the values given here z would have the value of 240. Line 10 multiplies the value stored in curgross by 0.25 and stores the result in curtax. In the case of this example the value stored in curtax should be 60. Line 11 calculates the net by subtracting the values stored in curtax from the value stored in curgross. 14 Visual Basic for Applications

15 By the time we have reached line 11 the programme has performed all of our calculations for us and has stored those calculations in the appropriate variables. Those variables, however, exist in the computer memory and thus cannot be seen by human eyes. For this reason, before ending the programme, we must show them to the user. Lines 12, 13 and 14 perform this task for us. In line 12 Debug.Print means write something in the Immediate Window. What will be written into this window will be the values after the keywords curgross in our case. The same logic applies to lines 13 and 14. Before leaving this explanation of the code it is important to point out that programme lines are executed in a strict top-to-bottom order. Thus it is important to ensure that the actions we want the programme to do are specified in the correct order. As an example look at the code in Listing 2-2 below. At first glance it looks very much like Listing 2-1 but if you compare lines 7, 8 and 9 in both of them you will see the difference. In our version below the value of the gross is calculated before any values have been given to either hours or rate. As we need to know the value of hours and rate before we can calculate the value of the gross lines 8 and 9 must come before line 7. Listing Sub payroll() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim curgross As Currency 5 Dim curtax As Currency 6 Dim curnet As Currency 7 curgross = snghours * currate 8 snghours = 30 9 currate = 8 10 curtax = curgross * curnet = curgross - curtax 12 Debug.Print curgross 13 Debug.Print curtax 14 Debug.Print curnet 15 End Sub Practice Copy the code in Listing 2-1into your code area and run it. Check that it runs correctly and that the output appears in the Immediate Window. 15 Visual Basic for Applications

16 Next change the values 30 and 8 for hours and rate in lines 7 and 8 to other values of your choice. Run the programme again and check the output in the Immediate Window. Repeat this action a number of times, each time with a different set of values for hours and rate. After each running check the Immediate Window. Exercise 2 1. A customer buys a number of the same items in a store. If the price of an item is represented by x and the amount purchased by the customer is represented by y, write an algebraic expression for calculating the total the customer is charged. 2. Extend the expression created in 1 above when we learn that the user bought 12 items at K6 each. 3. Three numbers are to be added together. Write an algebraic expression for this problem. Extend the expression if we know that the values of the three numbers are 7, 9 and Two numbers are to be processed as follows: the first is multiplied by 3 and the second multiplied by 4. The two results are then added. Write an algebraic expression for this problem. Extend the expression if we know that the first number is 12 and the second number is Three numbers are to be processed as follows: the first is to be multiplied by 2, the second is to be multiplied by 4 and the third is to be multiplied by 7. The first two results are to be added and the third result is subtracted from the sum. Extend the expression if we know that the three numbers are 7, 9 and 2. The following exercises are based on problems 1 to 5 above. 6. Write a programme based on Exercises 1and 2 above. You must declare three variables, two to hold the values of the amount purchased and the unit price of each item and a third variable to hold the total charged to the customer. The programme will, then, calculate the product of those two values and store the result in the third variable. Finally the programme will display the result of the calculation in the Immediate Window using the Debug.Print command. Ensure that you use the required conventions for naming the variables. 7. Write a programme based on Exercises 3 above. You must declare four variables, two to hold the values of the three variables and also to hold the result. The programme will, then, calculate the sum of those three variables and store the result in 16 Visual Basic for Applications

17 the fourth variable. Finally the programme will display the result of the calculation in the Immediate Window using the Debug.Print command. 8. Write a programme based on exercise 4 above. Follow the same guidelines as for exercises 6 and 7 above. 9. Write a programme based on exercise 5 above. Again follow the same guidelines as for exercises 6 and 7 above Assignment: Part 1 Create a small application for calculating a customer s total in a store. Assume that the customer buys only one item type but that he may buy as many of that item as he wishes. As an example the customer buys only tins o Diana Tuna, but he may buy as many tins as he wishes. The programme will ask the user for the amount of items that the customer has purchased and the unit price for those items. The programme will calculate the subtotal by multiplying the amount sold by the unit price. GST is then calculated by multiplying the subtotal by 0.1 or by dividing the subtotal by 10. The total charged to the customer is then calculated by adding the subtotal and the GST. The values of the subtotal, GST and Total are then printed out in the immediate window. 17 Visual Basic for Applications

18 Learning Outcomes 3. Interacting with the User On completion of this chapter you will know how to interact with the user by directly supplying information to the programme from the keyboard. Introduction In the programme of Listing 2-1 there is no interaction between the user and the programme, other than actually running the programme in the first place. Although the programme calculates the values of the gross, tax and net correctly, it only does it when the values of hours and rate are 30 and 8 respectively. Our programme needs to be more versatile than this. By this we mean that it must be able to calculate the payroll regardless of the number of hours or how big or small the hourly rate is. In order to be able to do this the user must be able to directly supply the programme with the values of the hours and rate. The InputBox Function In Listing 3-1 below we have a new version of the programme we examined in Listing 2-1 above. The structure and the size of the two programmes are the same. The only difference is in lines 7 and 8. Here the constants 30 and 8 are replaced by the InputBox function. When a running programme meets a line with an InputBox function in it, it halts the top to bottom flow of the programme and puts a dialogue box on the screen like that shown in Figure 3-1 below. The programme will wait at that line until the user enters a value in the textbox and clicks on the OK button. In our example below normal top to bottom flow occurs until the programme reaches line 7. Here the InputBox function causes the programme to halt and the dialogue box in Figure 3-1 will appear on the screen. The dialogue box will stay like this until the user enters the value of the hours into the textbox and clicks the OK button. Once this occurs, the value entered by the user into the textbox is stored in the variable snghours. Thus if the user entered 45 into the textbox and pressed the OK button, this would be the same as if line 7, originally, was: snghours = Visual Basic for Applications

19 Returning back to examining line 7: once the user has entered value for the hours and clicked on OK, then, as we said, the value entered by the user is stored in the variable snghours and the programme moves to the next line, i.e. line 8. Here it encounters another InputBox function. This version of the InputBox function will control the entry of the rate in the same way as its predecessor controlled the entry of the hours. Apart from the use of the two InputBox functions there is no other difference between this programme and its predecessor. Listing Sub payroll2() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim curgross As Currency 5 Dim curtax As Currency 6 Dim curnet As Currency 7 snghours = InputBox("Enter hours worked") 8 currate = InputBox("Enter hourly rate") 9 curgross = snghours * currate 10 curtax = curgross * curnet = curgross - curtax 12 Debug.Print curgross 13 Debug.Print curtax 14 Debug.Print curnet 15 End Sub Figure 3-1 Programme Divisions Input, Process and Output Let us have another look at Listing 3-1. Lines 2 6 is where the variables are declared. Apart from those lines the rest of the code i.e. lines 7 14 are divided into three logical parts. Lines 7 and 8 look very similar and perform similar functions they allow the user to put data into the programme. This part of the code is called the Input section. 19 Visual Basic for Applications

20 Line 9 uses the values that were input in lines 7 and 8 in order to calculate the value of the gross. Line 10 uses the result of line 9 in order to calculate the tax. Line 11 uses the results of lines 9 and 10 in order to calculate the net. Thus lines 9, 10 and 11 process the data that was inputted at lines 7 and 8. For this reason lines 9, 10 and 11 are referred to as the Process section of the programme. Lines 12, 13 and 14 print the result of the calculation, or in other words the result of the processing out on to the Immediate Window. For this reason those 3 lines are referred to as the Output section of the programme. Every programme, whether large or small is divided into the same three sections. In large complex programmes the input section itself may be divided into its own Input, Process and Output sections. The same applies to the Process and Output sections. Practice Copy the code of Listing 3-1into your programme area and run it a number of times each time with a different set of values for hours and rate. Each time check that the correct values for gross tax and net are printed out. Exercise 3 1. What is the shortcoming of the programme shown in Listing Explain the use of the InputBox function. 3. All programmes are divided into three components. Name the three components. 4. Discuss what occurs in the three components mentioned above. Asssignment Part 2 Modify the programme that you have created in Assignment Part 1 so that it will use the InputBox function to ask the user directly to enter values for the unit price and the amount sold. The calculation of the subtotal, GST and total are to be left as they were before. 20 Visual Basic for Applications

21 4. Decisions Learning Outcomes On completion of this section you shall know: How to use a simple decision using the If construct How to use a two way decision using the If..Else construct How to make multiple decisions using the Select..Case construct Introduction In all aspects of life we make decisions. Examples are if the PMV s are running we shall go into town, otherwise we shall study. In programming we have to make decisions as well or to be more precise we shall tell the computer how to make decisions. To demonstrate this we shall modify the way we calculate the tax. In Listing 1-1 we had a simple flat tax rate of 25%. In real life tax rates are never as simple as this. If the salary is low then the tax rate will also be low but a higher salary will incur higher tax rate. In our case we shall modify the simple payroll programme we met in Chapter 3 so that it will calculate tax in two different ways depending on the value of the gross pay. Calculating different Tax Regimes In Listing 3-1 tax was calculated as a flat 25% of the gross. As stated above tax calculation is not quite this simple. Most governments have different levels of taxation depending on a person s income level. In our case we shall assume that any gross which is K500 or less will be taxed at 25% whereas any gross that exceeds K500 will be tax at 25% of the first K500 and 33% of the remainder. Let us look below at our modified code to see how this is done. Listing Sub Pay() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim curgross As Currency 5 Dim curtax As Currency 6 Dim curnett As Currency 7 snghours = InputBox("Enter Hours worked") 8 currate = InputBox("Enter Rate") 9 curgross = snghours * currate 10 If curgross <= 500 Then 11 curtax = curgross * Visual Basic for Applications

22 12 Else 13 curtax = (curgross - 500) * End If 15 curnett = curgross - curtax 16 Debug.Print "Gross ", curgross 17 Debug.Print curtax 18 Debug.Print curnett 19 End Sub The code in Listing 4-1 is the same as that in Listing 3-1 until we get to line 10. Here we have an if construct which extends as far as line 14. After this the code is, once again, the same as that in Listing 3-1. At line 10 the If construct begins with the keyword If. This is followed by the condition that is to be tested in this case curgross<500. If we entered 40 for the hours worked and 10 for the hourly rate then curgross would have a value of 400. This would make the condition true since 400 is less than 500, and therefore the body of the If would be executed. This body is simply line 11 and contains only the code for calculating 25% of the gross pay. On the other hand if the value hours was 40 and of rate was 20 then gross would have a value of 800. In this case the condition at line 10 would be false. The body of the If would therefore be skipped and programme control would jump to line 12 for the Else part of the construct. The body of the Else is simply line 13. Earlier we stated that if the value of the gross was greater than 500 the tax would be 25% of 500 which is plus 33% of the remainder. The remainder is calculated as curgross % of this is calculated as (curgross 500) *.33. Thus the entire calculation is (curgross 500) *.33 The bodies of the If and Else can have as many lines of code as are required. They can even contain their own If..Else constructs. In our case the bodies only contain one line of code each. Notice that lines 11 and 13 are further indented than the rest of the code. This is because line 11 is the body of the If construct and line 13 is the body of the Else construct. Practice Copy the code in Listing 4-1into the programme area and run it a number of times. Use different combinations of hours and rate so that some give a gross less than 500 and others give a gross greater than 500. Before running the programme each time first check using pen 22 Visual Basic for Applications

23 and paper what the values for the gross, tax and net should be, then check that the programme outputs the same results. Exercise 4 1. Explain the different components of the IF..Else..End If construct. 2. What code gets executed in the body of the If? 3. What code gets executed in the body of the Else? 4. In Listing 4-1 determine which lines form the Input, Process and Output sections Assignment Part 3 Modify the application you have created for Assignment Part 2 so that it can process customer discounts. If the total is more than K100 then the customer receives a 5% discount otherwise no discount is given. The discount must be subtracted from the subtotal before the GST is calculated. You must add an extra variable to your programme in order to hold the value of the discount. The value of the discount must be printed along with the other values. 23 Visual Basic for Applications

24 Learning Outcomes 5. More Complex Decisions On completion of this chapter you will know how to make the programme perform more complex decisions using the case construct The case construct The If..Else construct is fine when we have only to choose between two alternatives as above. On the other hand if we have to choose between a larger number of alternatives, the If..Else construct, even though it can handle the situation, can be very clumsy. In this situation we use the Select Case construct. In order to explore this construct we shall extend our payroll application further so that it can handle superannuation calculation. Superannuation calculation normally involves taking a percentage of an employee s pay and putting it into his superannuation account. We shall devise a way of calculating this upper contribution. Each employee is given a super code number and this number determines the percentage of his gross that will be deducted and put into his super account. In our case the percentage taken will be according to the following table: Listing 5-1 Superannuation code Percentage 0 0% 1 5% 2 7% 3 10% 4 20% What this means is that if the superannuation code is 0 then the employee pays no superannuation, whereas if the superannuation code is 1 then the employee pays 5% of his gross pay towards the superannuation. The same applies for the other possible values of the superannuation code. On the other hand, if the value for superannuation is any number other than those in the range 0 4, then calculation of the payroll ceases and a message is printed indicating that faulty data has been entered. The modified code appears below in Listing Visual Basic for Applications

25 Listing Sub Pay() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim curgross As Currency 5 Dim curtax As Currency 6 Dim curnett As Currency 7 Dim cursuper As Currency 8 Dim intsupercode As Integer 9 snghours = InputBox("Enter Hours worked") 10 currate = InputBox("Enter Rate") 11 intsupercode = InputBox("Enter superannuation code") 12 curgross = snghours * currate 13 If curgross <= 500 Then 14 curtax = curgross * Else 16 curtax = (curgross - 500) * End If 18 Select Case intsupercode 19 Case 0 20 cursuper = 0 21 Case 1 22 cursuper = curgross * Case 2 24 cursuper = curgross * Case 3 26 cursuper = curgross * Case 4 28 cursuper = curgross * Case Else 30 Debug.Print "Faulty data entered for super code" 31 End 32 End Select 33 curnett = curgross - curtax - cursuper 34 Debug.Print "Gross ", curgross 35 Debug.Print "Tax", curtax 36 Debug.Print "Super", cursuper 37 Debug.Print "Nett", curnett 38 End Sub The first change we notice here is that two new variables have been added. At line 7 a new Currency variable cursuper has been added and at line 8 an Integer variable intsupercode has been added. There is no further change from Listing 4-1 until we get to line 18. Here we meet the Select..Case construct. As with all of the constructs we have met so far it starts with the name of the construct Select Case in this instance - and ends with End followed by the name of the construct. In this example the construct starts at line 18 and 25 Visual Basic for Applications

26 finishes at line 32. Lines are the body of the construct and for this reason they are indented one tab space beyond the Seelct Case and End Select. There are further indentations but we shall look at those in a minute. The code at line 18 Select Case intsupercode is equivalent to the statement check the value of the variable intsupercode. Check it against what? At lines 19, 21, 23, 25 and 27 we have Case 0, Case 1 etc. These lines are equivalent to saying if the value of supercode is 0 or if the value of supercode is 1 etc. Thus the code at line 19 is equivalent to saying if the value of intsupercode is 0 then execute the code at line 20. If this is the case i.e. if intsupercode is zero then the body of this Case is executed at line 20 and the variable cursuper is given the value zero. At this stage no other testing is made since a match has been found and so all of the other Case statements are ignored and control passes to line 33 where execution of the rest of the code continues. Of course if the value of intsupercode is not zero then line 20 is skipped and at line 21 the value for the same variable is tested for being equal to 1. This skipping to each of the Case statements continues until a match has been found. If, however, no match is found then testing finally arrives at line 29 where we meet Case Else. This is equivalent to saying if the value of intsupercode is not 0, 1, 2, 3 or 4. If this is the case, or, in other words, if the value of intsupercode is a negative number or greater than 4 then the body of the Case Else is executed. This is the lines 30 and 31. Line 30 simply states that a faulty value has been received for the superannuation code and at line 31 the keyword End terminates the execution of the programme. Again notice the indentation of the code. Lines 18 and 32 begin and end the Select Case construct and thus they are at the same level of indentation as the main body of the code. Everything between those two lines form the body of the construct and therefore are indented at least one extra tab space. Lines 19, 21, 23, 25, 27 and 29 are indented 1 tab space more than lines 18 and 32. Lines 20, 22, 24, 26, 28, 30 and 31 are indented two tab spaces. Line 20 is the body of the Case 0 construct which is why it is tabbed one more space than line 19. Similarly line 22 is the body of the Case 1 construct which is why it is indented to the same level as line 20. The same applies to lines 24, 26, 28, 30 and 31 In the example above, for each different value of intsupercode a different action was performed. But what about if superannuation was calculated at 5% if the value of the code was 1, 2 or 3. The table below is an example of this situation. 26 Visual Basic for Applications

27 Listing 5-3 Superannuation code Percentage 0 0% 1 5% 2 5% 3 5% 4 7% 5 10% 6 10% 7 20% 8 20% 9 20% The modified code for the new Select Case construct is shown in Error! Reference source not found.. The rest of the code both before and after it has been omitted since it has not changed. Listing Select Case intsupercode 2 Case 0 3 cursuper = 0 4 Case 1, 2, 3 5 cursuper = curgross * Case 4 7 cursuper = curgross * Case 5, 6 9 cursuper = curgross * Case 7, 8, 9 11 cursuper = curgross * Case Else 13 Debug.Print "Faulty data entered for super code" 14 End 15 End Select In the case where intsupercode has a value of 0 then there is no difference between this and the previous version. On the other hand if intsupercode has a value of 1, 2 or 3 then control enters at line 4 and only line 5 will be executed. After this control will pass to the line after the End Select statement. Thus the Case statement can trap more than one value. In order to specify the values we simply enter them after the keyword Case and separate them with commas. 27 Visual Basic for Applications

28 Summary If we wish to make a choice between two different pathways, depending on the value of a condition then we use the if..else construct. The body of the if is executed if the condition is true, otherwise the body of the else is executed. The bodies of both can be as small as one line of code or as large as we wish. If we wish to test a variable and take a number of different paths depending on its value then we use the Select..case statement. Practice Programme testing involves running a programme, entering sample data and check that the programme s output is correct, or in other words checking that the programme processes the data correctly. In the case of Listing 5-1 we would create a table as below and enter various values for hours and rate. Next we would calculate the different values of gross, tax and nett that the hoursrate combinations would give us and enter those values under Expected output. Next we would run the programme a number of times and each time enter the values that the programme would calculate for us under Actual output. Finally we would compare the data in Expected output and Actual output and if they were the same then we would presume that our programme is processing the data correctly. Listing 5-5 Input Expected output Actual output Hours Rate Gross Tax Nett Gross Tax Nett In Listing 5-1 the gross is calculated by multiplying the hours by the hourly rate. If the gross is 500 or less then the tax is calculated as 25% of the gross. On the other hand if the gross is greater than 500 then tax is calculated as 25% of the first 500 and 33% of the remainder. Nett is calculated by subtracting the tax from the gross. In the above table fill in your own data for hours and rate. Ensure that some of the hours-rate combinations will give you a gross less than 500 and that some will give a gross above Visual Basic for Applications

29 For each combination of hours and rate work out the gross, tax and nett using either pen and paper or a calculator. Enter those values under Gross, Tax and Nett in the Expected Values part of the table. Now run the programme a number of times. Each time you run it enter one of the hours-rate combinations and use the results to fill in the gross tax and nett in the Actual output. Finally compare the data in Expected output and Actual output. Finally we shall look at testing the code in Listing 5-2. For this create a table as shown below. Listing 5-6 Input Expected Output Actual Output Hours Rate Super code Gross Tax Super Nett Gross Tax Super Nett This time enter values for hours, rate and super code. For the values in super code ensure that you will only enter codes that are in the superannuation reference table on Listing 5-1. Exercises 5 1. Describe the structure of the if..else construct. 2. In Listing 4-1 state what lines would be executed and what lines would be skipped if the user entered 20 for hours and 20 for rate. 3. Repeat the above for values of 30 for hours and 20 for rate. 4. Describe the structure of the Select..case construct. 5. In what situations would you use the Select..case construct instead of the if..else construct? 6. In Listing 5-2 what lines would be executed and what lines would be skipped if the value of intsupercode was Repeat the above for a value of 4 for intsupercode. Assignment Part 4 Modify the code you created for Assignment Part 3 so that it can accommodate a select case construct. The method of calculating the discount is to be altered. Now the user will have to enter a discount code into the system. He will be prompted for this in the same way as for the amount sold and the unit price. Discount will be calculated according to the following table. 29 Visual Basic for Applications

30 Discount Code Percentage The calculation of the total will remain the same as in Assignment Part 3. In order to test the correctness of the code prepare test input data and manually calculate what the output should be. Now run the programme a number of times with the various input data sets that you had prepared and check the output from the programme matches the expected output every time. Use Listing 5-5 and Listing 5-6 as models for preparing your test data. 30 Visual Basic for Applications

31 6. Loops Learning Outcomes On completion of this section you will be familiar with the structures and uses of: for loops while loops do loops Introduction The sequence of our programming has up to now gone from top to bottom. In Listing 2-1 the sequence of execution went from line 7 to line 14 without any interruption. (The lines containing variable declarations are not executed.) In Listing 4-1 the sequence of execution would go 7, 8, 9, 11, 15, 16, 17, 18, if the value of curgross was 500 or less. If the value was greater than 500 then the sequence would be 7, 8, 9, 13, 15, 16, 17, 18. Some lines could be skipped but the sequence was always top to bottom with no going back. In loops we interrupt this top to bottom sequence, because the nature of a loop is that a group of lines may be repeatedly executed before the line following them gets executed. Thus a sequence of execution of a group of lines containing a loop could be: 1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5, 6, 7, 8 Here we notice that the lines 3, 4, 5 are executed 5 times before line 6 is executed. This means that those lines are part of a loop. In programming there are three types of loops: For loops While loops Do loops In each type of loop a group of lines is repeated. The difference between the loops is how they control the repetition of the lines. The for loop Listing 6-1 below contains a For loop that prints the square of all numbers between 1 and Visual Basic for Applications

32 Listing Sub ForDemo() 2 Dim intcounter As Integer 3 Dim intsquare As Integer 4 For intcounter = 1 To 5 5 intsquare = intcounter ^ 2 6 Debug.Print intcounter, intsquare 7 Next 8 End Sub In lines 2 and 3 we declare the two variables that we shall be using. The first one, intcounter, is used to control the loop as we shall see shortly, while the other will hold the value of the square of counter, before being printed. Line 4 is where the loop is defined. It begins with the keyword For which indicates what type of loop we are going to use. After this we have the variable that is to be the loop counter i.e. intcounter. After the loop counter we have a = and this is followed by the initial value of intcounter which is 1 in this case. The initial value is followed by the keyword To. This keyword is in turn followed by the final value of intcounter which in our case is 5. This means that intcounter starts with an initial value of 1 and is then successively revalued to 2, 3, 4 and 5. Let us now look at a line by line execution. When line 4 is first encountered the variable intcounter is initialised to 1. Since this is less than or equal to 5 the body of the loop is entered. At line 5 the variable intsqure is updated. This is done by squaring the counter and storing the result in intsquare. (In Visual Basic the power operator is ^. Thus intcounter ^ 2 is equivalent to intcounter 2 in ordinary mathematics.) Since intcounter has a value of 1 its square will also be 1 and so intsquare also is 1. Control now passes to line 6 where the values of intcounter and intsquare are printed. In this case the output will be: 1 1 Control now passes to line 7 which contains the keyword Next. This indicates that it is the end of the body of the loop. However as this is a loop it does not necessarily mean that the code following Next will be executed. What happens instead is that control is passed back to line 4, where the value of intcounter is incremented to 2. This value is still not greater than 5 and thus control once more goes into the body of the loop to line 5. This time, intsquare will be valued to 4 (the square of 2) and line 6 will print out 32 Visual Basic for Applications

33 2 4 Control again passes to line 7, where Next passes control back to line 4. Everything proceeds as described up to now until intcounter has a value of 5. When this occurs intsquare is valued to 25 and line 6 prints out 5 25 Once more control passes to line 7. This time the loop counter intcounter - has reached its maximum value. Because of this control is not passed back to line 4 any more, instead control passes to line 8 where the programme ends. In the counter is incremented by 1 each time around the loop. We can, on the other hand increment the counter by any value we want. In Listing 6-2we have an example where the counter is incremented in steps of 2 Listing Sub ForStep() 2 Dim intcounter As Integer 3 Dim intsquare As Integer 4 For intcounter = 1 To 10 Step 2 5 intsquare = intcounter ^ 2 6 Debug.Print intcounter, intsquare 7 Next 8 End Sub The code here is identical to that in Listing 6-1except for line 4. In the present example this reads as For intcounter = 1 To 10 Step 2 This means that the variable intcounter starts off as 1, goes through the body of the loop as explained before, calculating the value of intsquare in line 5 and printing it in line 6. When line 7 passes control back to line 4, Step 2 ensures that intcounter is incremented by 2 instead of by 1. Thus its new value will be 3. This means that at each turn of the loop the successive values of intcounter and intsquare will be Visual Basic for Applications

34 9 81 The For loop can also count backwards as shown in Listing 6-3 Listing Sub ForBack() 2 Dim intcounter As Integer 3 Dim intsquare As Integer 4 For intcounter = 5 To 1 Step -1 5 intsquare = intcounter ^ 2 6 Debug.Print intcounter, intsquare 7 Next 8 End Sub Once again this programme changes from its two predecessors only at line 4. This time it is For intcounter = 5 To 1 Step -1 In this case intcounter starts at 5 and each time around the loop its value will decrease by 1 each time until it reaches 1. Its output will be: Before leaving the For loop we shall look at its most frequent uses totalling numbers. Listing 6-4 shows a programme for totaling the numbers between 1 and 5. Listing Sub AddUp() 2 Dim intcounter As Integer 3 Dim inttotal As Integer 4 inttotal = 0 5 For intcounter = 1 To 5 6 inttotal = inttotal + intcounter 7 Next 8 Debug.Print inttotal 9 End Sub In this listing the main difference is at line 6 where the total is calculated. Notice that at line 4 the number that holds the total is initialised to zero. After that we enter the body of the loop. The first time around the loop intcounter will have a value of 1. Thus at line 6 inttotal = inttotal + intcounter means add the value of inttotal to the value of intcounter and store the result in inttotal. The first time around the loop intcounter will have a value of 1 and inttotal will have a value of 0, thus line 4 will be equivalent to inttotal = Once the line is executed inttotal will end up with a value of Visual Basic for Applications

35 The second time around the loop intcounter will have a value of 2 and inttotal will have a value of 1, thus line 4 will be equivalent to inttotal = Once the line is executed inttotal will end up with a value of 3. The third time around the loop intcounter will have a value of 3 and inttotal will have a value of 3, thus line 4 will be equivalent to inttotal = Once the line is executed inttotal will end up with a value of 6. The fourth time around the loop intcounter will have a value of 4 and inttotal will have a value of 6, thus line 4 will be equivalent to inttotal = Once this line is executed inttotal will end up with a value of 10. The final time around the loop intcounter will have a value of 5 and inttotal will have a value of 10, thus line 4 will be equivalent to inttotal = Once this line is executed inttotal will end up with a value of 15. The while loop Listing 6-4 shows a For loop that adds up the numbers between 1 and 5. This is fine but what if we wanted to add up the numbers between 5 and 35? We could, of course, alter line 5 to For intcounter = 5 To 35. This would work but altering programme code frequently is not recommended especially if it is being used by a non IT person. Suppose we were adding up random numbers such as 125, 15, 89, 217, 5. In this case the For loop would be of no use at all. In this instance we need the While loop. A While loop is structurally and logically different from a For loop. The main differences between them are as follows: The For loop is controlled by the values on both sides of the keyword To. These values determine how many times the loop will run. The while loop is controlled by a priming read before the loop itself and then by a test that occurs at the start of the loop. There is a second read inside the body of the loop that further controls it. The For loop runs a definite number of times. The While loop runs an indefinite number of times and in fact, depending on the circumstances may not run at all. Listing 6-5 below shows the structure of a while loop. 35 Visual Basic for Applications

36 Listing Sub WhileExample() 2 Dim intvalue As Integer 3 Dim inttotal As Integer 4 inttotal = 0 5 intvalue = InputBox("Enter value to be totalled") 6 While intvalue >= 0 7 inttotal = inttotal + intvalue 8 intvalue = InputBox("Enter value to be totalled") 9 Wend 10 Debug.Print "The total of the values you have entered is ", inttotal 11 End Sub This loop is used to total up a random set of numbers that is entered by the user. It could be used for totalling student marks or totalling a customer s purchases at a supermarket checkout since in both of those cases the values would always be positive. In lines 2 and 3 we declare our variables. intvalue will be used to accept the value entered by the user while inttotal will be used to total up all of the values. When using a variable for totalling up a number of values, the first action should always be to initialise that variable to zero. In our case this is done at line 4. Line 5 contains the priming read of the loop. The user is simply requested to enter a value and once the value is entered it is stored in the variable intvalue. Line 6 is the start of the loop structure. It begins with the keyword While. This is followed by the condition. In our case the condition is intvalue >= 0. Thus if the user entered 6 then the condition would be true. If the condition is true then the main body of the loop is entered. The body of the loop consists of lines 7 and 8. In line 7 the value entered by the use is added to inttotal in exactly the same way as it was done in line 6 of Listing 6-4. Line 8 contains the other loop control the main read of the loop. Notice that this line is identical to line 5 it accepts the user s input and stores it in the variable intvalue. Once this is done control passes to line 9 which contains the keyword Wend. This is an abbreviation of while end and is the end of the loop structure. Wend passes control back to the line containing While i.e. line 6, where the value of intvalue is tested once more. If the condition is true then the body of the loop is entered once more and processing proceeds as before. This continues indefinitely until the user enters a negative number at line 8. When this occurs Wend passes control back to line 6 again where intvalue is tested once more. This time the condition will be false since intvalue will contain a negative number. Because of this the 36 Visual Basic for Applications

37 body of the loop will be skipped and control will pass to the line after the Wend statement, i.e. to line 10. Here the value of inttotal is printed and the programme finishes. As a final example of the While loop we shall look at how to use it to validate data, in other words how to use it to ensure that only correct data is allowed to be processed by the programme. As an example, in our payroll programme if we want to ensure that the hours worked are between 5 and 60 then we must ensure that any number that is greater than 5 or less than 60 is rejected and that the user is asked to re-enter that number again. This process should continue until a number in the correct range, i.e. between 5 and 60 is received. In Listing 6-6 below is shown part of the Pay programme where a While loop structure that extends from line 2 to line 6 is used to control the values that can be entered into the variable snghours. Listing snghours = InputBox("Enter Hours worked") 2 While snghours < 5 Or snghours > 60 3 MsgBox "Hours must be in the range 5-60" 4 snghours = InputBox("Enter hours") 5 Wend 6 currate = InputBox("Enter Rate") At line 1 we have the priming read for the loop. This line is identical to line 5 in Listing 6-5. In the current case, instead of going straight ahead and getting the value for the rate we set about ensuring that the value entered is between 5 and 60 inclusive. Thus at line 2 we have a While structure with a somewhat more complex condition than we have had before. This is because we have to check the number is greater than or equal to the minimum value and less than or equal to the maximum value. Thus the condition has got two parts separated by the operator Or. This means that if any one of the two subconditions is true the entire condition is true. As an example if snghours has a value of 3 then the subcondition snghours <5 will be true while the sub condition snghours > 60 will be false. Since one of them is true then entire condition will be true. Similarly if snghours has a value of 80 then snghours < 5 will be false while snghours > 60 will be true. Once again one of the sub conditions is true and therefore the entire condition is true. If the entire condition is true then the body of the loop is entered where at line 3 a message is displayed indicating the fact that a number in the wrong range was entered and at line 4 the 37 Visual Basic for Applications

38 user is once more asked to enter the value for hours. The Wend at line 5 throws the programme back to line 2 again where the new value for hour is tested. On the other hand, if at line 1 the user had entered 40 for hours then the sub condtion snghours < 5 would be false and snghours > 60 would also be false. Because of this the entire condition would be false. In this case the body of the loop would be skipped and control would jump from line 2 to line 6 where the user would be prompted to enter the value for the rate. The do..loop until The final loop construct, the do..loop until, appears in Error! Reference source not found. below. Listing Sub DoLoopExample() 2 Dim intvalue As Integer 3 Dim inttotal As Integer 4 inttotal = 0 5 Do 6 intvalue = InputBox("Enter a number") 7 If intvalue >= 0 Then 8 inttotal = inttotal + intvalue 9 End If 10 Loop Until intvalue < 0 11 Debug.Print inttotal 12 End Sub The loop structure here is between lines 5 and 10. Notice that there is no priming read outside of the loop structure itself. The only read in the loop occurs at line 6. An IF construct test if this value is a positive number. If it is then at line 8 the value entered is added to the variable inttotal. At line 10 the variable intvalue is tested for being negative. If it is then the loop terminates, otherwise control is passed back to line 5 again. Summary All loops are used to repeat a group of command lines a number of times. Each loop must have a keyword to indicate what type of loop it is, a counter that keeps track of how often to go around the loop, a part that initialises the counter, a part that alters the counter and condition that tests the value of the counter to see if it has reached its minimum or maximum. 38 Visual Basic for Applications

39 In the For loop, the values before and after the keyword To controls how many times the loop repeats. The value of the loop counter starts at the first number and is incremented on each repetition until the counter is equal to the second number. In the While loop the counter is initialised outside the body of the loop in a separate command line. The condition of the loop follows the keyword While. If the condition is true then the body of the loop is entered where the loop processing occurs. Beore the end of the loop the loop counter is revalued again and the keyword Wend passes control back to the While line once more. This process continues until the condition of the loop becomes false. Practice Copy the code of Listing 5-2 into your programme area and modify it by adding the While loop in Listing 6-6 in order to validate the value of the hours. Now run this program and try entering values for hours that are less then 5 or greater than 60 and ensure that each one of them is rejected and that the programme comes back again to ask for another value for hours.. Once you are satisfied that values less than 5 or greater than 60 are rejected then test a range of values that are between 5 and 60 and ensure that all of those are accepted. Finally add another While loop to validate the value of the rate. The rate must be between 10 and 20. Again test the programme a number of times to ensure that numbers less than 10 or greater than 20 are rejected and that numbers that fall between 10 and 20 are accepted. Finally prepare test data for various ranges of values for hours and rate. For each have some below the allowed range, within the allowed range and above the allowed range. Determine which set of values will produce output and which will not. Now run the programme and test it with those values. Check that the expected results and the actual results are the same. Exercise 6 Part 1 1. give a general definition of a programming loop. 2. describe the structure of a for loop. 3. what are the essential components of a while loop and where are they placed in relation to the structure of the loop? 4. what are the main logical differences between a while loop and a for loop? 39 Visual Basic for Applications

40 5. what are the essential components of a do..while loop and where are they placed in relation to the structure of the loop? 6. what are the similarities between the while and the do..while loops? 7. what are the differences between the while and the do..while loops? Part 2 Write a programme, using a For loop, that adds up all of the numbers between 1 and 100. The programme will only print out the final sum, and not the intermediate calculations. Part 3 Repeat part 2Error! Reference source not found., except this time use a while loop. In Listing 6-5 the Input and Process sections are mixed up. Determine which lines form the Input and which ones form the Process. For Loop Exercises Option Explicit Sub forpractice1() Dim intcounter As Integer Dim intlow As Integer Dim inthigh As Integer Dim intsquare As Integer Dim intcube As Integer intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = intlow To inthigh intsquare = intcounter ^ 2 intcube = intcounter ^ 3 Debug.Print intcounter; intsquare; intcube Next End Sub Explain what this programme is doing. What will be the output to the above if the user enters 5 and 10 for the two values. Sub forpractice2() Dim intcounter As Integer 40 Visual Basic for Applications

41 Dim intlow As Integer Dim inthigh As Integer Dim intsquare As Integer Dim intcube As Integer intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = intlow To inthigh intsquare = intcounter ^ 2 intcube = intcounter ^ 3 Next Debug.Print intcounter; intsquare; intcube End Sub What is the difference between this programme and the first one? Which Sub forpractice3() Dim intcounter As Integer Dim intlow As Integer Dim inthigh As Integer Dim intsum As Integer intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = intlow To inthigh intsum = intsum + intcounter Debug.Print intsum Next End Sub Explain what the above programme is doing. What is the difference between it and the two previous ones? What will the output be if the user enters 2 and 7 for the values? Sub forpractice4() Dim intcounter As Integer Dim intlow As Integer Dim inthigh As Integer Dim intsum As Integer 41 Visual Basic for Applications

42 intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = intlow To inthigh intsum = intsum + intcounter Next Debug.Print intsum End Sub What is the difference between it and the two previous ones? What will the output be if the user enters 2 and 7 for the values? Which programme is more correct? Sub forpractice5() Dim intcounter As Integer Dim intfactorial As Integer intfactorial = 1 For intcounter = 1 To 6 intfactorial = intfactorial * intcounter Debug.Print intfactorial Next End Sub Sub forpractice6() Dim intcounter As Integer Dim intfactorial As Integer intfactorial = 1 For intcounter = 1 To 6 intfactorial = intfactorial * intcounter Next Debug.Print intfactorial End Sub forpractice5 and forpractice 6 are very alike. What are the defferences between them and forpractice3 and forpractice4 42 Visual Basic for Applications

43 Each of the programmes below has something wrong with it. Work out what it is. Sub wngpractice1() Dim intcounter As Integer Dim intlow As Integer Dim inthigh As Integer Dim intsquare As Integer Dim intcube As Integer intcounter = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = intlow To inthigh intsquare = intcounter ^ 2 intcube = intcounter ^ 3 Debug.Print intcounter; intsquare; intcube Next End Sub Sub wngpractice2() Dim intcounter As Integer Dim intlow As Integer Dim inthigh As Integer Dim intsquare As Integer Dim intcube As Integer intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = 1 To 10 intsquare = intcounter ^ 2 intcube = intcounter ^ 3 Next Debug.Print intcounter; intsquare; intcube End Sub Sub wngpractice3() Dim intcounter As Integer Dim intlow As Integer Dim inthigh As Integer 43 Visual Basic for Applications

44 Dim intsum As Integer intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = intlow To 10 intsum = intsum + intcounter Debug.Print intsum Next End Sub Sub wngpractice4() Dim intcounter As Integer Dim intlow As Integer Dim inthigh As Integer Dim intsum As Integer intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = intlow To inthigh intsum = intsum + intcounter Next End Sub Sub wngpractice5() Dim intcounter As Integer Dim intfactorial As Integer intfactorial = 1 For intcounter = 1 To 6 Debug.Print intfactorial Next End Sub Sub wngpractice6() Dim intcounter As Integer Dim intfactorial As Integer intfactorial = 1 For intcounter = intlow To inthigh intfactorial = intfactorial * intcounter Next 44 Visual Basic for Applications

45 Debug.Print intfactorial End Sub All of the above programmes have something wrong with them. Find the error in each case. Also determine what would the output be if each of them were run. 45 Visual Basic for Applications

46 Sub sample1() Dim intlow As Integer Dim inthigh As Integer Dim intcounter As Integer Dim intcount As Integer Dim intavg As Integer Dim intsum As Integer Dim intdiff As Integer For intcounter = 1 To 10 intcount = intcounter + 1 intsum = intsum + intcounter intavg = intsum / 10 Debug.Print intcounter, intcount, intsum, intavg Next End Sub Write out the output of the above programme. There are some extra lines in the programme that are not used. Which lines are they? What does the programme do? Sub sample2() Dim intlow As Integer Dim inthigh As Integer Dim intcounter As Integer Dim intcount As Integer Dim intavg As Integer Dim intsum As Integer Dim intdiff As Integer For intcounter = 1 To 10 intcount = intcounter + 1 intsum = intsum + intcounter intavg = intsum / 10 Next Debug.Print intcounter, intcount, intsum, intavg End Sub What is the difference between this programme and the previous one? 46 Visual Basic for Applications

47 Sub sample3() Dim intlow As Integer Dim inthigh As Integer Dim intcounter As Integer Dim intcount As Integer Dim intavg As Integer Dim intsum As Integer Dim intdiff As Integer intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = 1 To 10 intcount = intcounter + 1 intsum = intsum + intcounter intavg = intsum / 10 Next Debug.Print intcounter, intcount, intsum, intavg End Sub Whats wrong with this programme? Sub sample4() Dim intlow As Integer Dim inthigh As Integer Dim intcounter As Integer Dim intcount As Integer Dim intavg As Integer Dim intsum As Integer Dim intdiff As Integer intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") For intcounter = intlow To inthigh intcount = intcounter + 1 intsum = intsum + intcounter intavg = intsum / 10 Next Debug.Print intcounter, intcount, intsum, intavg 47 Visual Basic for Applications

48 End Sub What does this programme do?whats wrong with it? Sub sample5() Dim intlow As Integer Dim inthigh As Integer Dim intcounter As Integer Dim intcount As Integer Dim intavg As Integer Dim intsum As Integer Dim intdiff As Integer intlow = InputBox("Enter low value") inthigh = InputBox("Enter high value") intdiff = inthigh - intlow + 1 For intcounter = intlow To inthigh intcount = intcounter + 1 intsum = intsum + intcounter intavg = intsum / intdiff Next Debug.Print intcounter, intcount, intsum, intavg End Sub More for loop exercises 1. The factorial of 7 is 1 x 2 x 3 x 4 x 5 x 6 x 7. Write a programme that calculates and prints out the factorial of 7. All of the intermediary calculations must be shown. 2. Repeat the exercise above but only the factorial of 7 itself is to be printed and not the intermediate calculations. 3. Write a programme that prints the factorial of any number that is entered by the user 4. Write a programme that adds up all of the numbers between 1 and 100. Only the final result is to be printed. 5. Write a programme that calculates the average of all of the numbers between 1 and Visual Basic for Applications

49 Assignment Part 5 Section 1 The programme you created in Assignment Part 4 has a fault in that it can only process the sale of one single item. If the customer purchases two different items then the programme has to be run twice. Your task is to modify the programme so that it can handle the sale of any number of different items. A While loop will be used to control the data entry. The sequence will be as follows: The user is prompted to enter the price of a single item A While loop tests this for being greater than zero. If this is true then the body of the loop is entered and the user is prompted for the amount sold. The processing will now continue as before until the data for that sale is printed. The user is prompted once more for the price of a single item. This command is followed by a Wend which throws control back to the While line where the value is once more tested for being greater than zero Section 2 Modify further the programme of Section 1. As well as being able to handle multiple purchases by the same customer it should also be able to total all of the purchases by that customer as well as totaling the total GST for the same customer. For suggestions on how to do this totaling check Listing 6-5 Section 3 Modify further the programme of Section 1 so that the unit price is validated as being a value between 3 and 25. Use Listing 6-6 as an example of how to do this Section 4 Once you feel that the programme is performing correctly prepare test data. In this case you need two sets of test data. One set tests whether the While loop will either loop or terminate depending on the value entered for the price of a single item. The other set is more complex. This tests data that will cause the While loop to continue looping. It must test that individual 49 Visual Basic for Applications

50 transactions produce the correct results and that a number of transactions will produce the correct total. 50 Visual Basic for Applications

51 Learning Outcomes 7. Functions & Procedures On completion of this section you will be familiar with Difference between functions and procedures The need for them in a programme. How to pass arguments to a function or procedure. How to get values back from functions. Introduction If we look back at Listing 2-1 we had a very simple programme that was very easy to follow since the individual lines of the input, processing and output followed each other in a very logical sequence from top to bottom. Of course this programme was so simple that it was of no use in real life. In order to make it more useful we added an If..Else construct in order to calculate the tax. This addition is shown inlisting 4-1. After that we added a Select..Case construct in order to calculate the superannuation, as shown in Listing 5-2. Finally, in order to validate the hours we added the While loop shown in Listing 6-6Error! Reference source not found.. For completion a similar loop should be added for validating the rate and the superannuation code. Recall that the If.. Else construct was added to handle the complexity of the tax calculation, the Select Case to handle the even more complex superannuation contribution and the While loop to handle the validation of the data going into the variable snghours. In order to restore the original simplicity of the programme we shall create separate procedures for handling the calculation of the gross, the tax, the superannuation and the nett. In the main programme we simply place calls to those procedures As well as making our programme easier to read, functions and procedures have another benefit. Suppose that there was a group of lines of a programme that were required to be used in different parts of the programme, then, we can simply write out the lines of code separately for each part of the programme where they are required. This has two drawbacks: Firstly the more often we retype the lines of code the more likely we are to make a mistake in one of them. This would cause inconsistency in the application. 51 Visual Basic for Applications

52 If the routine needs to be altered then we have to make the same alteration wherever the routine occurs. This has the inherent danger that we may miss out one of the instances of the routine. The other alternative is to write the group of lines together only once and then to call that group whenever we need to use them. This has the following advantages: It saves both saving typing time and storage space. As we write them only once the danger of error is minimised. If the routine needs to be changed then the change has to be done only once Our first task here is to look at what functions and procedures are and what are the similarities and the difference between them. Functions and procedures As we said earlier functions and procedures are pieces of code that are called from other programs in order to perform calculations or else to run pieces of code that are required more than once. The main difference between functions and procedures is that functions perform calculations or other processing and send the result of the calculation or the processing back to the main programme. The procedures don t perform any calculations and don t send any results back to the main programme. A revisit to the Payroll The code shown below is simply Listing 6-6 broken into methods. Below the code we will examine its new construction and how it operates. Listing Sub Pay2() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim curgross As Currency 5 Dim curtax As Currency 6 Dim curnett As Currency 7 Dim cursuper As Currency 8 Dim intsupercode As Integer 9 snghours = InputBox("Enter Hours worked") 10 currate = InputBox("Enter Rate") 11 intsupercode = InputBox("Enter superannuation code") 12 curgross = calculategross(snghours, currate) 13 curtax = calculatetax(curgross) 14 cursuper = calculatesuper(intsupercode, curgross) 52 Visual Basic for Applications

53 15 curnett = calculatenett(curgross, curtax, cursuper) 16 showdata snghours, currate, curgross, curtax, cursuper, curnett 17 End Sub Function calculategross(hours As Single, rate As Currency) As Currency 20 Dim gross As Currency 21 gross = hours * rate 22 calculategross = gross 23 End Function Function calculatetax(gross As Currency) As Currency 26 Dim tax As Currency 27 If gross <= 500 Then 28 tax = gross * Else 30 tax = (gross - 500) * End If 32 calculatetax = tax 33 End Function Function calculatesuper(supercode As Integer, gross As Currency) As Currency 36 Dim super As Currency 37 Select Case supercode 38 Case 0 39 super = 0 40 Case 1, 2, 3 41 super = gross * Case 4 43 super = gross * Case 5, 6 45 super = gross * Case 7, 8, 9 47 super = gross * Case Else 49 Debug.Print "Faulty data entered for super code" 50 End 51 End Select 52 calculatesuper = super 53 End Function Function calculatenett(gross As Currency, tax As Currency, super As Currency) As Currency 56 Dim nett As Currency 57 nett = gross - tax - super 58 calculatenett = nett 59 End Function 60 Sub showdata(hours As Single, rate As Currency, gross As 53 Visual Basic for Applications

54 Currency, tax As Currency, super As Currency, nett As Currency) 61 Debug.Print "Hours ", hours 62 Debug.Print "Rate"; ", rate" 63 Debug.Print "Gross ", gross 64 Debug.Print "Tax", tax 65 Debug.Print "Super", super 66 Debug.Print "Nett", nett 67 End Sub Here Sub Pay extends from line 1 to line 17. At first glance it is remarkably similar to Listing 1-1, but once we examine it closely we begin to find some differences. The first difference is at line 12. This line is curgross = calculategross(snghours, curate) This is equivalent to saying pass control to the function calculategross and pass a copy of the data in the variables snghours and currate to it If the user entered 20 and 30 for hours and rate then those two values will be passed to calculategross. The function calculategross itself spans lines Let us first examine its declaration line: Function calculategross(hours As Single, rate As Currency) As Currency The first word Function indicates that it is a piece of code that will perform a calculation and send the result of that calculation back to the programme that called it. The second word calculategross is the name of the function and whenever we wish to call that function we use its name as we did at line 12. After the name we have what looks like two variables in brackets (hours as Single, rate as Currency). Those are the arguments of the function. If a function is to perform a calculation it has to be given the raw data needed. The arguments is how this data reaches the function. Recall that in line 12 when we called calculategross we also included the variables snghours and currate between the brackets. When the function activates, the value of snghours will be copied into the argument hours and the value of currate will be copied into the argument rate. Because of this copying calculategross now has the raw data it needs to perform its calculations. These calculations occur in the body of the function. At line 20 a local variable gross is declared. At line 21 the values of the arguments hours and rate are multiplied and the result stored in gross. This value must now be sent back to the main programme. This is done at line 22, although to a beginner it is difficult to know what is happening. The command calculategross = gross means do the following 54 Visual Basic for Applications

55 1. finish the function calculategross and return control back to line of code that called it i.e. line take back also the value of the variable gross 3. store this value in the variable to the left of the call to calculategross The function calculategross was called at line 12. The variable to the left of the call is curgross and thus the value calculated inside the body of the function calculategross is stored in this variable. The same logic applies to the calls to the functions calculatetax, calculatesuper and calculatenett at lines 13, 14 and 15. The call to showdata at line 16 is different however. The differences are: 1. There is no variable to the left of the call. 2. The arguments are not enclosed in brackets Let us now look at the definition of showdata itself which spans lines 60 to 67. At line 60 we notice that the first word is Sub and not Function. This means that this will not perform any calculations and will not be returning any value back to the main programme. It is for this reason that there is no variable to the left of it when it is called at line 16. The values of the variables in Sub Pay are passed to its arguments in the same way as values were passed to the functions. Here, however, no calculations are performed on them. Instead they are printed to the screen using Debug.Print Now looking once more at Sub Pay we have restored the original simplicity, and the line by line logic is easy to follow. Thus in the input section the values for hours, rate and super code are received at lines 9, 10 and 11. In the processing section the gross is calculated at line 12, tax at line 13, superannuation at line 14 and nett at line 15. The output section has only one line 16 where a single call to showdata is used to display the result of the calculation. Summary Functions and procedures are used both to avoid repetition of code within a programme and also in order to make the logic of the programme easier to follow. Data is passed by the calling routine to a method using arguments. The data passed and the arguments must match each other in type. The difference between functions and procedures is that functions perform a calculation and return the result of it back to the main programme, whereas procedures 55 Visual Basic for Applications

56 don t return any values back. The functions must be declared with the keyword Function while the procedures are to be declared with the keyword Sub. Practice Copy Listing 7-1 into your computer, and then, compile and run it. Exercise 7 Part 1 1. How does the use of functions and procedures lead to having better written programmes? 2. What does an argument mean as far as functions and procedures are concerned? 3. What co-relation must exist between the arguments and the data passed to them? 4. Describe in detail the similarities and differences between functions and procedures Part 2 In Listing 7-1 determine which lines of Pay2 are the Input, Process and Output sections. Also determine the same section in calculategross or any other of the calculate functions. Does the procedure showdata have all three sections. If not which ones does it have? Assignment Part 6 Modify the code you have created for Assignment Part 5 as follows: 1. Put the calculation of the subtotal, GST, discount and total into three separate functions called calculatesubtotal, calculategst, calculatediscount, calculatetotal. 2. The function calculatesubtotal will have two arguments, the unit price and the amount sold. 3. The function calculategst will have only one argument: the subtotal 4. The function caculatediscount will have two arguments: the subtotal and the discount code 5. The function calculatetotal will have three arguments: the subtotal, the GSt and the discount 6. There must also be a procedure for printing the data called showdata. This will print out the values of subtotal, GST, discount and total. 56 Visual Basic for Applications

57 Although a major reorganization of the programme has occurred here there has been no change in the actual processing. The test data for this part will be exactly the same as that for Part Visual Basic for Applications

58 8. Using Strings Learning Outcomes On completion of this chapter you will know What is a String data type How to get String data from the user and print it Introduction Up to now we have been using numeric data of type Single, Currency and Integer in order to demonstrate how to process a simple payroll application. We have, however, been ignoring the most important part of a payroll application the name of the person being paid. To write a person s name we have to use ordinary text instead of numbers and thus the data types of Single, Currency and Integer that we have been using up to now are no good to us. In order to handle text we must use the data type String. Using String variables in a programme Listing 8-1 below shows one more version of Sub Pay this time with String data added. Listing Sub Pay() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim curgross As Currency 5 Dim curtax As Currency 6 Dim curnett As Currency 7 Dim cursuper As Currency 8 Dim intsupercode As Integer 9 Dim strname As String 10 Dim strsurname As String 11 Dim strfullname As String 12 strname = InputBox("Enter first name of employee") 13 strsurname = InputBox("Enter surname of employee") 14 snghours = InputBox("Enter Hours worked") 15 currate = InputBox("Enter Rate") 16 intsupercode = InputBox("Enter superannuation code") 17 strfullname = strname & " " & strsurname 18 curgross = calculategross(snghours, currate) 19 curtax = calculatetax(curgross) 20 cursuper = calculatesuper(intsupercode, curgross) 21 curnett = calculatenett(curgross, curtax, cursuper) 58 Visual Basic for Applications

59 22 showdata strfullname, snghours, currate, curgross, curtax, cursuper, curnett 23 End Sub Sub showdata(name As String, hours As Single, rate As Currency, gross As Currency, tax As Currency, super As Currency, nett As Currency) 26 Debug.Print "Employee name", name 27 Debug.Print "Hours ", hours 28 Debug.Print "Rate ", rate 29 Debug.Print "Gross ", gross 30 Debug.Print "Tax", tax 31 Debug.Print "Super", super 32 Debug.Print "Nett", nett 33 End Sub At lines 9, 10 and 11 we have declared three String variables, strname, strsurname and strfullname. At lines 12 and 13 we get values form the variables strname and strsurname using the InputBox function. At line 17, at the start of the processing section, we update the value of strfullname using the operator &. This operator adds two strings together. Thus the line of code strworker = James & Graham will result in the value JamesGraham to be stored in the variable strworker. If we wish to have a space separating the name and surname we must alter our code to strworker = James & & Graham For this reason, at line 17, we have strfullname = strname & & strsurname where the name and the surname will be separated by a space. At line 22 the call to showdata includes the variable strfullname and at line 25, where showdata is defined, an extra argument has been added to its list of arguments. The new String argument, name has been placed before the other arguments. Practice Copy the code of Listing 8-1into your programme area. Since none of the functions for calculating the various payroll items are included here you must copy those from Listing 7-1. The same test data will do as that for Part 6, but check each time that the employee s name is printed along with the rest of the other data items. 59 Visual Basic for Applications

60 Exercise 8 Write a programme that accepts two string data items from the user, a person s name and surname. The two data items are printed out in one string item with labels. If the user entered the items John and Smith then the output of the programme would be The name is John and the surname is Smith Assignment Part 7 Modify the programme that you have created for Assignment Part 6 so that two string items are processed: Name of the customer and Description of item purchased. The name of the customer should be entered only once while the description of item purchased has to be entered for each item. No processing occurs on those two string items but their values should be printed out along with the subtotal etc. 60 Visual Basic for Applications

61 Learning Outcomes 9. Debugging a programme On completion of this chapter you will know: The nature of breakpoints How to set and remove breakpoints in a programme How to step through a programme line by line How to examine values of variables while stepping through a programme Introduction When normally running a programme the processing speed is very fast and we cannot see the individual lines of programme being executed. This is as it should be since if we could see each line being executed the programme would be running so slow that it would be completely useless. Occasionally, however, it is good to be able to slow down the processing so we can examine individual lines being executed. Some of the reasons for this are: The programme may not be functioning as it should be due to faulty code. In this case it is good to be able to slow down the processing so we can examine each command being executed and check the values of the variables as the data in them changes. For learners, being able to see the execution sequence in such instances as which lines are skipped and which lines are executed in a If..Else or Select..Case construct or which group of lines are repeated in a loop construct would be helpful in the understanding of those constructs. In this chapter we shall concentrate how to examine the line by line execution of the programme code as well as checking the values of the variables at each stage of the execution. Breakpoints When we manually want to run a Visual Basic programme we simply click inside the code and then press F5. The programme will then run, executing one line after another at the rate of perhaps 500,000 lines per second until the programme finishes. The only interruptions to this would be if we used either an InputBox or Msgbox command in the code. In this case 61 Visual Basic for Applications

62 the execution would stop until we clicked the OK button on the dialogue boxes. Even though the programme execution would be halted by the commands mentioned we would not still be able to examine the code. In order to be able to do this we need to set a breakpoint in the programme before we run it. For our example we shall use the first programme that we wrote in Listing 2-1. in order to examine the code. We first list the programme itself as shown in Figure 9-1. We want to start examining the code at the line for calculating the gross. To do this we move to the grey area to the left of the edit area and click opposite the line for calculating the gross. This will result in a dark red circle to appear in the grey area and the line of code itself will be highlighted in the same colour as shown below in Figure 9-2. Our breakpoint is now positioned at this line. This means that the programme will run normally until it reaches the breakpoint. It will then stop and at this point we can examine the values of the variables that have been given values up until then. Figure Visual Basic for Applications

63 Figure 9-2 In order to try this out we simply press F5 as before. We shall be asked for the value of the hours in the first line of code and of the rate in the second line of code. After this the breakpoint will be reached. The execution of the programme will pause and the line for calculating the gross will be highlighted in yellow as shown in Figure 9-3. Figure 9-3 The highlighted line has not yet been executed and thus we can only examine the values of the variables snghours and currate. To examine the value of a variable you simply position the cursor over its name. In Figure 9-4 the cursor has been positioned over snghours and a small textbox appears below it, showing us its value. If we were to position the cursor over curgross, we would see that it has a value of zero because the highlighted line has not yet been executed and therefore the value of the gross has not been calculated. 63 Visual Basic for Applications

64 Figure 9-4 To execute the current line we press F8. This causes the execution of the line to occur and the yellow highlight will move on to the next line, indicating that it is now the line that is ready for execution. This is shown in Figure 9-5 below. Since the line for calculating the gross has been executed, when we put our cursor over curgross we can read its updated value. Figure 9-5 Pressing F8 again will cause the line for calculating the tax to be executed and will cause the highlight to move to the line for calculating the nett. This is shown in Figure 9-6 where we can read the value of the variable curtax. 64 Visual Basic for Applications

65 Figure 9-6 Similarly pressing F8 once more will execute the line for calculating the nett and allow us to check the value for curnett as shown below. Practice Figure 9-7 Copy Listing 7-1 into your code module and this time debug it instead of running it. To do this take the following steps: 1. Insert a breakpoint at line 9 - the first executable line. 2. Press F5 to start the programme running 3. To make the programme move from line to line press F8 Notice the control jumping to the functions and then returning back to the line that initially called the functions. Also ensure that you check the values calculated within the function 65 Visual Basic for Applications

66 bodies and also check that those values are passed back to the appropriate variables in the main programme.. Exercise Debug the programme you created for Error! Reference source not found. in the same way as you debugged Listing Visual Basic for Applications

67 10. File Processing Learning Outcomes On completion of this chapter you will know: The nature of a file How to open and close a file How to add data to a file and read data from it. Introduction Up to now we have managed to calculate a complete payroll and display all of the calculated data including the name of the employee whose salary we are calculating. We are not yet, however, able to keep a permanent record of our transactions and each time we calculate a new payroll the one that went before it is lost. Once we shut down Excel then even the last payroll that we calculated is lost. This is because all of our data has been stored in the computer s memory. By nature this is volatile. As an example of this volatility, each time we run a program the data in its variables is wiped out once the program stops running. Similarly when we turn the computer off all of the data in its memory is lost. In order to keep permanent record of our data we must save it to a file. Error! Reference source not found. below is an adaptation of our payroll programme where after each payroll calculation the data, instead of being written onto the Immediate Window is instead written to a file.. A file writing programme As stated above Listing 10-1 is an adaptation of our payroll programme. We have not included any of the functions that perform the calculations of the gross, tax etc, because we have not made any alteration to any of them. The first difference we see in Sub Pay is at line 12. Open Employees For Append As 1 This can be explained as open a file called Employees. If the file does not exist create it and then open it. If it already exists open it and go to the end of the file so we can append records to it. The file is to be opened on channel Visual Basic for Applications

68 Lines is a While loop which contains most of the body of Sub Pay. At line 13 a value is got for the variable strname. At line 14 this is tested for being blank. (When the InputBox dialogue box appears if you click on OK without entering any data into the text box then a blank will be stored in the variable strname.) If it is not a blank, or in other words if the user had entered an actual piece of text then the body of the While loop is entered at line 15. Here the normal processing we have been used to commences until line 23 is completed. In our previous version once the nett was calculated we printed the calculated values out on the screen. In this case, however, we write our calculated data to a file. Thus line 24 commences with Write # 1. This means write to the file that is opened on channel 1 the values of all of the variables that are listed on the rest of this line. These are the variables that contain the values for name and surname of employee, the hours, rate, gross, tax, superannuation and nett. Line 25 is the main read of the loop and the employee s name is prompted for. Line 26 then passes control back to the While at line 14 where the name is once more tested for being blank. Once a blank is received for the name control passes to line 27 where the file opened on channel 1, i.e. the file Employees, is closed.. If we run this programme and add a number of employees and their payroll details all of the data will be saved to this file Employees. If we now use Notepad to open this file the data will look as in Figure 10-1 Figure 10-1 Listing Sub Pay() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim curgross As Currency 5 Dim curtax As Currency 68 Visual Basic for Applications

69 6 Dim curnett As Currency 7 Dim cursuper As Currency 8 Dim intsupercode As Integer 9 Dim strname As String 10 Dim strsurname As String 11 Dim strfullname As String 12 Open "Employees" For Append As 1 13 strname = InputBox("Enter first name of employee") 14 While Len(strName) <> 0 15 strsurname = InputBox("Enter surname of employee") 16 snghours = InputBox("Enter Hours worked") 17 currate = InputBox("Enter Rate") 18 intsupercode = InputBox("Enter superannuation code") 19 strfullname = strname & " " & strsurname 20 curgross = calculategross(snghours, currate) 21 curtax = calculatetax(curgross) 22 cursuper = calculatesuper(intsupercode, curgross) 23 curnett = calculatenett(curgross, curtax, cursuper) 24 Write #1, strfullname, snghours, currate, curgross, curtax, cursuper, curnett 25 strname = InputBox("Enter first name of employee") 26 Wend 27 Close #1 28 End Sub Sub ReadData() 31 Dim strfullname As String 32 Dim snghours As Single 33 Dim currate As Currency 34 Dim curgross As Currency 35 Dim curtax As Currency 36 Dim curnett As Currency 37 Dim cursuper As Currency 38 Open "Employees" For Input As 1 39 Do 40 Input #1, strfullname, snghours, currate, curgross, curtax, cursuper, curnett 41 Debug.Print strfullname, snghours, currate, curgross, curtax, cursuper, curnett 42 Loop Until EOF(1) 43 Close #1 44 End Sub In Listing 10-1 we also have a programme for reading the data from the file. This programme spans lines Lines declare variables that are similar to those that were declared for Sub Pay. In fact, the variables declared at lines correspond with the data that was saved to the file at line 24. This is because at line 24 we wrote one String 69 Visual Basic for Applications

70 variable, one Single variable and five Currency variables to the file. When we read the file each data item must be stored in a variable. At line 38 we open the file. This time we open it for Input, which means that we are reading data from it instead of writing data to it. The reading of the data is controlled by a Do loop. At line 40 one String variable, one Single variable and five Currency variables are read form the file. These variables are printed to the screen at line 41. At line 42 we have the control for the loop. The syntax here needs some explanation. Firstly we need to examine in more detail how the data is written to the file at line 24. The Write # statement writes the content of each variable to the file and then puts a comma at the end of it before writing the contents of the next variable. When the contents of the last variable i.e. curnett, is written to the file Write # puts a linefeed character at the end to indicate that one complete record has been printed. This is why the contents of a file written by the Sub Pay above looks like the data shown in Figure In a file stored on disk, however, the data does not quite look like this, since all of the data is stored on a single track one record after another as shown in Figure 10-2 below.. Figure 10-2 When this file is opened for Input, as at line 37, a file pointer is positioned at the first character of the file, as shown above. Every open file also has a property called EOF which stands for end of file. As long as the file pointer is somewhere in the middle of the file, EOF is false. At line 39 the Input # command works as follows: 1. Data is read starting at the position of the file pointer and continues until the comma is met. This data is then stored in the variable strname. By now the file pointer is now positioned over the first character of smith 2. Data is read again, starting at the new position of the file pointer and continues until the next comma. This data is stored in strsurname. The file pointer is now positioned over the first digit of The digits of the number is now read and continues until the next comma. This data is stored in snghours. The file pointer has now moved on to the first digit of the next number. 70 Visual Basic for Applications

71 This process continues until data has been put into all of the variables in the list following Input #. By now the file pointer will be positioned above the first character in the second record, in other words above the m of mike. As there is more data left in the file EOF will still be false. Control will now pass to line 40 where the data is printed and then on to line 41 where we have the control of the loop. Here EOF is still false and the syntax Loop Unitl EOF means continue looping until EOF is true. Because of this control will pass back to line 40 where data is read once more beginning at the position of the file pointer and continuing until data has been put into the last variable. By now the file pointer will be positioned over the s of sam and EOF will still be false. The data will be printed out at line 41 again and since EOF is false control is passed back to line 39. Line 40 will now read the data as before, repositioning the file pointer as it reads. By the time the final piece of data is read into curnett the file pointer will be pointing just beyond the last item in the file in other words EOF will be true. Line 41 will print the data as before and then control passes to line 42 where the condition will now be false and thus the loop terminates and control passes to line 43, where the file is closed. Practice Copy the code in Listing 10-1 into your programme area. Ensure that the other functions for calculating the gross, tax etc are also copied into the same module. Now run the programme and add about four employees. Open the file with Notepad and check that the data is the same as that entered and that the programme calculated the values of the gross, tax, superannuation and nett before printing them to the file.. Finally run the programme once more in debug mode as shown in chapter 9 and check the values of the variables at each stage of the processing. Exercise 10 Modify the code you created in Exercise 8 so that instead of printing the text to the Immediate Window it prints it to a file. Next write another programme which reads each name from the file and prints it in the Immediate Window. 71 Visual Basic for Applications

72 Assignment Part 8 Modify the programme created for Assignment Part 7 so that on completion of each sale the data is written to a file called Sales as well as being printed on the screen. It s the same data that will be written to the file as was printed on the screen before. The simplest way to do this is to create a procedure called savedata. This will have exactly the same agruments as showdata, but instead of printing the data to the screen it saves it to the file Sales. You should be able to check that the data is written correctly by opening the file with Notepad and examining its contents Next write another programme that will open the file and read each record back and then print the data read. A While loop will control the reading of the data so that the code will be prevented from reading past the end of the file. 72 Visual Basic for Applications

73 Visual Programming Using Events 73 Visual Basic for Applications

74 11. Objects, Properties & Events Learning On completion of this chapter you will know: 1. What are objects 2. How objects are used to interface with the user 3. What properties of an object mean 4. How changing the property of an object can alter that object 5. The nature of events 6. How to use events to control the running of programme code 7. How programme code can alter the properties of objects Introduction Up to now we have not added any visual elements to our programming. The reason for this is that we wanted to concentrate on the programming concepts and techniques such as programme structure, use of Case structure etc without being distracted by visual elements. For this reason data was inputted into the programme using the InputBox function and the result of the processing was displayed in the Immediate Window. It is now time for us to look at forms and the controls that we can put on forms in order to create an interesting and dynamic interface for the computer user. After looking at the nature of forms and the objects we can place on them, we shall look at using a form to process a simple payroll application like the one we did in Chapter Visual Basic for Applications

75 A look at Forms Figure 11-1 You create a form in exactly the same way as you create a Module. Simply click on Insert and from the drop down menu click on Form. The form will appear as in Figure 11-1 above. The form itself is the grey rectangle with the dotted grid. In the bottom left corner we have the properties box. This shows the properties of form. A form has 35 properties altogether but only 11 of them are shown above. We never use the full 35 properties anyway in fact we rarely use any more than five properties of the form. The most commonly used ones are Name, Caption, Height and Width. As stated earlier, changing the properties of an object changes the object itself. Currently, referring to Figure 11-1, the Caption property has a value of UserForm1. We can see this by looking at the writing in the blue band at the top of the form. Also we can examine the value of the Caption property in the Properties box at the bottom left of the screen. The BackColor property is shown as grey and the Height property is shown as 180. Altering any of those properties will alter the appearance of the form. 75 Visual Basic for Applications

76 Figure 11-2 To alter the BackColor property we click on that property and then click on the downpointing arrow. This gives us a range of colours as shown in Figure 11-2 above. Simply selecting one of the colours will put that colour as the background colour of the form. Figure 11-3 below shows the form with the background colour changed to white, the Caption property changed to Sample form for teaching and the Height property changed to Visual Basic for Applications

77 Figure 11-3 The Textbox, Label and Command Button controls Textboxes, labels and command buttons are the most common controls that appear on forms, and they are the first that we will examine for creating an application. As stated above we shall use them in order to create a graphical version of the payroll example we used in Chapter 2. Figure 11-4 below shows a form with labels, textboxes and a single command button attached. To the right of the form is a panel which is labelled Toolbox. This panel is shown in more detail in Figure Let us examine this panel first as we shall be using it to get all of the controls that we place on the form. Here we are interested in only three controls, Label, Command button and Textbox. In order to create any of those controls on the form we simply click on the icon in the Toolbox and then draw that object on the form using the mouse. Figure 11-4 shows five labels, five textboxes and one command button drawn on the form. 77 Visual Basic for Applications

78 Figure 11-4 Figure 11-5 Now let us examine the form itself in Figure As stated earlier this form will be used to create a visual version of the payroll application we started with at the beginning of the book. At that basic level we started with the following data items: 1. Hours 2. Rate 3. Gross 4. Tax 5. Net 78 Visual Basic for Applications

79 In the programme we needed five variables to hold the values of those data items, we used the InputBox function to get data from the user for hours and rate and we used the Debug.Print function to display the values of the gross, tax and net in the Immediate Window. In the form we shall use the first two textboxes for the user to enter the values for the hours and rate and the final three textboxes to display the values of the gross, tax and net. The user will enter hours and rate into the first two textboxes, and then click on the command button. This will run the code behind the form. This code will read the values in the first two textboxes, perform the calculation and then display the gross, tax and net in the last three textboxes. This means that the textboxes will be referred to in the code. Because of this we need to give them meaningful names. We could, of course, call them Hours, Rate, Gross, Tax and Net and the programme would work perfectly with those names. However when naming textboxes, or any other controls on the form that will be referred to in the code we follow the same convention as we did with naming variables, i.e. the first three letters of the name describes the type of control we are naming. As we are naming textboxes, those three letters will be txt. Thus our five textboxes will be named txthours, txtrate, txtgross, txttax and txtnet. The command button is used to run the code that calculates the pay and thus it should be named cmdcalculate. There is no need to name the labels to the left of the textboxes since they will not be referred to in the code. Figure 11-4 shows the first textbox and, from the properties window, we can see that it is named txthours. As stated the labels to the left of the textboxes need not be named but their Caption properties have to be changed in order to describe the textboxes to the right. Thus their Caption properties have been altered to Hours, Rate, Gross, Tax and Net. Creating and running Code in a Form Finally we shall look at the command button and how we can use it to create and run the code. If your display is as in Figure 11-4 then double click on the command button. Once you do this your display will change to that shown in Figure 11-6 below, except that at this stage you should not have the procedure calculatepay. Also, if instead of Private Sub cmdcalculate_cick, you have Private Sub CommandButton1_Click then you have forgotten 79 Visual Basic for Applications

80 to name your command button. If this occurs then return to the form by using View/Object, then name the command button and double click on it once more to return to the Code view. Figure 11-6 The area between Private Sub cmdcalculate_cick and End Sub should be blank. We could insert the code for calculating the pay here and it would work fine. From the point of view of overall programme design, this is not a good idea. The reason is that if the same code had to be run from a different form then we would have to enter the same code into the click event of that form. If we once put the code into a separate procedure and then call it from the click event of our button, then if we need to use the same procedure elsewhere we simply call from the click event of the other form control and have no need to make a second copy of it. The complete code is shown both in Figure 11-6 and, for clarity, in Listing 11-1 and Listing The code in lines 1 3 hardly needs explaining. Line 1 indicates that it is the click event of the command button and line 2 calls the procedure Sub calculatepay. Listing Private Sub cmdcalculate_click() 2 calculatepay 3 End Sub 80 Visual Basic for Applications

81 Listing Sub calculatepay() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim curgross As Currency 5 Dim curtax As Currency 6 Dim curnet As Currency 7 snghours = Val(txtHours.Text) 8 currate = Val(txtRate.Text) 9 curgross = snghours * currate 10 curtax = curgross * curnet = curgross - curtax 12 txtgross.text = curgross 13 txttax.text = curtax 14 txtnet.text = curnet 15 End Sub Sub calculatepay is shown in Listing If we compare this code to that in Listing 3-1 we see that the two pieces of code are almost identical. The only differences are in lines 7 and 8 and lines 12, 13 and 14. In the example in Chapter 3 the values were given by the user through the two InputBox functions. In our current example the user enters the values for hours and rate in the textboxes txthours and txtrate. When we run the procedure calculatepay, it reads the values we have entered into those two textboxes. In line 7 we have: snghours = Val(txtHours.Text) The textbox txthours is the place where we put the value of the hours worked by an employee. One of the properties of a textbox is the Text property. When we first load up the form all of the textboxes are blank. This means that their Text properties are null. Once we enter something into the textbox via the keyboard the Text property changes. Thus if we entered 20 as the value of the hours worked, then the Text property of txthours would change to 20. Similarly entering 10 into the textbox txtrate would cause the Text property of that box to change to 10. Note that even though we enter numeric characters once they are in the textbox they are treated as text. Thus when the code in line 7 reads the Text property of txthours it reads text data and not numeric data. Before this is stored in the variable snghours it must be converted to numeric format. The Val function does this for us. Thus the sequence of events in line 7 is: 1. The Text property of txthours is read 2. The Val function converts this property into a number 3. This number is stored in the variable snghours The exact same logic applies to line Visual Basic for Applications

82 Now let us have a look at how the results of the calculation are displayed on the form. Remember that the user did not enter any data into the textboxes txtgross, txttax or txtnet. Thus their Text properties are null. The programme, however, can not only read these properties, it can also change it. Thus in order to display the value of the gross at line 12 the programme sinply changes the Text property of txtgross to the value of the variable curgross. The values of the tax and net are displayed in their respective textboxes in exactly the same way. Figure 11-7 below shows what the form would look like after calculating pay, where 20 hours were worked at a rate of K10 per hour. Events an Introduction Figure 11-7 In the example above we used the procedure cmdcalculate_click in Listing 11-1in order to call the procedure calculatepay in Listing The former procedure is generated by the system itself. We can read its name as the Click event off the control cmdcalculate.. Events are things that happen. In programming they are things that happen to controls placed on forms. There are many types of events that can happen to many types of controls. Later we shall be looking at more of those events but for now we concentrate on the click event off commandbuttons. The click event of a particular object occurs whenever we use the mouse to click on that object. Thus if we have a button named cmdcalculate on a form and we click on it then the Click event of cmdcalculate occurs. What this means is that a procedure named cmdcalculate_click will run. 82 Visual Basic for Applications

83 Modes of a Form Forms have two modes: Design Mode and Form Mode. The Design Mode is used when we are designing a form i.e. when we are adding labels, textboxes, etc. to it. We attach code to it also in the same mode. Thus the form we see in Figure 11-1 to Figure 11-4 is in the Design Mode. Once we have completed our design and run the application by pressing F5, then we see the form as in Figure This version of the form is the Form View. This is the view in which we can processs that data that the form was designed for in the first place. Summary A form is an easy way for a programme and a user to communicate. This communication is normally done through the different controls that are on the form. The most common controls are Textboxes, Labels and Command Buttons. In the example shown in Figure 11-7 the textboxes are used both for the user to communicate with the programme and for the programme to communicate with the user. The user communicates with the programme by entering the values of hours and rate into the textboxes txthours and txtrate. The command button is also for the user to communicate with the programme. Once the user clicks on the command button the code in the Click event of that button runs. Practice Part 1 Create a form like that shown in Figure Add labels, textboxes and a command button and name them as they are named above. Next double click on the command button to get into the code part of the form. Now copy into it the code from Listing 11-1 and Listing Check that the programme runs correctly. Part 2 Modify the code for Part 1 as follows: 1. Create an extra textbox that will hold the employee s full name. Name the textbox appropriately 2. Alter the programme code so that the employee s name is stored in a string variable. 3. Add an extra button to the form for saving the payroll data to a text file named Workers. The code will have the following steps: 83 Visual Basic for Applications

84 Exercise 11 a. The file is opened in Append mode. b. The contents of the textboxes are written to the file c. The file is closed. 1. Write a description of a Form. In your work pay attention to how the form can be used for input and output of data. Also mention the different objects that can be placed on the form and their uses. 2. What are the Visual Basic conventions for naming textboxes, and command buttons. 3. Explain how to get a code running by clicking on a command button. Assignment Part 9 Create a form to process the same data you were processing in Assignment Part 8. Here there is no addition to the processing. Instead you will create a form which will receive the input data from the user. It then performs the same processing as before. Some of the output will, however be different. Instead of printing the results to the Immediate Window it will instead print them to the appropriate text boxes of the form. From above you should be able to work out that the form must contain textboxes for all of the input items as well as for all of the outputs that are listed in showdata. It must also contain a command button on whose click event the procedure Sales will run. The following alterations must be made to the procedure Sales: 1. The While loop structure has to be removed. 2. All of the lines that use the InputBox function have to be altered so that they read their data from the form s textboxes instead. The only other alteration that needs to be made to the code is that the procedure showdata will display its data in the appropriate textboxes of the form instead of printing them to the Immediate Window. The same test data can be used here as was used for Part Visual Basic for Applications

85 12. More Events Learning Outcomes On completion of this chapter you will know: The nature of the events, Activate, Change, Enter and Exit How those events can be used to automate the running of an application. Introduction In chapter 11 we looked at the Click event of the command button control. In the code this was designated as cmdcalculate_click. This event occurs when we click on that command button with the mouse. Similarly if we had a button named cmdsave, then the code for the click event of that button would be cmdsave_click. The Click event is not restricted to command buttons. Most other objects you place on a form also have a Click event, including labels and textboxes. If you wish to know all of the events that are attached to the controls on your form, then go to the code window and from the left combo box at the top of your code window select the control you wish to examine. From the events list box to the right, click on the down pointing arrow. This will display the list of events attached to the control you selected. This is shown in Figure 12-1 below. The Change, Enter and Exit events Figure 12-1 When browsing the internet or even using a word processor or a spreadsheet we see things appearing and disappearing on the screen the whole time without any effort on our part. These notices and images that appear are caused by events that are attached to objects within the applications we are dealing with or else to the Windows operating system itself. 85 Visual Basic for Applications

86 We wish to make our form as professional looking as possible and also to make it as easy as possible for the user to use the form s controls correctly. As an example of this, when the user has selected the textbox txthours in order to enter data into it, we would like some instruction to appear somewhere on the form to instruct the user as to what values for hours he is supposed to enter. On the other hand when the user has left this textbox and has gone to another one we would like this message to disappear since the message applies only to txthours. In order to do this we use the Enter and Exit events of the textbox. The Enter event occurs when we click on the textbox or move into it in any other way. Thus we can put into the procedure attached to this event the code for making the instructions appear. The Exit event occurs when we leave the textbox and move somewhere else. Again we use code within the procedure attached to this event to remove the instructions. As well as providing instructions to the user we would also like the form to automatically calculate the pay details for us while we are adjusting the value of either hours or rate. In order to do this we use the Change event of the appropriate textboxes. The Change event of a textbox occurs when the Text property of that textbox changes, in other words when we use any keyboard key while that textbox has the focus. In our case we will put a call to calculatepay into the Change events of the textboxes txthours and txtrate. In Listing 12-1 below we have the code that controls the Change, Enter and Exit events for the textboxes txthours and txtrate. Lines 1 7 control the Change events while lines 9 23 control the Enter and Exit events. Listing Private Sub txthours_change() 2 calculatepay 3 End Sub 4 5 Private Sub txtrate_change() 6 calculatepay 7 End Sub 8 9 Private Sub txthours_enter() 10 frmpaydemo.caption = "Value for hours must be in the range 5-40" 11 End Sub Private Sub txthours_exit(byval Cancel As MSForms.ReturnBoolean) 86 Visual Basic for Applications

87 14 frmpaydemo.caption = "Payroll demo - using a Form" 15 End Sub Private Sub txtrate_enter() 18 frmpaydemo.caption = "Value for rate must be in the range 2-10" 19 End Sub Private Sub txtrate_exit(byval Cancel As MSForms.ReturnBoolean) 22 frmpaydemo.caption = "Payroll demo - using a Form" 23 End Sub Let us now look at the events referred to and see how they control the processing of the payroll. We shall begin with the Change events. In a textbox a change occurs whenever the value of the Text property is changed. Thus adding a single character to the textbox or removing one causes a Change event to occur. As an example entering the value 16 into txthours causes the Change event to occur twice, once for entering 1 and a second time for entering 6. Each time the Change event of this textbox occurs, the code in lines 1 3 is run. This code simply calls the procedure calculatepay which both calculate the pay and updates the other 3 textboxes. The exact same logic applies to the code in lines 5 7. This group of lines control the Change event of txtrate whenever the user enters data into that textbox. Before we look at the code for the Enter and Exit events we must first examine the idea of the active control on a form. As a spreadsheet user you are familiar with the concept of the active cell. This is the cell in the worksheet where you can enter data. If you want to enter data into another cell, you must first make that cell the active cell. The same concept applies to textboxes and other controls on a form. In the form shown in Figure 11-7 above we have five textboxes. At any time only one of those textboxes can be the active one, i.e. only one of them can receive data from the keyboard. If we want to enter data into any other textbox we must first make that the active textbox, usually by clicking on it using the mouse. If txthours was the active textbox and if we made txtrate the active textbox by clicking on it with the mouse, then two things would happen, one after the other: the focus would shift from txthours and the focus would shift to txtrate. This would mean that two events would occur the Exit event of txthours and the Enter event for txtrate. Again, if we were to shift the focus back to txthours then two events would occur again: the Exit event for txtrate and the Enter event for txthours. 87 Visual Basic for Applications

88 As can be seen from the code in lines 9 23 above code can also be added to the Enter and Exit events. The code for those events, however, is not involved in processing the payroll data. Instead is it used to help the user use the form correctly. Thus if the hours had to be a number in the range 5 40 and the rate had to be in the range 2 10, then, when the cursor was in txthours we should give some indication to the user that the value entered is to be in the range To do this we attach code the Enter event of the textbox i.e. the event txthours_enter or lines 9 11 above. The code here alters the Caption property of the form to Value for hours must be in the range Of course this piece of information must be visible only when the focus is on txthours. Once the focus shifts to another control then the Caption property of the form must revert to the default value of Payroll demo - using a Form. This is done in the Exit event of txthours as shown in lines above. The code for the Enter and Exit events of txtrate uses the same logic as above. Figure 12-2 More Controls Checkbox, Option Button and Frame Next to textboxes, the next most common controls used to interact with a computer user are checkboxes and option buttons. The checkbox control is used to indicate a true/false or yes/no situation. In the case of our payroll application we may use a checkbox to indicate whether an employee is a member of a trade union or not. We can use this information to decide whether to deduct union fees from his pay or not. In Figure 12-3 below we have another illustration of the toolbox with the Checkbox, Frame and OptionButton icons highlighted. 88 Visual Basic for Applications

89 Figure 12-3 Of the properties of a checkbox we shall be using only three: Name, Caption and Value. The Name and Caption properties should be familiar to you by now but the property Value is new. This property is of Boolean type and therefore can only hold values true or false. The property Value is true if the checkbox is checked i.e. if there is a checkmark inside it - and false if the checkbox is blank. The option button is somewhat similar to the checkbox, in that it is also used to indicate a true/false situation. Again we shall be using the same three properties: Name, Caption and Value. Despite their initial similarities, there are fundamental differences between the checkboxes and the option buttons. The main difference is that while the checkboxes are independent of each other, option buttons can be processed only as a group. Thus, in a group of checkboxes any number of boxes can be checked and unchecked. On the other hand in a group of option buttons only one button can be checked at any one time all other buttons in the group must be unchecked. It is common to put option buttons inside a frame in order to emphasise the fact that they form a group. If a form has only one group of option buttons then there is no actual need, apart from emphasising clarity, for putting them inside a frame. On the other hand if a form has more than one group of option buttons and each group is meant to be independent of each other then the different groups must be placed in side individual frames. Apart from separating groups of option buttons from each other, another advantage of putting a number of related objects inside a frame is that if we wish to make the group invisible, we only need to make the frame invisible and everything inside it will also become invisible. The properties of the Frame control that we shall be using are Name, Caption and Visible. 89 Visual Basic for Applications

90 For a practical example of the difference between checkboxes and option buttons we shall look at extending our form application in order to include union fees and superannuation. An employee may or may not be a union member, i.e. it is a true/false situation. A checkbox can represent this situation for us. This checkbox will have a Name of chkunion, and a Caption property of Union Member. At the moment those are the only properties of the checkbox that we need to change. The Value property will be altered during the running of the programme, simply be clicking on the checkbox. Referring to the superannuation situation, the same concept applies to it either the employee pays superannuation or he doesn t. Again a checkbox will illustrate this situation for us. The Name and Caption properties of this checkbox will be chksuper and Superannuation. The superannuation situation, however, is a little more complex than the union one. With the union, if a person is a union member he pays K10 as a flat fee, while a non-union member pays no fees. On the other hand if an employee is a superannuation member then he has the option of paying either 5%, 10% or 15% of his gross towards his superannuation contributions. Clearly he has to select one of those options and again he can select only one of the options. This situation lends itself perfectly to using option buttons. For our application we shall have three option buttons whose Name properties will be opt05, opt10 and opt15. Their Caption properties will be 5%, 10% and 15%. Those option buttons will be inside a Frame control whose Name will be frmsuper and whose Caption will be Super Rate. Next we look at keeping unnecessary controls off the form. As an example if an employee is not a union member there is no need for the textbox txtunion to be visible. Similarly if the employee does not pay any superannuation contributions then neither txtsuper or frmsuper should be visible. We manage this by making those three controls invisible at the beginning. Then if the user clicks on either of the checkboxes then the Visible property of the three controls can be turned on or off depending on whether the checkbox in question is checked or unchecked. These new controls are displayed below in Figure 12-4, while the code that controls the extended form is shown in Listing Visual Basic for Applications

91 Figure 12-4 Listing Sub calculatepay() 2 Dim snghours As Single 3 Dim currate As Currency 4 Dim blnunion As Boolean 5 Dim curunionfees As Currency 6 Dim blnsuper As Boolean 7 Dim sngsuperrate As Single 8 Dim cursuper As Currency 9 Dim curgross As Currency 10 Dim curtax As Currency 11 Dim curnet As Currency 12 snghours = Val(txtHours.Text) 13 currate = Val(txtRate.Text) 14 blnunion = chkunion.value 15 blnsuper = chksuper.value 16 If blnunion Then 17 curunionfees = Else 19 curunionfees = 0 20 End If 21 If blnsuper Then 22 If opt05.value Then 23 sngsuperrate = ElseIf opt10.value Then 25 sngsuperrate = Visual Basic for Applications

92 26 ElseIf opt15.value Then 27 sngsuperrate = End If 29 Else 30 sngsuperrate = 0 31 End If 32 curgross = snghours * currate 33 curtax = curgross * cursuper = curgross * sngsuperrate 35 curnet = curgross - curtax - curunionfees - cursuper 36 txtgross.text = curgross 37 txttax.text = curtax 38 txtunion = curunionfees 39 txtsuper = cursuper 40 txtnet.text = curnet 41 End Sub Private Sub chksuper_click() 44 txtsuper.visible = chksuper.value 45 frmsuperrate.visible = chksuper.value 46 calculatepay 47 End Sub Private Sub chkunion_click() 50 txtunion.visible = chkunion.value 51 calculatepay 52 End Sub Private Sub opt05_click() 55 calculatepay 56 End Sub Private Sub opt10_click() 59 calculatepay 60 End Sub Private Sub opt15_click() 63 calculatepay 64 End Sub Private Sub txthours_change() 67 calculatepay 68 End Sub Private Sub txtrate_change() 71 calculatepay 72 End Sub Private Sub txthours_enter() 75 frmpaydemo.caption = "Value for hours must be in the range 5-40" 92 Visual Basic for Applications

93 76 End Sub Private Sub txthours_exit(byval Cancel As MSForms.ReturnBoolean) 79 frmpaydemo.caption = "Payroll demo - using a Form" 80 End Sub Private Sub txtrate_enter() 83 frmpaydemo.caption = "Value for rate must be in the range 2-10" 84 End Sub Private Sub txtrate_exit(byval Cancel As MSForms.ReturnBoolean) 87 frmpaydemo.caption = "Payroll demo - using a Form" 88 End Sub We shall not go through the code from top to bottom order as we normally do. Instead we shall first look at the new code for controlling the checkboxes and option buttons and then we shall look at the adjusted code for calculating the pay. We first look at the code for controlling the click event of chksuper. This code spans lines At first glance you might wonder what on earth is going on. Firstly chksuper_click indicates that this is the piece of code that runs when the user clicks on the check box chksuper. When you click on a checkbox you alter its appearance. If the checkbox was blank then a tick appears inside it, or, if a tick was already there then it goes blank. As we stated earlier, if a tick appears inside a checkbox then its Value property is true, whereas if it is blank then its Value property is false. Thus clicking on a checkbox alters its Value property between true and false. If the employee we are dealing with is a superannuation contributor then want the textbox txtsuper and the option buttons inside the frame frmsuperrate to be visible whereas if the employee is not a superannuation contributor then we want those controls to be invisible, since they are not needed. If an control s Visible property is true then the control is visible whereas if it s Visible property if false then the control is invisible. Line 44 changes the textbox txtsuper to be either visible or invisible. The way it does this is that it reads the Value property of chksuper and copies this value into the Visible property of txtsuper. Thus if chksuper has a tick inside it, its Value property is true. This causes the Visible property of txtsuper to be true as well which means that txtsuper will be visible. The same logic applies to line Visual Basic for Applications

94 On the other hand if chksuper is blank, i.e. if it has no tick inside it then then its Value property is false. This means that the employee does not pay any superannuation and therefore we don t need either txtsuper or the frame frmsuperrate. For this reason we wish to make them invisible by changing their Visible properties to false. Here we have an example of the same piece of code performing two opposite actions i.e. it may make two controls either visible or invisible depending on whether a checkbox is either checked or unchecked. Finally line 46 calls calculatepay. This needs to be done since altering the fact that an employee pays or doesn t pay superannuation contributions will alter how the pay is calculated. The same logic applies to the Click event of chkunion, which spans lines and for this reason we will not elaborate on it here. Figure 12-5 below shows how a form would look when the employee pays neither superannuation or union fees. The code for the Click events of the three option buttons spans lines This code here is very simple since selecting any one of those buttons effects only the calculation of the pay and does not affect any other control on the form. For this reason all the click events do is to call the procedure calculatepay. The code in lines has already been dealt with, and therefore we will not discuss it here. We need however to look at calculatepay since there are significant changes made to it regarding the calculation of the union fees and superannuation contribution. These changes span lines In lines 14 and 15 the Value properties of the checkboxes chkunion and chksuper are read into the Boolean variables blnunion and blnsuper. Lines is a simple If..Else construct which puts either zero or 10 into the variable curunionfees, depending on the value off blnunion. Lines control the calculation of superannuation. This is a more complex structure since it contains nested If constructs. Line 21 tests the value of blnsuper. If its value is true then the nested If that spans lines is executed. This structure tests the Value property of each of the option buttons to check which one of them has a value of true and updates the value off the variable sngsuperrate accordingly. 94 Visual Basic for Applications

95 If the value of blnsuper is false then lines are skipped and only line 30 is executed, which puts a value of zero into sngsuperrate. At line 35 we have a change to the calculation of then net since both union fees and superannuation contributions are now subtracted from it. Figure 12-5 Practice Create a form as shown in Figure Name the controls as appropriate. Next copy the code in Listing 12-2 into the form. Of that listing you should only copy the procedure calculatepay. The rest of the code should be generated from the appropriate events of the controls on the form. Exercise 1. Explain when the Change event occurs 2. Explain how the Enter and Exit events are used here to control instructions regarding what is to be entered into textboxes. 3. The Click event applies only to textboxes! True or false? 4. Sub cmdcalculate_click. What does the name of this procedure mean? 95 Visual Basic for Applications

96 Assignment Part 10 Alter your form from Assignment Part 9 to that shown below. Notice that the textbox txtdiscountcode is missing. This is because the entry of the discount code is now done through the option buttons at the right of the form. Figure 12-6 Now the calculation of the sales details are performed on the Change events of the text boxes that hold the amount sold and the unit price and on the Change events of the four option buttons. During those calculations no data is saved to the text file Sales. Data is saved to this file only when the Save button is clicked. 96 Visual Basic for Applications

97 VB for Apps Excel 97 Visual Basic for Applications

98 13. Macros Learning Outcomes On completion of this chapter you will know: How to record and play back macros How to modify the code of a macro How to combine a number of macros into one macro. Introduction Macros are a way of automating repetitive tasks within a spreadsheet or a word processing application. The idea is that instead of repeating the same set of operations time after time, we set the macro recorder on, perform the tasks once with the macro recorder recording them, and finally save the macro. From now on all we need to do is to play back the macro and our tasks are performed automatically for us. Macros are, in fact, Visual Basic code that the system writes automatically while it is recording our actions in the workbook. As Visual Basic programmers we can modify this code in any way we want as long as we stay within the correct syntax of the Visual Basic language. In this course the most frequent use we will be making of it is to copy sections of it into more general purpose programmes. Creating an Excel Macro To create a macro in Excel we simply turn on the macro recorder. To do this we go to the View tab and in the Macros group click on Macros. From the drop down list we select Record Macro. We then perform the tasks we want recorded. Once finished we stop the recorder. We do this in the same way that we started the recorder in the first place except that instead of clicking on Record Macro we click on Stop Recording. 98 Visual Basic for Applications

99 Figure 13-1 In Figure 13-2 below we have an example that we looked at in another course for calculating the interest and repayments on a bank loan. If entering this manually the steps would be: 1. Select cell B1 and enter the text Jan into it 2. Autofill this across to G1 3. Enter the text items Opening Balance, Interest, Repayment and Closing Balance into the range A2:A5 4. Enter Interest Rate into cell A8 5. Adjust the column width of A to accommodate the text items it contains. 6. Enter the values 0.12, 10000, and 700 into the cells B8, B2 and B4 respectively 7. Enter the formula =B2*$B$8/12 into cell B3 in order to calculate the monthly interest 8. Enter the formula =B2+B3-B4 into cell B5 in order to calculate the closing balance for the first month 9. Enter the formula =B5 into cell C2 in order to calculate the opening balance for the second month 10. Autofill this formula across to column G 11. Select cell B3 and copy its formula across to column G using Autofill 12. Select cell C4 and enter the formula =B4 into it. 13. Copy this formula across to G4 14. Select cell B5 and copy the formula in it across to G5 15. Select the range B2:G5 and format it for PNG currency 16. Select cell B8 and format it for percentage. 99 Visual Basic for Applications

100 Now let us examine the code in Listing 13-1 and see how it performs the above steps for us. Figure 13-2 Listing Sub BankSetup() 2 Range("B1").Select 3 ActiveCell.FormulaR1C1 = "Jan" 4 Selection.AutoFill Destination:=Range("B1:G1"), Type:=xlFillDefault 5 Range("A2").Select 6 ActiveCell.FormulaR1C1 = "Opening Balance" 7 Range("A3").Select 8 ActiveCell.FormulaR1C1 = "Interest" 9 Range("A4").Select 10 ActiveCell.FormulaR1C1 = "Repayment" 11 Range("A5").Select 12 ActiveCell.FormulaR1C1 = "Closing Balance" 13 Range("A8").Select 14 ActiveCell.FormulaR1C1 = "Interest Rate" 15 Columns("A:A").EntireColumn.AutoFit 16 Range("B8").Select 17 ActiveCell.FormulaR1C1 = "0.12" 18 Range("B2").Select 19 ActiveCell.FormulaR1C1 = "10000" 20 Range("B3").Select 21 ActiveCell.FormulaR1C1 = "=R[-1]C*R8C2/12" 22 Range("B4").Select 23 ActiveCell.FormulaR1C1 = "700" 24 Range("B5").Select 25 ActiveCell.FormulaR1C1 = "=R[-3]C+R[-2]C-R[-1]C" 26 Range("C2").Select 27 ActiveCell.FormulaR1C1 = "=R[3]C[-1]" 28 Selection.AutoFill Destination:=Range("C2:G2"), Type:=xlFillDefault 29 Range("B3").Select 30 Selection.AutoFill Destination:=Range("B3:G3"), Type:=xlFillDefault 31 Range("C4").Select 100 Visual Basic for Applications

101 32 ActiveCell.FormulaR1C1 = "=RC[-1]" 33 Range("C4").Select 34 Selection.AutoFill Destination:=Range("C4:G4"), Type:=xlFillDefault 35 Range("B5").Select 36 Selection.AutoFill Destination:=Range("B5:G5"), Type:=xlFillDefault 37 Range("B2:G5").Select 38 Selection.NumberFormat = "[$PGK] #,##0.00" 39 Range("B8").Select 40 Selection.NumberFormat = "0.00%" 41 End Sub Step 1 is performed by the code lines 2 and 3. The command Range("B1").Select is equivalent to clicking on the cell B1 or moving into it using the arrow keys. The command ActiveCell.FormulaR1C1 = "Jan" is equivalent to typing the text Jan into the active cell. Step 2 is performed by code line 4. The value supplied to the range must include the cell which contains the data we want autofilled as well as the end cell of the range we want it copied into. Steps 3 and 4 are performed by code lines As the logic is the same as for step 1 we don t need to elaborate on it here. Step 5 is performed by code line 15 Step 6 is performed by code lines 16, 17, 18, 19, 22 and 23. Notice that the code enters numeric values as if they were text. Step 7 is performed by lines 20 and 21. Formulae are entered using code in quite a different way to how they are entered manually. Manually the formula would be entered in cell B3. B2*$B$8/12. Now let us look at the formula in relation to the cell B3. Cell B2 is one row above B3 and the reference to cell B8 is absolute addressing. Thus the coder version of the formula R[-1]C*R8C2/12 can be read as multiply the cell one row above the current cell by the cell in row 8 column 2 and divide the result by 12 Step 8 is similar in logic to the step above. Manually the formula entered into B5 is B2+B3- B4. B2 is 3 rows above B5, B3 is 2 rows above it and B4 is 1 row above it, thus R[-3]C+R[- 2]C-R[-1]C can be read as add the cell 3 rows above the current one to the cell 2 rows above it and subtract the cell one row above it from the result. Step 9, which is performed in lines 26 and 27, is similar in logic to the above step 101 Visual Basic for Applications

102 Step 10 is performed in line 28 and uses the AutoFill we have discussed before. Steps are performed in lines contain code already familiar to us. Step 15 is performed in lines 37 and 38 Step 16 is performed in lines 39 and 40. Using Macro Code as part of a general Visual Basic application In Listing 13-1 we have seen Visual Basic code for: 1. Selecting cells and ranges 2. Entering data into cells 3. Entering formulae into cells 4. Using the AutoFill feature 5. Widening columns 6. Formatting ranges This code is not confined to macros only. Parts of it can be copied and used as part of a general Visual Basic application running within Excel. Even within a macro the code can be modified to perform actions differently to how the macro was originally recorded. As an example of editing existing macro code we shall look at altering Listing 13-1 so that instead of copying formulae across to column G it copies them across to column M. Here is one example: Selection.AutoFill Destination:=Range("B5:G5 ) This copies whatever is in cell B5 into the range B5:G5. We can easily alter it to copy the data as far as column M by altering to code to Selection.AutoFill Destination:=Range("B5:M5 ) If all of the other destination ranges are altered accordingly then the altered macro will create a 12 month application instead of a 6 month one. 102 Visual Basic for Applications

103 14. Spreadsheet Components coded in VB Learning Outcomes On completion of this chapter you will be familiar with how to manipulate the most commonly used components of a spreadsheet using VB code. Introduction All of the code you have done so far could be run inside Access, Word and PowerPoint. This is because we have concentrated on programming code and techniques alone without reference to the application inside which the code would be run. From now on you are going to be using VB code in order to manipulate spreadsheet components that up to now you have manipulated manually. These manipulations can be as simple as moving from one worksheet to another by clicking on it or as complex as adding a number of new worksheets to the workbook and naming them. It can also involve adding or deleting columns or rows, entering data into ranges and formatting ranges. As we have discovered in Chapter 13 any manipulation you can do manually, can also be done using code. Workbook, ThisWorkbook The Workbook object represents an actual Workbook. You cannot work with the Workbook itself, you have to create a variable that points to it and work with that variable. Once you create such a variable it can be used to point to any workbook that you have opened. It cannot point to a workbook that is stored on the disk. Normally, however, it is used to point to the workbook that contains the code itself. This workbook has a special name ThisWorkbook. In all of our examples here we shall be dealing only with the workbook which contains the code and thus we shall be using ThisWorkbook in almost all of our code. When dealing with Forms and the controls that could be placed on them we discovered that the forms and their controls had properties and that we could manipulate those controls by either reading or altering the values of those properties. Similarly all of our worksheet components also have properties. Like the form controls they have more properties than we will ever use and so we shall be looking at a very small number of those properties. Some of the properties of a Workbook include Name, FullName and Path. 103 Visual Basic for Applications

104 As well as properties, a Workbook also has Collections. A Collection is an object in its own right and has its own properties. As its name implies a Collection is an object that can deal with a number of items of the same type. In a non-programming environment a school could be seen as an object. This School object would have the following collections: Teachers, Students, Classrooms, Buildings etc. A Vehicle object would have a Wheels collection. Of the collections that we will be using in this course we shall be using two of their properties: Count and Add. If a school had 50 teachers working in it then we could have a line of code that would be: Kambubu.Teachers.Count = 50 If we wanted to select the first teacher we would use: Kambubu.Teachers(1)= Mr Wagi Finally if we wanted to add a new teacher we would use: Kambubu.Teachers.Add ( Joe Bloggs ) Listing 14-1 below is a short example of how to manipulate a workbook and its properties. Listing Sub workbookexperiment() 2 Dim wb As Workbook 3 Dim intcounter As Integer 4 Set wb = ThisWorkbook 5 Debug.Print "The name of the workbook is ", wb.name 6 Debug.Print "The number of worksheets is ", wb.worksheets.count 7 Debug.Print "The names of the worksheets are" 8 For intcounter = 1 To wb.worksheets.count 9 Debug.Print wb.worksheets(intcounter).name 10 Next 11 End Sub In lines 2 and 3 we declare our varibles: our Workbook variable in line 2 and a loop counter in Line 3. In line 4 we specify that the variable wb is to point to the workbook that we are working with. Line 5 prints out the string constant The name of the workbook is followed by the Name property of the current workbook. 104 Visual Basic for Applications

105 Line 6, as well as printing a string constant, also prints the Count property of the Worksheets collection of the current workbook. Finally lines 8, 9 and 10 is a For loop that prints out the name of each Worksheet object in the Worksheets collection. A sample output of the programme is shown below. The name of the workbook is Sample Sheet for VB training.xlsm The number of worksheets is 7 The names of the worksheets are Employees Payroll Timesheets Macro Recording examples Workers List Stock Sales Listing Sub addmanysheets() 2 Dim wb As Workbook 3 Set wb = ThisWorkbook 4 wb.worksheets.add Count:=5 5 End Sub The code above uses the Add method in order to add new worksheets to the workbook. The Add method on its own will simply add one worksheet but in this case we also have the argument Count:=5. This tells it to add five worksheets instead of one. Listing Sub addsheettoworkbook() 2 Dim wb As Workbook 3 Set wb = ThisWorkbook 4 wb.worksheets.add 5 wb.activesheet.name = "New Sheet" 6 End Sub Listing 14-3 above adds only a single sheet at line 4. Once a new sheet is added to the workbook that sheet automatically becomes the active sheet. Because of this line 5 can change the Name property of the new sheet to New Sheet Listing Sub shownames() 105 Visual Basic for Applications

106 2 Dim wb As Workbook 3 Set wb = ThisWorkbook 4 Debug.Print wb.name 5 Debug.Print wb.fullname 6 Debug.Print wb.path 7 End Sub Listing 14-4 above simply prints out the Name, FullName and Path properties of the current workbook. The output is shown below. By examining this we can see that the property FullName is simply the Path property with the Name property added on to it. Sample Sheet for VB training.xlsm D:\VB for apps\sample Sheet for VB training.xlsm D:\VB for apps Activesheet, Cells, Selection, Range, Rows, Columns Most of the work done in a spreadsheet is on the worksheets themselves. It is here that we add, modify, read and remove data. Even though a workbook may have up to 255 worksheets we can only work on one sheet at a time, in exactly the same way that we can only read a book one page at a time. The sheet that we are working on in a workbook is referred to as the active sheet. In VB for Applications the active sheet is pointed to by ActiveSheet. An example of how to use it is shown below in Listing Listing Sub activesheetdemo1() 2 Dim wb As Workbook 3 Set wb = ThisWorkbook 4 wb.worksheets("new Sheet").Activate 5 With ActiveSheet 6.Cells(1, 1) = "Hello everyone" 7.Cells(1, 2) = "This is the new sheet that I have created" 8 End With 9 End Sub The code in lines 2 and 3 should be familiar by now so we begin with line 4. This line could be translated into English as search the worksheets in the current workbook and make the one named New Sheet the active one. Lines 5 8 is a With..End With construct. We have not met this construct before and thus we need to spend some time explaining what it is all about. Earlier we have mentioned that 106 Visual Basic for Applications

107 all spreadsheet objects such as Worksheet, Workbook etc have properties. Many of those properties have their own properties, and those properties can have their own properties! Thus you could easily end up with a piece of code that would look as follows: Listing Application.Workbooks(1).Worksheets(2).Cells(2,3) = Application.Workbooks(1).Worksheets(2).Cells(2,4) = Application.Workbooks(1).Worksheets(2).Cells(2,5) = 16. The first line of this code inserts the value 12 into the cell C2 of the second worksheet, of the first workbook that is opened in Excel. The second and third lines insert the values 14 and 16 into the cells D2 and E2 of the same worksheet. These are very long lines of code to be writing, especially if there is a lot of data to be inserted. Within Visual Basic we can avoid this tedious and messy construction using the With construct. This would alter our code to the following: Listing With Application.Workbooks(1).Worksheets(2) 2.Cells(2,3) = 12 3.Cells(2,4) = 14 4.Cells(2,5) = 16 5 End With Here we only need to write the long line Application.Workbooks(1).Worksheets(2)only once after the keyword With. Between this line and the line End With, if we meet a line that begins with a period then VB presumes that the rest of that line should be appended to the piece of code that follows the keyword With. Thus as far as Visual Basic is concerned Listing 14-6 is identical to Listing In the example below we look at the Range and Selection objects as well as at the properties Rows and Columns properties Listing Sub activesheetdemo2() 2 Dim wb As Workbook 3 Dim introw As Integer 4 Dim intcol As Integer 5 Set wb = ThisWorkbook 6 wb.worksheets("new Sheet").Activate 107 Visual Basic for Applications

108 7 With ActiveSheet 8.Range(Cells(3, 4), Cells(12, 15)).Select 9 For introw = 1 To Selection.Rows.Count 10 For intcol = 1 To Selection.Columns.Count 11 Selection.Cells(intRow, intcol) = introw * intcol 12 Next 13 Next 14 End With 15 End Sub This application creates a multiplication table in the worksheet named New Sheet. The first seven lines of the code should be familiar to you by now, so we begin with line 8. This uses the Range property of the active sheet. This property is similar to the Range that we refer to when doing normal spreadsheeting. Both versions of the word simply mean a rectangular group of cells. In normal spreadsheeting we refer to a range as D3:O12 in other words we specify the cell at one corner of the range and the cell at the diagonally opposite corner. In VB for Applications we can refer to a range in the same way, but this limits us to always using the same range. On the other hand if we refer to it as we do in line 8 then we can extend or alter our range as we wish. In line 8 the Range has two parameters: Cells(3,4) and Cells(12,15). Cells(3, 4) means the cell where row 3 meets column 4 in other words cell D3. Similarly Cells(12, 15) means the cell where row 12 meets column 15 i.e. cell O12. Thus line 8 is equivalent to saying select the range D3:O12 in the active sheet. In the worksheet it has the same effect as holding the mouse button down over D3 and dragging as far as O12. Line 9 is the start of a For loop. The lowest range for the loop is 1 and the upper range is determined by Selection.Rows.Count. The selection referred to here is the selected range D3:O12. As the selection spans rows 3 to 12 then the number of rows in it is 10. Line 10 is the start of a nested For loop inside the first one. The lowest range for this is 1 and the upper range is determined by Selection.Columns.Count. This is like the previous one except that this time it is the number of columns in the selection that it gives us. Since the selection spans column 4 to 15 inclusive the value of Count in this case is 12. Line 11 is where the processing of the loops occur. The values of introw and intcol are multiplied and inserted into the cell of the selection determined by the values of the two counters. As an example, the first time through both loops both introw and intcol will have 108 Visual Basic for Applications

109 a value of 1 each. Thus the value to be entered into the cell will be 1 multiplied by 1, which is one. The cell it will be entered into will be the cell in the first row and first column of the selection which is cell D3. The inside loop will not increment intcol to 2 while introw stays at 1. Thus the value 2 will be inserted into the cell of the selection where the first row intersects the second column, i.e. cell E3. Figure 14-1 shows the result of running the programme. Practice Figure Copy Listing 14-1 into your programme area and run it. Check that the correct name of the workbook, the correct number of worksheets and the correct names of all of the sheets are printed out. Add a few extra sheets and rename a few more. Now run the programme again and check that the new output reflects the change you have made to the workbook 2. Copy Listing 14-2 into the programme area and run it. Check that it has added five extra worksheets to the workbook. 3. Modify Listing 14-3 so that it adds four new worksheets in turn and names them Cash at Bank, Accounts Receivable, Accounts Payable, Stock 4. Copy listing Listing 14-5 into your programme area and run it. Check that it inserts the two text items into the first two cells of row 1. Once it is performing correctly, modify it so that different text or numeric values are entered into other cells. You can be as inventive as you wish. 5. Modify Listing 13-1 so that instead of using the two steps of selecting a cell and then using the FormulaR1C1 to enter data into the cells it uses the ActiveSheet.Cells(row, col) method. 109 Visual Basic for Applications

110 15. Using a Form to interact with a Worksheet Learning Outcomes On completion of this chapter you will know: How to use forms in order to activate other forms How to use code on a form to activate different worksheets How to insert columns or delete columns using code The objects Workbook, Activesheet The collection Worksheets What are the major processing that occur to data Introduction Spreadsheet users frequently use their spreadsheets as a database, in other words they use them to store large volumes of data. The main problem of using this is that a spreadsheet has very limited capabilities of checking or validating the data that is being entered. It is also limited in how it can protect the data. Some of those problems can be overcome by entering the data under programme control. To do this we enter the data into a form and then use code attached to the form to check and validate the data before storing it in the worksheet. At first we shall look at a simple application for entering, modifying and browsing the data and then we shall look at a small example of how programme code can be used to validate the data being entered. Data Processing Add, Modify, Delete and Browse When dealing with data stored in a computer the only processing available to us are add, modify, delete and browse. If we have an application for processing student data in an educational institution then we normally add new data when we register new students. In other words we add new student records. 110 Visual Basic for Applications

111 When we alter details of existing students then we are modifying existing data. This may involve changing a student s surname due to the student getting married or correcting any other data item that had been entered wrongly. Deleting records is not the most frequently performed operation as we normally like to keep records of as many past events as we can. Browsing is done either by moving from record to record or by searching the data for a student id. Normally browsing does not involve changing the data. Using a Form as a Switchboard The application we are about to demonstrate will have four components: 1. Entering data records 2. Modifying existing data 3. Deleting records 4. Browsing the existing data All of those four activities will be carried out by separate forms. In order to unify the application we shall have a main form, from which we can activate the other four forms. The form is shown below in Figure 15-1 Figure 15-1 The form s name is frmmainmenuform. It has four command buttons named cmdadd, cmdbrowse, cmddelete and cmdmodify. Below is shown the code attached to each of those buttons. 111 Visual Basic for Applications

112 We need to examine only one of those pieces of code. We shall examine the first one, i.e. cmdadd_click which spans lines 1 3. Line 2 of this procedure calls the Show method of frmaddnewemployees. What this does is to display the named form on the computer screen so that we can use it to enter data into our workbook. While this form is on display we cannot use either the spreadsheet itself or any other form that was active before. Listing Private Sub cmdadd_click() 2 frmaddnewemployees.show 3 End Sub 4 5 Private Sub cmdbrowse_click() 6 frmbrowseemployees.show 7 End Sub 8 9 Private Sub cmddelete_click() 10 frmdeleteemployees.show 11 End Sub Private Sub cmdmodify_click() 14 frmmodifyemployee.show 15 End Sub Adding Data using a Form The form for adding data is shown below in Figure It has four text boxes named txtname, txtsurname, txtjobdescription and txtrate. It also has one command button named cmdadd. The code for the form is shown in Listing It will add the data in the textboxes to a worksheet named Workers List shown below in Figure This already has labels inserted across Row 1. The first record will be added into row 2. before the next record is added a new row is inserted at Row 2 thus pushing down the previous record. The new data is entered into the new Row 2. This process continues for all records added. Thus the most recent record is at the top and the oldest record is at the bottom. 112 Visual Basic for Applications

113 Figure 15-2 Figure 15-3 Listing Dim wb As Workbook 2 3 Private Sub UserForm_Activate() 4 Set wb = ThisWorkbook 5 wb.worksheets("workers List").Activate 6 End Sub 7 8 Private Sub cmdadd_click() 9 Rows("2:2").Select 10 Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove 11 ActiveSheet.Cells(2, 1).Value = txtname.text 12 ActiveSheet.Cells(2, 2).Value = txtsurname.text 13 ActiveSheet.Cells(2, 3).Value = txtjobdescription.text 14 ActiveSheet.Cells(2, 4).Value = txtrate.text 15 End Sub The code above is listed in the order in which the different procedures are run. The first procedure, i.e. that which spans lines 3 6, is run on the Activate event of the form. The Activate event of a form occurs just before the form appears on the screen in Form mode. In 113 Visual Basic for Applications

114 the procedure for this event it is common practice to put code that sets up the environment for the application to run successfully. In our case, since we are to put our data into the worksheet Workers List we first ensure that that worksheet is the active one. The first step here is to ensure that the variable wb points to the workbook that we are using. This occurs in line 4 In line 5 we activate the worksheet Workers List. The logic of the line is equivalent to Of all the worksheets in the current workbook select the one named Workers List and make it the active sheet Manually we would activate the same sheet by clicking on it. The code for actually adding the data to the current worksheet is included in the click event of the command button cmdadd, which spans lines As stated earlier data is added to the worksheet by inserting a blank row just above the current row 2 and inserting the data into the newly created blank row. Line 9 selects the current row 2. (Manually this would be done by clicking on the 2 in the row header bar.) Line 10 inserts an extra row at row 2 and pushes all other rows down one place. This leaves a blank row into which data can be entered. This is done in lines The method of entering data into the worksheet s cells is different from the method used in Listing 13-1 In this case the cells are identified by their row/column coordinates. Thus in line 11 the code piece ActiveSheet.Cells(2, 1) means the cell the second row and the first column meet. This clearly refers to cell A2. Similarly in line 12 ActiveSheet.Cells(2, 2) means where the second row and the second column meet which means cell B2. Thus lines insert the contents of the four textboxes on the form into the cells A2, B2, C2 and D Visual Basic for Applications

115 Modifying existing Data using a Form Figure 15-4 The form for modifying existing data is shown above. It contains the same four textboxes as the form for adding new data but the buttons are different. The names of the current buttons are cmdnext and cmdmodify. The processing of the data is more complex than that for adding new data. When adding new data we only needed to insert a blank row at row 2 and then copy the contents of our four textboxes into the first four columns of the new row 2. For modifying the data we must first display the data in the textboxes. If the user wishes to change the data he makes the alterations in the textboxes and then clicks the Modify button, which writes the data back to the worksheet. If the user does not wish to modify the record on display then he clicks the Next button in order to move to the next record. Thus our processing must be capable of doing the following: Displaying data on the form s textboxes Moving from one record to the next one Saving the contents of the textboxes back to the worksheet. Listing 15-3 below shows the code Listing Dim wb As Workbook 2 Dim intcurrentrecord As Integer 3 4 Private Sub UserForm_Activate() 115 Visual Basic for Applications

116 5 Set wb = ThisWorkbook 6 wb.worksheets("workers List").Activate 7 intcurrentrecord = 2 8 showdata 9 End Sub Private Sub cmdmodify_click() 12 ActiveSheet.Cells(intCurrentRecord, 1).Value = txtname.text 13 ActiveSheet.Cells(intCurrentRecord, 2).Value = txtsurname.text 14 ActiveSheet.Cells(intCurrentRecord, 3).Value = txtjobdescription.text 15 ActiveSheet.Cells(intCurrentRecord, 4).Value = txtrate.text 16 End Sub Private Sub cmdnext_click() 19 intcurrentrecord = intcurrentrecord showdata 21 End Sub Private Sub showdata() 24 If ActiveSheet.Cells(intCurrentRecord, 1).Value = "" Then 25 MsgBox "No records to display" 26 intcurrentrecord = intcurrentrecord Else 28 txtname.text = ActiveSheet.Cells(intCurrentRecord, 1).Value 29 txtsurname.text = ActiveSheet.Cells(intCurrentRecord, 2).Value 30 txtjobdescription.text = ActiveSheet.Cells(intCurrentRecord, 3).Value 31 txtrate.text = ActiveSheet.Cells(intCurrentRecord, 4).Value 32 End If 33 End Sub In the global area of the form we have declared two variables this time: wb and intcurrentrecord. The second variable is to be used for indicating which record in our list we are currently dealing with. The value of intcurrentrecord will be the number of the row whose contents we are currently looking at or modifying. The first procedure to run is the code attached to the Activate event of the form. This spans lines 4 9. The first two lines of code are identical to those of the code in Listing 15-2 and perform the same function. 116 Visual Basic for Applications

117 In Line 7 we set the value of intcurrentrecord to 2 and in the next line call the procedure showdata in order to display the contents of the first four columns of row 2. The next procedure is the Click event of cmdmodify. This is almost identical to the procedure cmdsave_click from Listing 15-2 in that it writes the contents of the four textboxes of the form back to the worksheet. The only difference is that this time the value of the variable intcurrentrecord is used to determine into which row the data is written. The next procedure is the Click event of cmdnext. The code here simply moves the focus to the next employee record and displays the data. Thus the first action at line 19 is to increase the value of intcurrentrecord and then call the procedure showdata. The procedure showdata itself spans lines The body consists of an If..Then..Else construct. Line 24 tests if the first column of the row we are about to display is a blank. (this would occur if either there were no records in the worksheet to begin with, or, more likely, if continuous pressing of the Next button had moved us past the end of the data. If cell is blank then lines 25 and 26 are executed and the rest of the procedure is skipped. On the other hand if the cell is not blank then there is data to display and the body of the Else is executed i.e. lines This is simply the reverse of the cmdmodify_click above in that the contents of the first four columns of the row pointed to by intcurrentrow are copied to the four textboxes on the form. Deleting Records The form that controls the deleting of records is very different from any of the other forms we have used in this example. It is shown in Figure 15-5 below. It has only two controls: a list box and a command button. The list box is named lstnames and the command button is named cmddelete. A list box is similar to a combo box in that it has a list of items and the user can select any one of those items simply by clicking on that item. In order for the programme to work out which item is selected the list box has a property called ListIndex. This is an integer and it gives the sequence number of the item selected. One thing to remember regarding the ListIndex property is that it starts counting at zero. Thus if the name Harry Potter is selected from the list below then ListIndex will have a value of zero. Similarly if Dick Smith is selected then ListIndex has a value of 1, while, if Tom Thumb is selected it has a value of 2. Finally if none of the items are selected then ListIndex has a value of Visual Basic for Applications

118 The sequence of our processing will be as follows: 1. The form loads 2. The Activate event will read the first two columns of each row of data, i.e. the name and surname, and add those to the list of lstnames. Once those two steps are accomplished the user is presented with something that looks like Figure 15-5 below. Now let us examine the code that got us this far as well as the code that runs when we click on the button cmddelete. Listing 15-4 Figure Dim wb As Workbook 2 Dim intcurrentrecord As Integer 3 4 Private Sub UserForm_Activate() 5 Set wb = ThisWorkbook 6 wb.worksheets("workers List").Activate 7 loadnames 8 End Sub 9 10 Sub loadnames() 11 Dim strfullname As String 12 lstnames.clear 13 intcurrentrecord = 2 14 While ActiveSheet.Cells(intCurrentRecord, 1).Value <> "" 15 strfullname = ActiveSheet.Cells(intCurrentRecord, 118 Visual Basic for Applications

119 1).Value & " " & ActiveSheet.Cells(intCurrentRecord, 2).Value 16 lstnames.additem strfullname 17 intcurrentrecord = intcurrentrecord Wend 19 intcurrentrecord = intcurrentrecord End Sub Private Sub cmddelete_click() 23 Dim intlistindex As Integer 24 intlistindex = lstnames.listindex 25 If intlistindex = -1 Then 26 MsgBox "No name selected from list" 27 Else 28 intcurrentrecord = intlistindex ActiveSheet.Rows(intCurrentRecord).Select 30 Selection.Delete Shift:=xlUp 31 loadnames 32 End If 33 End Sub We will examine the procedures in the code section above in the order in which they are run once the form loads. Obviously the first to run will be UserForm_Activate, which spans lines 4 8. Lines 5 and 6 work in the same way as they did for all of the other forms we have examined and so we will leave them alone. Line 7 calls the procedure loadnames. The procedure loadnames spans lines Line 11 declares a String variable strfullname which will hold the values of the first two columns of whichever row we are examining. Thus, if we were dealing with a worksheet like that in Figure 15-2 above, and if we were at row 3, then strfullname would be Dick Smith. Line 12 uses the Clear method of the list box in order to remove any items that may be there already. Line 13 sets the value of intcurrentrecord to 2 so that we can begin searching our list beginning at row 2. Lines consist of a While loop. Line 14 itself tests if the first cell of the current row has got a value in it. If it does then line 15 will read the values in the first and second cells of the current row, put a space between them and store the result in the variable strfullname. Line 16 uses the AddItem method of the listbox in order to add the value of strfullname to the box s list. 119 Visual Basic for Applications

120 Line 17 increases the value of intcurrentrecord by 1 so we can examine the next row of the worksheet. Line 18 throws control back to line 14 where the first cell in the new row is tested for being blank. If it is then control passes to line 19 where intcurrentrecord is reduced by 1 so that it will point at the last record in the worksheet. Finally we look at the Click event of cmddelete. This spans lines It uses the ListIndex property of the list box and thus we need to explain it here before proceeding with examining the code. If we look at Figure 15-5 we see a list box with three names, Harry Potter being the first, Dick Smith the second and Tom Thumb the third. If the user clicked on Harry Potter then the ListIndex property would have a value of 0, while if he clicked on Dick Smith then ListIndex would have a value of 1. Clearly it would have a value of 2 if the user clicked on Tom Thumb. Looking again at Figure 15-5 we see that none of the three names are selected, which means that ListIndex has a value of -1. Returning back to our code we can examine how the ListIndex property is used by the procedure in order to remove a record from the worksheet. At line 23 a variable intlistindex is declared as an integer. Its name clearly indicates that it will be used to store the value of the ListIndex property of the list box and in line 24 that s what exactly happens, the value of ListIndex is copied directly into intlistindex. The rest of the code, i.e. lines 25 32, consist of an If..Else..EndIF construct. In line 25 the value of intlistindex is tested for having the value of -1, in other words testing whether an item has been selected from the list box. If the test is false, i.e. if an item has been selected from the list then the Else part of the construct is executed. At line 28 intcurrentrecord is valued as intlistindex + 2. The reason for this is that the listbox starts to count at zero, while in the worksheet the first record begins at row 2. Thus in order to find the record in the worksheet that corresponds to the item selected from the list we simply add 2 to the value of ListIndex. Line 29 selects the row where the record to be deleted is in while line 30 runs the code for removing that row from the worksheet. Once the record has been removed from the worksheet there is no longer a direct correspondence between the data in the worksheet and the list of lstnames. This is because 120 Visual Basic for Applications

121 lstnames still holds a reference to the record that has been deleted. Thus, in order to have a one-to-one correspondence between the two again we must call loadnames at line 31. Scope of Variables Before continuing with examining the data processing we must pause and consider a concept that has been introduced in Listing 15-4 without being mentioned. This is the concept of global and local variables. A global variable, as the name implies, is visible to every procedure in the application while a local variable is visible only inside the procedure in which it is declared. If we look at the first two lines of Listing 15-4 we see that two variables are declared wb and intcurrentrecord. Those two variables are declared outside of all of the procedures and for this reason all procedures can see them. The variable intcurrentrecord is used in the procedures loadnames and cmddelete_click. On the other hand cmddelete_click declares its own variable intlistindex at line 23. Because this variable has been declared inside the procedure it is visible only between the lines 22 and 33 and is invisible to every other procedure in the application. Thus cmddelete_click can see the variable intcurrentrecord because it is declared outside of all the procedures and it can see intlistindex because it is declared inside the procedure itself. Similarly the procedure loadnames declares the variable strfullname at line 11. Thus this procedure can see both intcurrentrecord, again because it is declared global, and it can see its own variable strfullname. Again strfullname can only be seen between the lines 10 and 20. Browsing the Data Browsing data in a file means being able to move from one record to another, both from the beginning towards the end and backwards. One must also be able to jump directly to the first record and the last record. When designing the code for such an application one must also ensure that the user is not allowed past either the first record or the last one. Thus, referring to the small example in Figure 15-2 the user should not be allowed to browse above row 2 or below row 4. Below is the form we are using for browsing. The four textboxes are named as their predecessors were while the four command buttons are named cmdfirst, cmdlast, cmnext and cmdprevious. 121 Visual Basic for Applications

122 Also it is common in an application that allows browsing of records, that when the application starts up the first record is actually displayed. Listing 15-5 shows the code behind the form. Figure 15-6 Listing Dim wb As Workbook 2 Dim intcurrentrecord As Integer 3 Dim intlastrecord As Integer 4 5 Private Sub UserForm_Activate() 6 Set wb = ThisWorkbook 7 wb.worksheets("workers List").Activate 8 intcurrentrecord = 2 9 intlastrecord = 1 10 While ActiveSheet.Cells(intCurrentRecord, 1).Value <> "" 11 intcurrentrecord = intcurrentrecord Wend 13 intlastrecord = intcurrentrecord intcurrentrecord = 2 15 If intlastrecord <> 1 Then showdata 16 End Sub 17 Private Sub cmdfirst_click() 18 If intlastrecord <> 1 Then 19 intcurrentrecord = 2 20 showdata 21 End If 22 End Sub 122 Visual Basic for Applications

123 23 24 Private Sub cmdlast_click() 25 If intlastrecord <> 1 Then 26 intcurrentrecord = intlastrecord 27 showdata 28 End If 29 End Sub Private Sub cmdnext_click() 32 If intlastrecord <> 1 And intcurrentrecord <> intlastrecord Then 33 intcurrentrecord = intcurrentrecord showdata 35 End If 36 End Sub Private Sub cmdprevious_click() 39 If intlastrecord <> 1 And intcurrentrecord > 2 Then 40 intcurrentrecord = intcurrentrecord showdata 42 End If 43 End Sub 44 Sub showdata() 45 With ActiveSheet 46 txtname.text =.Cells(intCurrentRecord, 1) 47 txtsurname.text =.Cells(intCurrentRecord, 2) 48 txtjobdescription.text =.Cells(intCurrentRecord, 3) 49 txtrate.text =.Cells(intCurrentRecord, 4) 50 End With 51 End Sub In lines 1 3 we have our global variable declaration. This time, however, we have an extra variable, intlastrecord. The reason for this variable is that the code will need to know where the last record in the worksheet is. Therefore our first job, once we have activated the worksheet, will be to search down through the worksheet, counting the rows as we go down, until we reach an empty row. Once we reach this we will have counted one row more than we have records and therefore we subtract 1 from our counter to give us the position of the last record in our worksheet. What we have just described is part of the processing that occurs in in UserForm_Activate. So now let us look at this procedure in detail. The procedure itself spans lines 5 to 16 it s the longest version of it that we have had so far. Lines 6 and 7 should be familiar by now and so we shall start with line 8. Here we set intcurrentrecord to 2. The variable is therefore pointing to the first row of the worksheet where we store our data Visual Basic for Applications

124 Line 9 sets our new variable intlastrecord to 1. There is no data in row 1, only the labels and thus intlastrecord having a value of 1 means that there are no records in the worksheet. Lines is a While loop. The first time through the loop intcurrentrecord will have a value of 2. Thus line 10 will test if the value of cell(2,1), i.e. cell A2 is blank. If it is not then intcurrentrecord is incremented by 1 and line 12 will throw control back to line 10 where now cell(3,1) i.e. A3 is tested for being blank. This process continues until the first blank cell is found in column A. Once a blank cell is found then the condition at line 10 will be false and control will pass to line 13. Here intlastrecord is given the value of the number of the last row in the worksheet that contains data. Line 14 sets the value of intcurrentrecord to 2, or in other words it is pointing to the first row in the worksheet that contains data. Line 15 tests if the value of intlastrecord is not 1 and if this is the case then showdata is called. Next we shall look at the code for displaying the first record cmdfirst_click. This procedure spans lines The body is an If..End If structure. Line 18 tests if intlastrecord is not equal to 1, i.e. that there are records in the worksheet to display. If there are records to display, i.e. if intlastrecord is some value other than 1, then intcurrentrecord is set to 2 i.e. the first record in the worksheet and then showdata is called to display the contents of that record. The code for finding the last record spans lines The logic is exactly the same as that for finding the first record. The only difference is in line 26 where intcurrentrecord is set to the value of intlastrecord, so that showdata will display the contents of the last record. The code for finding the next record spans lines The logic here is slightly more complex than the two procedures we already have examined. The body of the procedure is still an If..End IF structure but the condition of the If at line 32 is more complex. As well as testing if there are records to display, i.e. if intlastrecord is not equal to 1, it also tests that intcurrentrecord is not equal to intlastrecord. The reason for this second test is that if intcurrentrecord has the same value as intlastrecord, it means that we are already at the end of the data and that there is no more data to display. The body of the If construct is therefore only executed if intlastrecord has a value greater than 1 and intcurrentrecord is less than intlastrecord. If both of those conditions are true then the body of the structure is executed i.e. intcurrentrecord is incremented by 1 and the procedure showdata is called. 124 Visual Basic for Applications

125 The code for moving to the previous record spans lines Logic is similar to the procedure we have just described except that in line 39 the second condition is that intcurrentrecord is greater than 2. The reason for this second condition is that if intcurrentrecord already has a value of 2 then we are already at the first record and we cannot go above it. Apart from this the rest of the logic is the same. Finally the procedure showdata, which spans lines 44 51, displays the data in the form s textboxes. It does this by copying the contents of the first four cells of the current row into the textboxes txtname, txtsurname, txtjobdescription and txtrate. Practice Create the five forms discussed in this chapter and add the appropriate controls to each form. Ensure that the controls are named appropriately. Now copy the code belonging to each form. Finally run the application and check that it performs each task correctly. Assignment Part 11 Once again you have to modify the previous part of the assignment, this time Part 10. Once you have finished you will have a simple version of the software that supermarkets use at the checkouts. There are two major functions that this software performs: it calculates the customer s total purchases and it also updates the stock file. In order to function the software is attached to a database file, which contains details of the stock that the supermarket holds. Among those details are: description of the stock, its unit price and the amount of that item in stock. Whenever a customer s purchase is passed over the scanner the following processing occurs: 1. The record for that stock item is accessed in the database file 2. Its unit price is read and is added to the customer s total 3. The amount in stock for that item is reduced by 1 This assignment is, of course, a very simplified version of the one the supermarkets use. However, by completing this assignment, you will have gained knowledge of the programming techniques required for creating a major piece of software to be used in commercial data processing. The specifications for this assignment are: 125 Visual Basic for Applications

126 1. Add two worksheets to your workbook and name them Sales and Stock respectively. The sheet Stock will contain details of the stock the supermarket holds and should look as Figure 15-7 below. The sheet Sales will record the sale of each individual stock item in exactly the same way as the text file recorded it up to now. Of course you may still update the text file, along with the worksheet, as one will act as a crosscheck on the other. 2. On the form the textbox txtdescription will be replaced with a combo box named cmbdescription. On the Activate event of the form the Stock sheet is activated and the contents of Column A are added to the list of the combo box cmbdescription. Check Listing 15-4 to see how this is done. 3. When processing a sale the user first enters the customer name. Next he selects an item from the drop down list of the combo box. On the Change event of this control the appropriate record is accessed in the file Stock and the unit price is read and is placed in the textbox txtunitprice. 4. The user then enters the amount of that item that has been purchased into the textbox txtamtsold. 5. To record this sale the user clicks the Save button. This causes the contents of the form s text boxes to be written to the worksheet Sales. Refer to Listing 15-2 to find out how to do this. Next the appropriate record in the Stock file is accessed and the amount of the item sold is subtracted from the current stock figure. You may wish, as stated earlier, to also write the contents of the form s text boxes to the text file that you have used up to now. Figure Visual Basic for Applications

127 Introduction 16. Appendix UserForm Practice Exercises The applications included here are for the purpose of introducing the beginner to the concept of forms and the variety of controls that can be placed on the form. It also deals with properties and events both of the form itself and also of the controls that are placed on it. Feel free to alter or expand any of those applications or create different versions of them. The more you do this the more familiar you become with form controls, and their events and properties. Change Event of Textboxes As the textboxes on this form contain no special data other than a value that is twice the value of the textbox above them, they were left with their default names: Textbox1 etc. The sole purpose of this application is the demonstrate how the Change event of a textbox can be used. The Change event of a textbox occur whenever the contents of that textbox changes. This includes: putting data into a blank textbox, deleting the contents of a textbox that already has data in it, or modifying its contents. The Change event occurs whether the contents are altered by hand, i.e. by clicking inside the textbox and using the keyboard keys to alter its contents, or else it occurs if the contents of a textbox are altered by computer code. In our case both sets of circumstances will cause the Change event to occur. 127 Visual Basic for Applications

128 1 Private Sub TextBox1_Change() 2 TextBox2.Text = Val(TextBox1.Text) * 2 3 End Sub 4 5 Private Sub TextBox2_Change() 6 TextBox3.Text = Val(TextBox2.Text) * 2 7 End Sub 8 9 Private Sub TextBox3_Change() 10 TextBox4.Text = Val(TextBox3.Text) * 2 11 End Sub Private Sub TextBox4_Change() 14 TextBox5.Text = Val(TextBox4.Text) * 2 15 End Sub Enter and Exit Events of Textboxes As textboxes for at least 80% of the controls we use on a form we shall look at a few more of their events Enter and Exit this time. The Enter event occurs once a textbox is selected. A textbox is selected in the following ways: 1. Being clicked with the mouse 2. Using the Tab key 3. Using programme code. The Exit event of a textbox occurs in the following ways: 128 Visual Basic for Applications

129 1. When another control is selected using the mouse 2. When the Tab key is used to move to the next control 3. When programme code is used to move to another control In the application below we use the two events in order to control prompts to the user on what kind of data is to be entered into the textboxes. In the diagram below the textbox txtname has the focus: we can see this by the fact that the cursor is flashing inside it. To the left is a label with instructions on what to put into the textbox. The contents of this label appliy only to the textbox txtname and would be downright wrong and unhelpful if they were visible when another textbox had the focus. For this reason when the textbox loses its focus i.e. when its Exit event occurs we must put code into that event to blank out the contents of the listbox. When a textbox loses the focus in our example it can only move to another textbox. Once it moves to this new textbox we must provide instructions on what is the correct data for this textbox. We therefore use its Enter event to write the appropriate text message into the label on the right. Finally the textboxes here are named txtname, txtaddress, txtage and txtoccupation. The label to the right is named lblmesssage. 1 Private Sub txtaddress_enter() 2 lblinstruction.caption = "Enter a person's address. Either post office box number, place of employment or address will do" 3 End Sub 4 5 Private Sub txtaddress_exit(byval Cancel As MSForms.ReturnBoolean) 129 Visual Basic for Applications

130 6 lblinstruction.caption = "" 7 End Sub Private Sub txtage_enter() 11 lblinstruction.caption = "Enter the person's age. If this is unknown enter 'No record of birth'" 12 End Sub Private Sub txtage_exit(byval Cancel As MSForms.ReturnBoolean) 15 lblinstruction.caption = "" 16 End Sub Private Sub txtname_enter() 19 lblinstruction.caption = "Enter a person's name and surname. Middle names must also be included" 20 End Sub Private Sub txtname_exit(byval Cancel As MSForms.ReturnBoolean) 23 lblinstruction.caption = "" 24 End Sub Private Sub txtoccupation_enter() 27 lblinstruction.caption = "Enter a person's occupation. If no occupation then enter 'unemployed'" 28 End Sub Private Sub txtoccupation_exit(byval Cancel As MSForms.ReturnBoolean) 31 lblinstruction.caption = "" 32 End Sub Combobox and Listbox Properties and Events Next to textboxes and command buttons, combo boxes and list boxes would form the next 10% of the controls we use. In the next exercise we look at how to add items to the lists of those boxes and also how to read the values of the items we select from their lists. The form below has a combo box named cmbdemo and a list box named lstdemo. The textbox is called txtdata and the two buttons are named cmbaddtocombo and cmbaddtolist. The label at the bottom is named lblmessage. In order to add data to either the combo box or list box we first enter the data into the textbox txtdata and then click on either of the command buttons. 130 Visual Basic for Applications

131 In order to see which item we have selected from either the combo or list boxes we select the item and the Change event of that control will write a message in the label indicating which item from the list the user has selected. In our case below its telling us that the user has selected the item Harry from the list box. 1 Private Sub cmbdemo_change() 2 lblmessage.caption = "The combobox's selected item is " & cmbdemo.text 3 End Sub 4 5 Private Sub cmdaddtocombo_click() 6 If txtdata.text <> "" Then cmbdemo.additem txtdata.text 7 End Sub 8 9 Private Sub cmdaddtolist_click() 10 If txtdata.text <> "" Then lstdemo.additem txtdata.text 11 End Sub Private Sub lstdemo_change() 14 lblmessage.caption = "The list box's selected item is 131 Visual Basic for Applications

132 " & lstdemo.text 15 End Sub Change Event of Option Buttons As you can see from the above illustration we are using pictures in our forms now! As we have not used Image controls in our forms before, we must say a few words about then here. An image is a control that you can display an image file such as a.jpg file inside it. Just like any other control you put on a form the Image control has properties such as Name, Height, Width, Visible etc. we shall be using the properties mentioned here as well as the Picture 132 Visual Basic for Applications

133 property. This property can only be used in Design mode and it allows us to add a picture to the image. Apart from the image the main purpose of this application is to test the Change events of option buttons. 1 Private Sub OptionButton1_Change() 2 Image1.Visible = OptionButton1.value 3 End Sub 4 5 Private Sub OptionButton2_Change() 6 Image2.Visible = OptionButton2.value 7 End Sub 8 Private Sub OptionButton3_Change() 9 Image3.Visible = OptionButton3.value 10 End Sub Change Event of Checkboxes 133 Visual Basic for Applications

134 1 Private Sub chkamanwriting_change() 2 picamanwriting.visible = chkamanwriting.value 3 End Sub 4 5 Private Sub chkayoungman_change() 6 picayoungman.visible = chkayoungman.value 7 End Sub 8 9 Private Sub chkportraitofawoman_change() 10 picportraitofawoman.visible = chkportraitofawoman.value 11 End Sub Private Sub chkwomanwithaveil_change() 14 picawomanwithaveil.visible = chkwomanwithaveil.value 15 End Sub 134 Visual Basic for Applications

135 16 17 Private Sub picawomanwithaveil_mousedown(byval Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) 18 With picawomanwithaveil 19 showhide.tag, False 20.Visible = True 21.Height = Width = top = left = End With 26 End Sub Private Sub picawomanwithaveil_mouseup(byval Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) 29 With picawomanwithaveil 30.Height = Width = top = left = showhide.tag, True 35 End With 36 End Sub Private Sub picamanwriting_mousedown(byval Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) 40 With picamanwriting 41 showhide.tag, False 42.Visible = True 43.Height = Width = End With 46 End Sub Private Sub picamanwriting_mouseup(byval Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) 49 With picamanwriting 50.Height = Width = showhide.tag, True 53 End With 54 End Sub Private Sub picayoungman_mousedown(byval Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) 135 Visual Basic for Applications

136 57 With picayoungman 58 showhide.tag, False 59.Visible = True 60.Height = Width = top = left = End With 65 End Sub Private Sub picayoungman_mouseup(byval Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) 68 With picayoungman 69.Height = Width = top = showhide.tag, True 73 End With 74 End Sub Private Sub picportraitofawoman_mousedown(byval Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) 77 With picportraitofawoman 78 showhide.tag, False 79.Visible = True 80.Height = Width = top = left = End With 85 End Sub Private Sub picportraitofawoman_mouseup(byval Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) 88 With picportraitofawoman 89.Height = Width = top = left = showhide.tag, True 94 End With 95 End Sub Sub showhide(id As String, state As Boolean) 98 If id <> picayoungman.tag And chkayoungman Then picayoungman.visible = state 99 If id <> picportraitofawoman.tag And chkportraitofawoman Then picportraitofawoman.visible = 136 Visual Basic for Applications

137 state 100 If id <> picawomanwithaveil.tag And chkwomanwithaveil Then picawomanwithaveil.visible = state 101 If id <> picamanwriting.tag And chkamanwriting Then picamanwriting.visible = state 102 End Sub MouseDown and MouseUp Events 137 Visual Basic for Applications

138 Although the MouseDown and MouseUp events are mainly used in graphics applications, we will include them here for practice, and also graphics are much more fun to play with than watered down business applications. A beginner may be confused about the two new mouse events in the belief that you can only click with a mouse. But remember that a click involves pressing the mouse button and then releasing it. This is in fact two actions and each of them has its own event the MouseDown and MouseUp events. The down event occurs once you press the left mouse button and the up occurs once you release the button. The Click event occurs only after the MouseUp event. As we have not added any code to the Click event it is ignored in this application. 138 Visual Basic for Applications

In this section you will learn some simple data entry, editing, formatting techniques and some simple formulae. Contents

In this section you will learn some simple data entry, editing, formatting techniques and some simple formulae. Contents In this section you will learn some simple data entry, editing, formatting techniques and some simple formulae. Contents Section Topic Sub-topic Pages Section 2 Spreadsheets Layout and Design S2: 2 3 Formulae

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Skill Set 3. Formulas

Skill Set 3. Formulas Skill Set 3 Formulas By the end of this Skill Set you should be able to: Create Simple Formulas Understand Totals and Subtotals Use Brackets Select Cells with the Mouse to Create Formulas Calculate Percentages

More information

VBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide

VBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide VBA Visual Basic for Applications Learner Guide 1 Table of Contents SECTION 1 WORKING WITH MACROS...5 WORKING WITH MACROS...6 About Excel macros...6 Opening Excel (using Windows 7 or 10)...6 Recognizing

More information

DOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES

DOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES Chapter 1 : Examples of commonly used formulas - Office Support A collection of useful Excel formulas for sums and counts, dates and times, text manipularion, conditional formatting, percentages, Excel

More information

EC121 Mathematical Techniques A Revision Notes

EC121 Mathematical Techniques A Revision Notes EC Mathematical Techniques A Revision Notes EC Mathematical Techniques A Revision Notes Mathematical Techniques A begins with two weeks of intensive revision of basic arithmetic and algebra, to the level

More information

Civil Engineering Computation

Civil Engineering Computation Civil Engineering Computation First Steps in VBA Homework Evaluation 2 1 Homework Evaluation 3 Based on this rubric, you may resubmit Homework 1 and Homework 2 (along with today s homework) by next Monday

More information

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

[Page 177 (continued)] a. if ( age >= 65 ); cout << Age is greater than or equal to 65 << endl; else cout << Age is less than 65 << endl; Page 1 of 10 [Page 177 (continued)] Exercises 4.11 Identify and correct the error(s) in each of the following: a. if ( age >= 65 ); cout

More information

You will have mastered the material in this chapter when you can:

You will have mastered the material in this chapter when you can: CHAPTER 6 Loop Structures OBJECTIVES You will have mastered the material in this chapter when you can: Add a MenuStrip object Use the InputBox function Display data using the ListBox object Understand

More information

Number Systems MA1S1. Tristan McLoughlin. November 27, 2013

Number Systems MA1S1. Tristan McLoughlin. November 27, 2013 Number Systems MA1S1 Tristan McLoughlin November 27, 2013 http://en.wikipedia.org/wiki/binary numeral system http://accu.org/index.php/articles/1558 http://www.binaryconvert.com http://en.wikipedia.org/wiki/ascii

More information

PA Payroll Exercise for Intermediate Excel

PA Payroll Exercise for Intermediate Excel PA Payroll Exercise for Intermediate Excel Follow the directions below to create a payroll exercise. Read through each individual direction before performing it, like you are following recipe instructions.

More information

Chapter 1 Operations With Numbers

Chapter 1 Operations With Numbers Chapter 1 Operations With Numbers Part I Negative Numbers You may already know what negative numbers are, but even if you don t, then you have probably seen them several times over the past few days. If

More information

Visual Basic. Chapter 3

Visual Basic. Chapter 3 Visual Basic Chapter 3 Structured Visual Basic In this chapter, we will begin to learn how to write structured Visual Basic programs Creating a flowchart and/or creating pseudocode before you create the

More information

INTRODUCTION TO MICROSOFT EXCEL: DATA ENTRY AND FORMULAS

INTRODUCTION TO MICROSOFT EXCEL: DATA ENTRY AND FORMULAS P a g e 1 INTRODUCTION TO MICROSOFT EXCEL: DATA ENTRY AND FORMULAS MARGERT E HEGGAN FREE PUBLIC LIBRARY SECTION ONE: WHAT IS MICROSOFT EXCEL MICROSOFT EXCEL is a SPREADSHEET program used for organizing

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

M i c r o s o f t E x c e l A d v a n c e d P a r t 3-4. Microsoft Excel Advanced 3-4

M i c r o s o f t E x c e l A d v a n c e d P a r t 3-4. Microsoft Excel Advanced 3-4 Microsoft Excel 2010 Advanced 3-4 0 Absolute references There may be times when you do not want a cell reference to change when copying or filling cells. You can use an absolute reference to keep a row

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

Excel VBA. Microsoft Excel is an extremely powerful tool that you can use to manipulate, analyze, and present data.

Excel VBA. Microsoft Excel is an extremely powerful tool that you can use to manipulate, analyze, and present data. Excel VBA WHAT IS VBA AND WHY WE USE IT Microsoft Excel is an extremely powerful tool that you can use to manipulate, analyze, and present data. Sometimes though, despite the rich set of features in the

More information

2 A little on Spreadsheets

2 A little on Spreadsheets 2 A little on Spreadsheets Spreadsheets are computer versions of an accounts ledger. They are used frequently in business, but have wider uses. In particular they are often used to manipulate experimental

More information

MICROSOFT EXCEL 2000 LEVEL 3

MICROSOFT EXCEL 2000 LEVEL 3 MICROSOFT EXCEL 2000 LEVEL 3 WWP Training Limited Page 1 STUDENT EDITION LESSON 1 - USING LOGICAL, LOOKUP AND ROUND FUNCTIONS... 7 Using the IF Function... 8 Using Nested IF Functions... 10 Using an AND

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

Prepared By: Graeme Hilson. U3A Nunawading

Prepared By: Graeme Hilson. U3A Nunawading 0 Prepared By: Graeme Hilson U3A Nunawading - 2015 1 CONTENTS This Course Page 3 Reference Material Page 3 Introduction page 3 Microsoft Excel Page 3 What is a Spreadsheet Page 4 Excel Screen Page 4 Using

More information

An overview about DroidBasic For Android

An overview about DroidBasic For Android An overview about DroidBasic For Android from February 25, 2013 Contents An overview about DroidBasic For Android...1 Object-Oriented...2 Event-Driven...2 DroidBasic Framework...2 The Integrated Development

More information

A PRACTICAL TUTORIAL TO EXCEL

A PRACTICAL TUTORIAL TO EXCEL 2010 BEGINNERS A PRACTICAL TUTORIAL TO EXCEL by: Julio C. Fajardo A Practical Tutorial to Excel About: Excel is one of the early software tools developed by Microsoft. The program has been widely adopted

More information

CS112 Lecture: Repetition Statements

CS112 Lecture: Repetition Statements CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general

More information

Section 3. Formulas. By the end of this Section you should be able to:

Section 3. Formulas. By the end of this Section you should be able to: Excel 2003 CLAIT Plus Section 3 Formulas By the end of this Section you should be able to: Create Simple Formulas Understand Mathematical Operators Use Brackets Calculate Percentages Select Cells with

More information

The For Next and For Each Loops Explained for VBA & Excel

The For Next and For Each Loops Explained for VBA & Excel The For Next and For Each Loops Explained for VBA & Excel excelcampus.com /vba/for-each-next-loop/ 16 Bottom line: The For Next Loops are some of the most powerful VBA macro coding techniques for automating

More information

Microsoft Excel 2010 Step-by-Step Exercises PivotTables and PivotCharts: Exercise 1

Microsoft Excel 2010 Step-by-Step Exercises PivotTables and PivotCharts: Exercise 1 Microsoft Excel 2010 Step-by-Step Exercises PivotTables and PivotCharts: Exercise 1 In this exercise you will learn how to: Create a new PivotTable Add fields to a PivotTable Format and rename PivotTable

More information

Unit 7. Lesson 7.1. Loop. For Next Statements. Introduction. Loop

Unit 7. Lesson 7.1. Loop. For Next Statements. Introduction. Loop Loop Unit 7 Loop Introduction So far we have seen that each instruction is executed once and once only. Some time we may require that a group of instructions be executed repeatedly, until some logical

More information

EDIT202 Spreadsheet Lab Prep Sheet

EDIT202 Spreadsheet Lab Prep Sheet EDIT202 Spreadsheet Lab Prep Sheet While it is clear to see how a spreadsheet may be used in a classroom to aid a teacher in marking (as your lab will clearly indicate), it should be noted that spreadsheets

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials Fundamentals We build up instructions from three types of materials Constants Expressions Fundamentals Constants are just that, they are values that don t change as our macros are executing Fundamentals

More information

Excel 2013 for Beginners

Excel 2013 for Beginners Excel 2013 for Beginners Class Objective: This class will familiarize you with the basics of using Microsoft Excel. Class Outline: Introduction to Microsoft Excel 2013... 1 Microsoft Excel...2-3 Getting

More information

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013 DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013 GETTING STARTED PAGE 02 Prerequisites What You Will Learn MORE TASKS IN MICROSOFT EXCEL PAGE 03 Cutting, Copying, and Pasting Data Basic Formulas Filling Data

More information

QUICK EXCEL TUTORIAL. The Very Basics

QUICK EXCEL TUTORIAL. The Very Basics QUICK EXCEL TUTORIAL The Very Basics You Are Here. Titles & Column Headers Merging Cells Text Alignment When we work on spread sheets we often need to have a title and/or header clearly visible. Merge

More information

Lecture- 5. Introduction to Microsoft Excel

Lecture- 5. Introduction to Microsoft Excel Lecture- 5 Introduction to Microsoft Excel The Microsoft Excel Window Microsoft Excel is an electronic spreadsheet. You can use it to organize your data into rows and columns. You can also use it to perform

More information

Overview About KBasic

Overview About KBasic Overview About KBasic The following chapter has been used from Wikipedia entry about BASIC and is licensed under the GNU Free Documentation License. Table of Contents Object-Oriented...2 Event-Driven...2

More information

Welcome to Introduction to Microsoft Excel 2010

Welcome to Introduction to Microsoft Excel 2010 Welcome to Introduction to Microsoft Excel 2010 2 Introduction to Excel 2010 What is Microsoft Office Excel 2010? Microsoft Office Excel is a powerful and easy-to-use spreadsheet application. If you are

More information

MICROSOFT EXCEL 2002 (XP): LEVEL 3

MICROSOFT EXCEL 2002 (XP): LEVEL 3 MICROSOFT EXCEL 2002 (XP): LEVEL 3 WWP Training Limited Page 1 STUDENT EDITION LESSON 1 - USING LOGICAL LOOKUP AND ROUND FUNCTIONS... 7 Using Lookup Functions... 8 Using the VLOOKUP Function... 8 Using

More information

Note that ALL of these points are Intercepts(along an axis), something you should see often in later work.

Note that ALL of these points are Intercepts(along an axis), something you should see often in later work. SECTION 1.1: Plotting Coordinate Points on the X-Y Graph This should be a review subject, as it was covered in the prerequisite coursework. But as a reminder, and for practice, plot each of the following

More information

1. Introduction to Microsoft Excel

1. Introduction to Microsoft Excel 1. Introduction to Microsoft Excel A spreadsheet is an online version of an accountant's worksheet, which can automatically do most of the calculating for you. You can do budgets, analyze data, or generate

More information

Learning Microsoft Excel Module 1 Contents. Chapter 1: Introduction to Microsoft Excel

Learning Microsoft Excel Module 1 Contents. Chapter 1: Introduction to Microsoft Excel Module 1 Contents Chapter 1: Introduction to Microsoft Excel Loading Microsoft Excel...1-1 The Microsoft Excel Screen...1-2 Moving the Cursor...1-4 Using the Mouse...1-4 Using the Arrow Keys...1-4 Using

More information

COPYRIGHTED MATERIAL PART I. LESSON 1: Introducing VBA. LESSON 2: Getting Started with Macros. LESSON 3: Introducing the Visual Basic Editor

COPYRIGHTED MATERIAL PART I. LESSON 1: Introducing VBA. LESSON 2: Getting Started with Macros. LESSON 3: Introducing the Visual Basic Editor PART I LESSON 1: Introducing VBA LESSON 2: Getting Started with Macros LESSON 3: Introducing the Visual Basic Editor LESSON 4: Working in the VBE COPYRIGHTED MATERIAL 1 Welcome to your first lesson in

More information

PROBLEM SOLVING AND OFFICE AUTOMATION. A Program consists of a series of instruction that a computer processes to perform the required operation.

PROBLEM SOLVING AND OFFICE AUTOMATION. A Program consists of a series of instruction that a computer processes to perform the required operation. UNIT III PROBLEM SOLVING AND OFFICE AUTOMATION Planning the Computer Program Purpose Algorithm Flow Charts Pseudo code -Application Software Packages- Introduction to Office Packages (not detailed commands

More information

ITConnect KEEPING TRACK OF YOUR EXPENSES WITH YNAB

ITConnect KEEPING TRACK OF YOUR EXPENSES WITH YNAB ITConnect Technology made practical for home APRIL 06 Edit PDF files with Word Word is the best tool we have at hand to edit PDFs without having to purchase extra software. Viruses distributed by email

More information

Microsoft Excel 2013: Part 3 More on Formatting Cells And Worksheet Basics. To apply number formatting:

Microsoft Excel 2013: Part 3 More on Formatting Cells And Worksheet Basics. To apply number formatting: Microsoft Excel 2013: Part 3 More on Formatting Cells And Worksheet Basics Formatting text and numbers In Excel, you can apply specific formatting for text and numbers instead of displaying all cell content

More information

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Programming Basics and Practice GEDB029 Decision Making, Branching and Looping Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Decision Making and Branching C language possesses such decision-making capabilities

More information

Excel. Spreadsheet functions

Excel. Spreadsheet functions Excel Spreadsheet functions Objectives Week 1 By the end of this session you will be able to :- Move around workbooks and worksheets Insert and delete rows and columns Calculate with the Auto Sum function

More information

Contents. What's New. Version released. Newsletter #31 (May 24, 2008) What's New New version released, version 4.3.3

Contents. What's New. Version released. Newsletter #31 (May 24, 2008) What's New New version released, version 4.3.3 Campground Master Newsletter #31 (May 24, 2008) 1 Newsletter #31 (May 24, 2008) Contents What's New New version released, version 4.3.3 Q & A Retrieving credit card information Guarantee Info missing the

More information

Learning Microsoft Excel Module 1 Contents. Chapter 1: Introduction to Microsoft Excel

Learning Microsoft Excel Module 1 Contents. Chapter 1: Introduction to Microsoft Excel Module 1 Contents Chapter 1: Introduction to Microsoft Excel The Microsoft Excel Screen...1-1 Moving the Cursor...1-3 Using the Mouse...1-3 Using the Arrow Keys...1-3 Using the Scroll Bars...1-4 Moving

More information

For many people, learning any new computer software can be an anxietyproducing

For many people, learning any new computer software can be an anxietyproducing 1 Getting to Know Stata 12 For many people, learning any new computer software can be an anxietyproducing task. When that computer program involves statistics, the stress level generally increases exponentially.

More information

How & Why We Subnet Lab Workbook

How & Why We Subnet Lab Workbook i How & Why We Subnet Lab Workbook ii CertificationKits.com How & Why We Subnet Workbook Copyright 2013 CertificationKits LLC All rights reserved. No part of this book maybe be reproduced or transmitted

More information

Microsoft Excel 2007 Macros and VBA

Microsoft Excel 2007 Macros and VBA Microsoft Excel 2007 Macros and VBA With the introduction of Excel 2007 Microsoft made a number of changes to the way macros and VBA are approached. This document outlines these special features of Excel

More information

VBA Collections A Group of Similar Objects that Share Common Properties, Methods and

VBA Collections A Group of Similar Objects that Share Common Properties, Methods and VBA AND MACROS VBA is a major division of the stand-alone Visual Basic programming language. It is integrated into Microsoft Office applications. It is the macro language of Microsoft Office Suite. Previously

More information

DLD VIDYA SAGAR P. potharajuvidyasagar.wordpress.com. Vignana Bharathi Institute of Technology UNIT 1 DLD P VIDYA SAGAR

DLD VIDYA SAGAR P. potharajuvidyasagar.wordpress.com. Vignana Bharathi Institute of Technology UNIT 1 DLD P VIDYA SAGAR UNIT I Digital Systems: Binary Numbers, Octal, Hexa Decimal and other base numbers, Number base conversions, complements, signed binary numbers, Floating point number representation, binary codes, error

More information

Visual Basic for Applications

Visual Basic for Applications Visual Basic for Applications Programming Damiano SOMENZI School of Economics and Management Advanced Computer Skills damiano.somenzi@unibz.it Week 1 Outline 1 Visual Basic for Applications Programming

More information

Microsoft Excel Level 2

Microsoft Excel Level 2 Microsoft Excel Level 2 Table of Contents Chapter 1 Working with Excel Templates... 5 What is a Template?... 5 I. Opening a Template... 5 II. Using a Template... 5 III. Creating a Template... 6 Chapter

More information

=AVERAGE(Al:A10) gives the average of all the numbers in the cells from Al to A10 inclusive.

=AVERAGE(Al:A10) gives the average of all the numbers in the cells from Al to A10 inclusive. What is a function? A function is simply a specialised calculation that Excel has memorised. There are many functions (around 200) built into Excel and they can do lots of different things. In this chapter

More information

Using Microsoft Excel

Using Microsoft Excel Using Microsoft Excel Excel contains numerous tools that are intended to meet a wide range of requirements. Some of the more specialised tools are useful to people in certain situations while others have

More information

Premium POS Pizza Order Entry Module. Introduction and Tutorial

Premium POS Pizza Order Entry Module. Introduction and Tutorial Premium POS Pizza Order Entry Module Introduction and Tutorial Overview The premium POS Pizza module is a replacement for the standard order-entry module. The standard module will still continue to be

More information

Copyright 2018 MakeUseOf. All Rights Reserved.

Copyright 2018 MakeUseOf. All Rights Reserved. The Beginner s Guide to Microsoft Excel Written by Sandy Stachowiak Published April 2018. Read the original article here: https://www.makeuseof.com/tag/beginners-guide-microsoftexcel/ This ebook is the

More information

Advanced Excel Macros : Data Validation/Analysis : OneDrive

Advanced Excel Macros : Data Validation/Analysis : OneDrive Advanced Excel Macros : Data Validation/Analysis : OneDrive Macros Macros in Excel are in short, a recording of keystrokes. Beyond simple recording, you can use macros to automate tasks that you will use

More information

Excel 2007 Fundamentals

Excel 2007 Fundamentals Excel 2007 Fundamentals Introduction The aim of this document is to introduce some basic techniques for using Excel to enter data, perform calculations and produce simple charts based on that information.

More information

Excel Level 1

Excel Level 1 Excel 2016 - Level 1 Tell Me Assistant The Tell Me Assistant, which is new to all Office 2016 applications, allows users to search words, or phrases, about what they want to do in Excel. The Tell Me Assistant

More information

Microsoft Excel 2007 Creating a XY Scatter Chart

Microsoft Excel 2007 Creating a XY Scatter Chart Microsoft Excel 2007 Creating a XY Scatter Chart Introduction This document will walk you through the process of creating a XY Scatter Chart using Microsoft Excel 2007 and using the available Excel features

More information

This chapter is intended to take you through the basic steps of using the Visual Basic

This chapter is intended to take you through the basic steps of using the Visual Basic CHAPTER 1 The Basics This chapter is intended to take you through the basic steps of using the Visual Basic Editor window and writing a simple piece of VBA code. It will show you how to use the Visual

More information

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript Chapter 17 Fundamental Concepts Expressed in JavaScript Learning Objectives Tell the difference between name, value, and variable List three basic data types and the rules for specifying them in a program

More information

Visual basic tutorial problems, developed by Dr. Clement,

Visual basic tutorial problems, developed by Dr. Clement, EXCEL Visual Basic Tutorial Problems (Version January 20, 2009) Dr. Prabhakar Clement Arthur H. Feagin Distinguished Chair Professor Department of Civil Engineering, Auburn University Home page: http://www.eng.auburn.edu/users/clemept/

More information

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to

More information

MICROSOFT EXCEL 2003 LEVEL 3

MICROSOFT EXCEL 2003 LEVEL 3 MICROSOFT EXCEL 2003 LEVEL 3 WWP Training Limited Page 1 STUDENT EDITION LESSON 1 - USING LOGICAL, LOOKUP AND ROUND FUNCTIONS... 7 Using Lookup Functions... 8 Using the VLOOKUP Function... 8 Using the

More information

Editing and Formatting Worksheets

Editing and Formatting Worksheets LESSON 2 Editing and Formatting Worksheets 2.1 After completing this lesson, you will be able to: Format numeric data. Adjust the size of rows and columns. Align cell contents. Create and apply conditional

More information

variables programming statements

variables programming statements 1 VB PROGRAMMERS GUIDE LESSON 1 File: VbGuideL1.doc Date Started: May 24, 2002 Last Update: Dec 27, 2002 ISBN: 0-9730824-9-6 Version: 0.0 INTRODUCTION TO VB PROGRAMMING VB stands for Visual Basic. Visual

More information

Divisibility Rules and Their Explanations

Divisibility Rules and Their Explanations Divisibility Rules and Their Explanations Increase Your Number Sense These divisibility rules apply to determining the divisibility of a positive integer (1, 2, 3, ) by another positive integer or 0 (although

More information

Maximizing the Power of Excel With Macros and Modules

Maximizing the Power of Excel With Macros and Modules Maximizing the Power of Excel With Macros and Modules Produced by SkillPath Seminars The Smart Choice 6900 Squibb Road P.O. Box 2768 Mission, KS 66201-2768 1-800-873-7545 www.skillpath.com Maximizing the

More information

Key concepts through Excel Basic videos 01 to 25

Key concepts through Excel Basic videos 01 to 25 Key concepts through Excel Basic videos 01 to 25 1) Row and Colum make up Cell 2) All Cells = Worksheet = Sheet 3) Name of Sheet is in Sheet Tab 4) All Worksheets = Workbook File 5) Default Alignment In

More information

Excel (Giant) Handout (3/16/15)

Excel (Giant) Handout (3/16/15) Excel (Giant) Handout (3/16/15) Excel is a spreadsheet processor that is an outgrowth of Lotus 1-2-3 and Symphony. It is a Microsoft Product that is part of Microsoft Office (all versions) along with Microsoft

More information

EXCEL BASICS: MICROSOFT OFFICE 2010

EXCEL BASICS: MICROSOFT OFFICE 2010 EXCEL BASICS: MICROSOFT OFFICE 2010 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

The Energy Grid Powerful Web Marketing for the Alternative Energy Industry

The Energy Grid Powerful Web Marketing for the Alternative Energy Industry The Energy Grid Powerful Web Marketing for the Alternative Energy Industry The Energy Grid 105 Rt 101A, Unit 18 Amherst, NH 03031 (603) 413-0322 MCR@TheEnergyGrid.com Terms & Disclaimer: USE THIS PROGRAM

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #29 Arrays in C (Refer Slide Time: 00:08) This session will learn about arrays in C. Now, what is the word array

More information

ABOUT PIVOTTABLES TABLE OF CONTENTS

ABOUT PIVOTTABLES TABLE OF CONTENTS University of Southern California Academic Information Services Excel 2007 - PivotTables ABOUT PIVOTTABLES PivotTables provide an excellent means of analyzing data stored in database format by rearranging

More information

Excel Template Instructions for the Glo-Brite Payroll Project (Using Excel 2010 or 2013)

Excel Template Instructions for the Glo-Brite Payroll Project (Using Excel 2010 or 2013) Excel Template Instructions for the Glo-Brite Payroll Project (Using Excel 2010 or 2013) T APPENDIX B he Excel template for the Payroll Project is an electronic version of the books of account and payroll

More information

d2vbaref.doc Page 1 of 22 05/11/02 14:21

d2vbaref.doc Page 1 of 22 05/11/02 14:21 Database Design 2 1. VBA or Macros?... 2 1.1 Advantages of VBA:... 2 1.2 When to use macros... 3 1.3 From here...... 3 2. A simple event procedure... 4 2.1 The code explained... 4 2.2 How does the error

More information

Microsoft Excel Microsoft Excel

Microsoft Excel Microsoft Excel Excel 101 Microsoft Excel is a spreadsheet program that can be used to organize data, perform calculations, and create charts and graphs. Spreadsheets or graphs created with Microsoft Excel can be imported

More information

INFORMATION SHEET 24002/1: AN EXCEL PRIMER

INFORMATION SHEET 24002/1: AN EXCEL PRIMER INFORMATION SHEET 24002/1: AN EXCEL PRIMER How to use this document This guide to the basics of Microsoft Excel is intended for those people who use the program, but need or wish to know more than the

More information

Advanced Microsoft Excel

Advanced Microsoft Excel Advanced Microsoft Excel Beau's Computer Store 25000 20000 15000 10000 5000 January February March 0 Computers Digital Cameras MP3 Players Cell Phones Presented by www.stsico.com Table of Contents PMT

More information

Activity 1 Creating a simple gradebook

Activity 1 Creating a simple gradebook Activity 1 Creating a simple gradebook 1 Launch Excel to start a new spreadsheet a. Click on the Excel icon to start a new workbook, either from the start menu, Office Toolbar, or an Excel icon on the

More information

1. About AP Invoice Wizard

1. About AP Invoice Wizard 1. About AP Invoice Wizard Welcome to AP Invoice Wizard. We have developed this tool in response to demand from Oracle Payables users for a user friendly and robust spreadsheet tool to load AP Invoices

More information

Performing Basic Calculations

Performing Basic Calculations 7.1 LESSON 7 Performing Basic Calculations After completing this lesson, you will be able to: Build formulas. Copy formulas. Edit formulas. Use the SUM function and AutoSum. Use the Insert Function feature.

More information

Learning Excel VBA. Using Loops in Your Code. ComboProjects. Prepared By Daniel Lamarche

Learning Excel VBA. Using Loops in Your Code. ComboProjects. Prepared By Daniel Lamarche Learning Excel VBA Using s in Your Code Prepared By Daniel Lamarche ComboProjects Using s in Your Code By Daniel Lamarche (Last update June 2016). s are pretty simple in concept however many new programmers

More information

Excel Basics: Working with Spreadsheets

Excel Basics: Working with Spreadsheets Excel Basics: Working with Spreadsheets E 890 / 1 Unravel the Mysteries of Cells, Rows, Ranges, Formulas and More Spreadsheets are all about numbers: they help us keep track of figures and make calculations.

More information

Introduction to Microsoft Excel 2010

Introduction to Microsoft Excel 2010 Introduction to Microsoft Excel 2010 THE BASICS PAGE 02! What is Microsoft Excel?! Important Microsoft Excel Terms! Opening Microsoft Excel 2010! The Title Bar! Page View, Zoom, and Sheets MENUS...PAGE

More information

EXCEL BASICS: MICROSOFT OFFICE 2007

EXCEL BASICS: MICROSOFT OFFICE 2007 EXCEL BASICS: MICROSOFT OFFICE 2007 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

Using Microsoft Excel

Using Microsoft Excel Using Microsoft Excel in Excel Although calculations are one of the main uses for spreadsheets, Excel can do most of the hard work for you by using a formula. When you enter a formula in to a spreadsheet

More information

E D T 3 2 E D T 3. Slide 1

E D T 3 2 E D T 3. Slide 1 Slide Spreadsheets Using Microsoft xcel Reminder: We had covered spreadsheets very briefly when we discussed the different types of software in a previous presentation. Spreadsheets are effective tools

More information

Excel & Business Math Video/Class Project #01 Introduction to Excel. Why We Use Excel for Math. First Formula.

Excel & Business Math Video/Class Project #01 Introduction to Excel. Why We Use Excel for Math. First Formula. Excel & Business Math Video/Class Project #01 Introduction to Excel. Why We Use Excel for Math. First Formula. Topics Covered in Video: 1) USB Drive to store files from class... 2 2) Save As to Download

More information

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0 VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 L J Howell UX Software 2009 Ver. 1.0 TABLE OF CONTENTS INTRODUCTION...ii What is this book about?... iii How to use this book... iii

More information

The Excel Project: Excel for Accountants, Business People... from the Beginning Duncan Williamson

The Excel Project: Excel for Accountants, Business People... from the Beginning Duncan Williamson The Excel Project: Excel for Accountants, Business People... from the Beginning Duncan Williamson Introduction In this book you will see that we use Excel 2007 as the focal point of much of the work we

More information

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Table of Contents Introduction!... 1 Part 1: Entering Data!... 2 1.a: Typing!... 2 1.b: Editing

More information

Using Microsoft Excel

Using Microsoft Excel Using Microsoft Excel Introduction This handout briefly outlines most of the basic uses and functions of Excel that we will be using in this course. Although Excel may be used for performing statistical

More information

SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. Numbers & Number Systems

SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. Numbers & Number Systems SCHOOL OF ENGINEERING & BUILT ENVIRONMENT Mathematics Numbers & Number Systems Introduction Numbers and Their Properties Multiples and Factors The Division Algorithm Prime and Composite Numbers Prime Factors

More information