Extending the Unit Converter

Similar documents
You can record macros to automate tedious

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

Agenda. First Example 24/09/2009 INTRODUCTION TO VBA PROGRAMMING. First Example. The world s simplest calculator...

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

Microsoft Excel 2007 Macros and VBA

Computer Science Lab Exercise 2

Using Microsoft Excel

Civil Engineering Computation

Window (further define the behaviour of objects)

Copyrighted Material. Copyrighted. Material. Copyrighted

2. create the workbook file

This project was originally conceived as a pocket database application for a mobile platform, allowing a

Excel Basics: Working with Spreadsheets

Excel has a powerful automation feature that lets you automate processes that you need to do repeatedly.

RegressItPC installation and test instructions 1

HOUR 4 Understanding Events

SolidWorks A Visual Basic for Applications tutorial for SolidWorks users SDC PUBLICATIONS

Unit 9 Spreadsheet development. Create a user form

Using Microsoft Excel

This is a book about using Visual Basic for Applications (VBA), which is a

MODULE VI: MORE FUNCTIONS

Access Forms Masterclass 5 Create Dynamic Titles for Your Forms

Customizing the Excel 2013 program window. Getting started with Excel 2013

VBA Foundations, Part 12

Macros in Excel: Recording, Running, and Editing

6/14/2010. VBA program units: Subroutines and Functions. Functions: Examples: Examples:

MICROSOFT EXCEL VISUAL BASIC FOR APPLICATIONS INTRODUCTION

VBA Foundations, Part 7

Excel & Visual Basic for Applications (VBA)

VISUAL BASIC 2 EDITOR

XP: Backup Your Important Files for Safety

Taskbar: Working with Several Windows at Once

Introduction... 1 Part I: Getting Started with Excel VBA Programming Part II: How VBA Works with Excel... 31

EXCEL BASICS: MICROSOFT OFFICE 2007

KEYWORDS DDE GETOBJECT PATHNAME CLASS VB EDITOR WITHEVENTS HMI 1.0 TYPE LIBRARY HMI.TAG

Using Microsoft Excel

Printing Tips Revised: 1/5/18

Computer Science Lab Exercise 1

Lesson 16: Collaborating in Excel. Return to the Excel 2007 web page

Instructions for Using the Databases

Getting started 7. Writing macros 23

Intro. Scheme Basics. scm> 5 5. scm>

EXCEL BASICS: MICROSOFT OFFICE 2010

Excel programmers develop two basic types of spreadsheets: spreadsheets

Chapter 10 Working with Graphs and Charts

Creating If/Then/Else Routines

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Light Speed with Excel

Spreadsheet Concepts: Creating Charts in Microsoft Excel

AlphaCam Routing Example

Excel Advanced

CS130/230 Lecture 12 Advanced Forms and Visual Basic for Applications

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

Class #10 Wednesday, November 8, 2017

Macros enable you to automate almost any task that you can undertake

Microsoft Access Lesson 3: Creating Reports

BASIC EXCEL SYLLABUS Section 1: Getting Started Section 2: Working with Worksheet Section 3: Administration Section 4: Data Handling & Manipulation

EstimatorXpress PowerPack Tutorials

This book is about using Visual Basic for Applications (VBA), which is a

Macros enable you to automate almost any task that you can undertake

ADD AND NAME WORKSHEETS

Rescuing Lost Files from CDs and DVDs

Excel Foundation (Step 2)

Chapter 1: Getting Started

Introduction VBA for AutoCAD (Mini Guide)

Text Box Frames. Format Text Box

This document describes how to use the CAP workbook with Excel It applies to version 6b of the workbook.

Open a new Excel workbook and look for the Standard Toolbar.

Orientation. How do I use SYNOPSYS? What does it do?

Links Menu (Blogroll) Contents: Links Widget

13 FORMATTING WORKSHEETS

Manual Vba Access 2010 Close Form Without Saving Record

LSP 121. LSP 121 Math and Tech Literacy II. Topics. Loops. Loops. Loops

VISUAL BASIC 2005 EXPRESS: NOW PLAYING

Using Microsoft Access

Using Microsoft Excel

Create Reflections with Images

6. Essential Spreadsheet Operations

How to work a workbook

Excel Programming with VBA (Macro Programming) 24 hours Getting Started

Excel 2016 Functions

Introduction to Microsoft Excel

Creating a new form with check boxes, drop-down list boxes, and text box fill-ins. Customizing each of the three form fields.

The first program we write will display a picture on a Windows screen, with buttons to make the picture appear and disappear.

Customizing Access Parameter Queries

Crash Course in Modernization. A whitepaper from mrc

