Download presentation
Presentation is loading. Please wait.
Published byDennis Craig Modified over 9 years ago
1
http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application
2
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
3
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
4
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…
5
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
6
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
7
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
8
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
9
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
10
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 …)
11
' 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)
12
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)
13
'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
14
'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)
15
'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)
16
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.
17
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.
18
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
19
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.