Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application.

Slides:



Advertisements
Similar presentations
Working with Intrinsic Controls and ActiveX Controls
Advertisements

Office 2003 Post-Advanced Concepts and Techniques M i c r o s o f t Excel Project 7 Using Macros and Visual Basic for Applications (VBA) with Excel.
Tutorial 7: Developing an Excel Application
30/04/ Selection Nested If structures & Complex Multiple Conditions.
Loading Excel Double click the Excel icon on the desktop (if you have this) OR Click on Start All Programs Microsoft Office Microsoft Office Excel 2003.
Creating an OOED Application
Excel and VBA Creating an Excel Application
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
Fundamentals of Programming in Visual Basic 3.1 Visual basic Objects Visual Basic programs display a Windows style screen (called a form) with boxes into.
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
COMPREHENSIVE Excel Tutorial 8 Developing an Excel Application.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
Chapter 9 Macros, Navigation Forms, PivotTables, and PivotCharts
Not in Text CP212 Winter No VBA Required “Regular” Programming traditional programming is sequential in nature o one command executed after another.
Hello World In C++ and Microsoft Visual C++. Directions to begin a project 1. Go to All Programs 2. Open Visual Studio C++ 3. Click on New Project 4.
Working with a Database
Introduction to Graphical User Interfaces. Objectives * Students should understand what a procedural program is. * Students should understand what an.
Lab 9 – User Forms Design. User Forms What are user forms? –Known as dialog boxes –Major ways for getting user input An example of using user forms: Monthly.
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-3 1 Lecture Outline Variable Scope Calling another subprogram Programming.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
Copyright 2007, Paradigm Publishing Inc. EXCEL 2007 Chapter 7 BACKNEXTEND 7-1 LINKS TO OBJECTIVES Record & run a macro Record & run a macro Save as a macro-
IN THE NAME OF ALLAH UserForms on VBA Lab 06 Tahani Al_dweesh.
Introduction on VBA Lab 05 ins.Tahani Al_dweesh. Lab Objectives Introduction Calculation with VBA Storing and Retrieving Variables in a Worksheet Using.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Ch 11: Userforms CP212 Winter Topics Designing User Forms o Controls Setting Properties o Tab Order o Testing Writing Event Handlers o Userform_Initialize.
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Week 8.  Recap  User Forms  Input Validation Message Boxes Input Boxes  Conversion Functions.
PMS /134/182 HEX 0886B6 PMS /39/80 HEX 5E2750 PMS /168/180 HEX 00A8B4 PMS /190/40 HEX 66CC33 By Adrian Gardener Date 9 July 2012.
Creating a Web Site to Gather Data and Conduct Research.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Using Visual Basic for Applications (VBA) – Project 8.
Designing Interface Components. Components Navigation components - the user uses these components to give instructions. Input – Components that are used.
Introduction to Visual Basic.NET Chapter 2 Introduction to Controls, Events.
Microsoft Office 2007 Access Chapter 6 Using Macros, Switchboards, PivotTables, and PivotCharts.
VBA Lab 2 I ns.Samia Al-blwi. Visual Basic Grammar Object: Visual Basic is an object-oriented language. This means that all the items in Excel are thought.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
1 Flow Control II Code: Select-Case and For-Next Controls: Frames and OptionButtons.
Microsoft Access 2010 Chapter 10 Administering a Database System.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Chapter 9 Macros And Visual Basic For Applications.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
The Object Model. You can think of the contents of an Excel application as a hierarchy of collections of objects, manipulated by code Each object can.
1 CS105 Discussion 5 – Variables and If Announcements MP 1 due on Monday Midterm 1 on Tuesday If you need a conflict, request it NOW!!
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
Office of Housing Choice Voucher Program Voucher Management System – VMS Version Released October 2011.
The Excel model for information processing The Excel model is a grid of cells in which items of information are stored and processed. Any information that.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
Modify Tables and FieldsModify Tables and Fields Lesson 4 © 2014, John Wiley & Sons, Inc.Microsoft Official Academic Course, Microsoft Word Microsoft.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
Controlling Program Flow with Decision Structures.
Access Queries and Forms. Adding a New Field  To insert a field after you have saved your table, open Access, and open the table  It is easier to add.
Microsoft Visual C# 2010 Fourth Edition Chapter 3 Using GUI Objects and the Visual Studio IDE.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Macros in Excel Using VBA Time Required – 5 hours.
Working with UserForms Dr Joanna Wyrobek 1. Displaying a modeless UserForm By default, UserForms are displayed modally. This means that the UserForm must.
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
Chapter 8 Multiple Forms, Modules, and Menus. Introduction This chapter demonstrates how to: – Add multiple forms to a project – Create a module to hold.
Excel Tutorial 8 Developing an Excel Application
IE 8580 Module 4: DIY Monte Carlo Simulation
A variable is a name for a value stored in memory.
VBA - Excel VBA is Visual Basic for Applications
Developing an Excel Application
Even More VBA IE 469 Spring 2017.
Excel VBA Day 3 of 3 Tom Vorves.
User Forms.
UserForm.
Microsoft Excel 2007 – Level 2
Presentation transcript:

Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