How do I use BatchProcess

Introduction to Form Controls

1 Introduction to Using Excel Spreadsheets

FACULTY AND STAFF COMPUTER FOOTHILL-DE ANZA. Office Graphics

Technical White Paper

How to Rescue a Deleted File Using the Free Undelete 360 Program


Using Microsoft Excel

17. Introduction to Visual Basic Programming

Maximizing the Power of Excel With Macros and Modules

ENGG1811 Computing for Engineers Week 9 Dialogues and Forms Numerical Integration

Budget Exercise for Intermediate Excel

GUI Design and Event- Driven Programming

Download the files from you will use these files to finish the following exercises.

Transcription:

Extending the Unit Converter You wrote a unit converter previously that converted the values in selected cells from degrees Celsius to degrees Fahrenheit. You could write separate macros to do different conversions e.g. degrees Fahrenheit to degrees Celsius, mm to inches, metres to feet and so on. This would be easy to do the code for each one would be almost identical. The problem for the user would be finding the right macro. It would be far more useful if the user was presented with a dialog box in which they could select the conversion they want. You will see here how to create a dialog box like the one in Figure 1. The user will be able to select a conversion from the list given. When they press one of the buttons, the conversion will take place. If they choose, for example, mm to inches and press Convert -> then it will convert from mm to inches: pressing Convert <- will convert from inches to mm. You will see the steps required to do this. Figure 1 You will write this code so that it is in your Personal Macro Workbook i.e. so that it can be run from any workbook. To do this you need to make sure that PERSONAL.XLS (or PERSONAL.XLSB) is appearing in the Project Explorer in the VB editor as shown in Figure 2. If it isn t then open a workbook and record a macro in the Personal Macro Workbook you don t need to have anything in the macro just start recording and stop straight away. When you switch to the VB Editor, PERSONAL.XLS should appear as shown. Figure 2

Select VBAProject (PERSONAL.XLS) in the Project Explorer as shown and choose INSERT USERFORM. A blank window (called a Form in VB) will appear as shown in Figure 3. If you click on the blank form, a toolbox should appear like that shown if it doesn t, then select VIEW TOOLBOX. Also shown is the Properties Window (below the Project Explorer below) if it doesn t appear then select VIEW PROPERTIES WINDOW. Figure 3 The toolbox has a range of standard items you can place on your form. The first one you will use is a button. Select the Command Button tool and place one on the form by clicking on it. You can resize the button as desired. You can now run your form using the Run toolbar button. The form should appear on the screen. You can press the button but nothing will happen at the moment you will have to add some code. To get back to your code press the Close button on the form. Now add a second button and a Listbox control. Visual Object Properties When you create a visual object in VB (such as a UserForm or a CommandButton, etc.) you do two things: 1. You create the image that will appear on the screen. 2. You create a set of variables that hold the properties of the object and which can be accessed from within your code. While the properties of any of the objects on the form can be changed by your code, they can also be altered by you using the VB Editor. The property settings you change at this stage will determine what the form looks like when run.

The best way to illustrate this is with an example. You will start by changing the properties of your form. Select the form by clicking on it. The properties of the form will appear in the Properties Window. You will change the text at the top of the form this is the Caption property. Simply delete the current caption and type Unit Converter as shown below. Figure 4 Now select one of the buttons and change its Caption to Convert ->, and change the caption of the other button to Convert <-. Also, change the Name properties of the two buttons and the listbox to sensible things e.g. Conv_btn1, Conv_btn2 and Option_list. The name is how you will refer to the object in your code sensible names will make programming easier. Run the form again and see that the properties have changed. When you are creating a form you always follow the procedure outlined here: 1. Think what the form has to do and how the user will interact with it. In this case it needs a list box for the options and two buttons that the user will press to do the conversions. 2. Draw the objects on the form. 3. Give the objects sensible names. Note that you weren t told to change the Name property of the form don t do this. 4. Change the properties of the objects to the way you want them to be when the form first appears to the user. Only after doing all that should you think about writing code. Event-Driven Programming There are two main types of programs sequential programs and event-driven programs. In sequential programs the programmer dictates the order in which the user does things the computer simply follows the instructions in the program line-byline. That s the kind of program you have written so far in this module. In eventdriven programs, the user dictates the order. Note, for example, how you use Microsoft Excel. You can press the Ribbon controls, type, choose right-click menu options, etc., in any order you want. Similarly, if you