User Forms Design Tip 1: GUI Design Tips Organize the user interface so that the information flows either vertically or horizontally, with the most important information always located in the upper- left corner of the screen Group related controls together using either white space or a frame Either center the command buttons along the bottom of the screen or stack them in either the upper-right or lower-right corner Use no more than six command buttons on a screen Place the most commonly used command button first

Event Code for User Forms ● Much of Windows programming is built around events, where an event occurs whenever the user does something. Each of these events has a built-in event handler, which is a sub that you can add code to so that appropriate actions are taken when the event occurs. Event code is not placed in modules. Instead, it is placed in a user form’s code window, which can be accessed via –View->Code menu –Press F7 –Double-click on a control Understand the naming conventions of an event code –Each control has many stubs available, each start with the name of the control, followed by an underscore, and an event type, such as UserForm_Initialize, SubmitButton_Click. –You can select different events for a control from the two drop-down lists at the top of the window and insert a “Stub” –You do not have a choice over the format of the “Sub” line

Student Record Example Test & User Form Initiation Select the user form Run Sub/UserForm – Tab through the controls too Note that you can’t do anything further because the controls are not functional yet. Usually, when a dialog box pops up, it contains some default settings. To do this, we need to initialize our user form. Go to the user form code window: Select the user form, and double click on it or use the View\Code menu item On the top left of the code window, you can see “UserForm”. Then select “Initialize” from the right list box…

Exercise Step 3: User Form Initialization You will immediately see a new stub called “UserForm_Initialize()” appears. You can add code in this stub to do some initialization to your UserForm. This code determines how the user form looks like when the user first sees it. Understand the naming conventions of an event code –Each control has many stubs available, each start with the name of the control, followed by an underscore, and an event type, such as UserForm_Initialize, SubmitButton_Click. –You can select different events for a control from the two drop- down lists at the top of the window and insert a “Sub” –You do not have a choice over the format of the “Sub” line Go to View/Object Browser to look into details of each control

Exercise Step 3: User Form Initialization (Cont’d) Before writing the code, 1) create a new worksheet. Put “Courses” in cell A1. Then, in cells A2:A11 add 10 course names; 2) Make sure the name of your Listbox is called “CourseList” Code: Private Sub UserForm_Initialize() Dim cell As Range 'OptionButton Initializations: FemaleOption.Value = True FreshmanOption.Value = True 'CheckBox Initializations: MovieOption.Value = True SportsOption.Value = True 'ListBox Initialization: Range("A2:A11").Name = "Courses" For Each cell In Range("Courses") CourseList.AddItem cell.Value Next cell End Sub

Exercise Step 3: User Form Initialization (Cont’d) Another way to initialize the ListBox: If the RowSource property of the ListBox is assigned to Range("Courses"), you don’t need the above For-Each loop to populate the list box. You may run the user form again to see the results of the initialization

Exercise Step 4: CancelButton_Click (Cont’d) Private Sub CancelButton_Click() ' This line makes the user form disappear Unload Me End End Sub Me is the keyword for the user form

Step 5: Major Code – Behind Submit Button SubmitButton_Click event code –Usually the lengthiest part of the event code –Captures the user inputs –Performs error checking to ensure that a user provides “valid” inputs: A student cannot leave the Name box blank Cannot leave the GPA box blank; the input must be number and within the range 0-4 Selects his/her gender Selects at least one course in the Course list box Check properties and methods of objects in VBA by View->Object Browser in VBE

SubmitButton_Click Event Code Private Sub SubmitButton_Click() 'Make sure a name is entered into the Namebox If NameBox.Value = "" Then MsgBox "Please enter your name. " ' To have the cursor focus on the current text box NameBox.SetFocus Exit Sub ' To exit the sub right away End If ' Capture the name in a public variable for later use StudentName = NameBox.Value ' (Next page …)

' Validate GPA With GPABox If.Value = "" Then MsgBox "You forgot to enter your GPA!“.SetFocus Exit Sub ElseIf Not IsNumeric(.Value) Then MsgBox "Please enter your GPA between” _ & “0~4.0.".Value = "" ' delete the former input.SetFocus Exit Sub SubmitButton_Click Event Code (Cont’d)

ElseIf.Value 4 Then MsgBox "The GPA you entered is out of " _ & "range (0 ~ 4.0). Please try again.".SetFocus Exit Sub End If 'Capture the GPA in a public variable Grade = GPABox.Value End With SubmitButton_Click Event Code (Cont’d)

'Capture Gender and Standings If MaleOption = True Then Gender = "Male" ElseIf FemaleOption Then Gender = "Female" Else MsgBox "Please select your gender." Exit Sub End If If FreshmanOption = True Then Standings = "Freshman" ElseIf JuniorOption = True Then Standings = "Junior“ ElseIf SophomoreOption = True Then Standings = "Sophomore" Else Standings = "Senior" End If SubmitButton_Click Event Code (Cont’d) ' Capture hobbies IsTravel = TravelBox IsMovie = MovieBox IsSports = SportsBox IsComputer = ComputerBox

'Capture the courses selected in the list box With CourseList If.ListIndex <> -1 Then j = 1 'used as row index For i = 0 To.ListCount - 1 If.Selected(i) = True Then Worksheets("Sheet2").Range("A" & j).Value =.List(i) j = j + 1 End If Next Else MsgBox "Courses have not been selected”.SetFocus Exit Sub End If End With Unload Me 'Unload the user form End Sub SubmitButton_Click Event Code (Cont’d)

'Capture the courses selected in the list box With CourseList j = 1 'used as row index For i = 0 To.ListCount - 1 If.Selected(i) = True Then Worksheets("Sheet2").Range("A" & j).Value =.List(i) j = j + 1 End If Next i If j = 1 Then MsgBox "Courses have not been selected?".SetFocus Exit Sub End If End With Unload Me 'Unload the user form End Sub SubmitButton_Click Event Code (Cont’d)

Notes The ListIndex property indicates the position of the selected item in the list box, starting from 0. If no item is selected, ListIndex is –1. We want to ensure that some items has been selected. Don’t forget to unload the user form at the end of the sub. The variables used in the user form must be declared as public variables at the top of the module where they will be used, so that the values of these variables are captured in the user form event code. They are used later on in the module code.

Displaying a User Form How to make a user form display in the first place? –Use the Show method that displays the form – the code is stored in a module Public i As Integer, j As Integer, StudentName As String, Grade As Single Public Gender As String, Standings As String Public IsTravel As Boolean, IsMovie As Boolean, IsSports As Boolean, IsComputer As Boolean Sub Main() Dim Ans As Variant Ans = MsgBox("Register?", vbYesNo, "Registration option") If Ans = vbYes Then InputsForm.Show 'You can add some statements here to deal with the data 'captured through the user form. For example: Msgbox "The name you filled in is " & StudentName & ", and " & _ " your grade is " & Grade & ". " End If End Sub –Then, assign this Main sub to a button on the worksheet.

User Forms Design Tip 2: Guidelines for Application Development (1) Decide what you want the application to do –What functionality? –How to implement the functionality? Where to get input data? Dialog boxes on the interface or EXCEL worksheets? What information to be reported? How to display the solutions/results? In message boxes, tables, or charts? Communicate frequently and clearly with your teammates (and users, if available) Provide sufficient documentation – insert “good” comments whenever there is any possibility of confusion Give meaningful names for variables, subs, etc. E.g. TotalProfit, CarPrice, FirstName

User Forms Design Tip 2 (cont.): Guidelines for Application Development (2) Try to use multiple short subs instead of one long sub so that your programs are easier to maintain, extend, and debug. Develop as much of your application as possible with the Excel interface at design time, and let VBA fill in any other necessary details at run time. e.g. developing necessary “templates” at design time Add appropriate finishing touches: –Add navigational buttons and activate worksheets when necessary; –Hide sheets until they are needed using the Visible property; –Use the Excel’s Tools->Options menu item, with the View tab, to change some of the defaults on the selected sheets.