have a dialog box with many options and settings, you can set the options in any order you want. Things do not have to happen in a fixed sequence. This is event-driven programming. It allows more flexible and user-friendly programs to be written. An event-driven program reacts to events. These may be the clicking of a button, the moving of the mouse, the pressing of a key, etc. If there are no events, the program does nothing. The way you write an event-driven program is that you first decide what you want to happen and when. You then tie code to the appropriate event. This will be made clear with this example. In this case there are only two events the program needs to react to the pressing of one button or the other. When a button is pressed, the correct conversion must be done in Excel. The program won t have to do anything when the user selects one of the options - the program should only react when the user presses a button. Tying code to an event This is easy to do in VB. If you want something to happen when the button is pressed, just double-click on the button in the VB Editor. An empty subroutine will appear: Private Sub Conv_btn1_Click() End Sub Any commands placed between these lines will be run when the button named Conv_btn1 is Clicked note the name given to the subroutine. To test this type MsgBox "Test" switch back to the form by selecting it in the Project Explorer, and press the Run button. The form will appear as before but this time when you click on the button the message box should appear. Close the form. The VB Editor should appear again with the form displayed. To get back to the code, double-click on the button again. Note that, the more workbooks you have open in Excel, the more cluttered the Project Explorer will become and the more chance you have of making a mistake when switching back and forward between your form and your code. Close any workbooks that you are not currently using. You will now tie your code for converting to one of the buttons. Double click on it and put this code in it For i = 1 To Selection.Cells.Count Selection.Cells(i).Value = Selection.Cells(i).Value * 1.8 + 32 Next i Test this by typing some values in a worksheet, select them, switch to the VB Editor, run the form and press the button. The values should be converted. Adding Options to Listbox There is no way of adding items to the Listbox list by using the Properties Window. The only way to add items is using VB code. This is easy to do but the question is, where should this code go? In event-driven programming, what you need to think is

when should it happen? You want the items added when the form is run. You will now see how to do this. You need to tie the code to an event that happens when the form first appears. One such event is the Initialize event of the UserForm object. To tie code to this event, double-click on the UserForm in the VB Editor. An empty subroutine will appear Private Sub UserForm_Click() End Sub This is not the correct place to put the code. This corresponds to the user Clicking on the UserForm note the title. Above the code in the VB Editor there are two list boxes as shown in Figure 5. The first contains a list of all the objects on your form. When you select any of these objects, the second list contains a list of all the events associated with that object. If you look in the second list you will see things such as Click (the event when the user clicks on the UserForm), DblClick (the event when the user double-clicks on the form), MouseMove (the event when the user moves the mouse across the UserForm), and so on. If you wish, you can tie code to any of these events it all depends on what you want your program to do. Figure 5 Select the Initialize event for your UserForm. This occurs when the form is run. The following empty subroutine will appear Private Sub UserForm_Initialize() End Sub Now place this code in it: Options_list.AddItem ("Celsius <-> Fahrenheit") Options_list.AddItem ("mm <-> inches") Options_list.AddItem ("metres <-> feet") Options_list.AddItem ("kilometres <-> miles") and run the form. The list should appear and you should be able to select any one of the items. Note that you may have to resize the listbox on the form so that you can see them all. It s a good idea to make one of these items a default setting i.e. when you run the form it will already be selected. Add the following line Options_list.ListIndex = 0 The list index is the number of the item selected (starting at zero). When you run it now the first option should be selected.

Getting the Options to Work When the user presses the Convert -> button, the program needs to make the conversions depending on which option is selected. You can check which option is selected by checking the value of Options_list.ListIndex. Change the code tied to the button. You will need an If-ElseIf type structure inside the For-Next loop so that the correct conversion is done depending on the value of Options_list.ListIndex (which, remember, will be 0 if the first option is chosen). Don t try and do everything at once just get the first two options to work first. Then get all the options to work. Then copy your code to the Convert <- button the only thing you will have to change is the line changing the values. The conversion details are listed in Table 1. Celsius -> Fahrenheit c*1.8 + 32 mm -> inches mm*0.0393700787 metres -> feet m*3.2808399 kilometres -> miles km*0.621371192 Fahrenheit -> Celsius (f 32)/1.8 inches -> mm in/0.0393700787 feet -> metres ft/3.2808399 miles -> kilometres ml/0.621371192 Table 1 Modal Forms At the moment your form is not easy to use. You need to select the cells you want to convert, run the form, select the option and press the button. You then have to close the form. If you want to convert some other cells you need to go through all that again. Firstly, it is possible to add a Ribbon control to run the form but you won t see how to do that here. It would also be much better if you were able to switch back and forth between the form and Excel so you wouldn t have to close the form before selecting new cells. At the moment the form is modal i.e. when it s running you can t use Excel. Select the form in the editor and change its ShowModal property to FALSE. Now try it again. You ll find that it s much easier to use you can jump between it and Excel.