http://blackboard.umbc.edu lab 10. user forms design – code part ► lab 9 review ► continue...

19
http://blackboard.umbc.edu Lab 10. User Forms Design – Lab 10. User Forms Design – Code Part Code Part Lab 9 Review Lab 9 Review Continue ‘Student Continue ‘Student Record’ Example Record’ Example A Car Loan Application A Car Loan Application

Upload: dennis-craig

Post on 19-Jan-2016

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

http://blackboard.umbc.edu

Lab 10. User Forms Design – Code PartLab 10. User Forms Design – Code Part

►► Lab 9 ReviewLab 9 Review

► ► Continue ‘Student Record’ ExampleContinue ‘Student Record’ Example

► ► A Car Loan ApplicationA Car Loan Application

Page 2: Http://blackboard.umbc.edu 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 TipsUser 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

Page 3: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

Event Code for User FormsEvent 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

Page 4: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

Student Record Example Student Record Example Test & User Form InitiationTest & 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…

Page 5: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

Exercise Step 3: User Form InitializationExercise 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

Page 6: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

Exercise Step 3: User Form Initialization (Cont’d)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 cellEnd Sub

Page 7: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

Exercise Step 3: User Form Initialization (Cont’d)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

Page 8: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

Exercise Step 4: CancelButton_Click (Cont’d)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

Page 9: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

Step 5: Major Code – Behind Submit ButtonStep 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

Page 10: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

SubmitButton_Click Event CodeSubmitButton_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 …)

Page 11: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

' 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)SubmitButton_Click Event Code (Cont’d)

Page 12: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

ElseIf .Value < 0 Or .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)SubmitButton_Click Event Code (Cont’d)

Page 13: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

'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)SubmitButton_Click Event Code (Cont’d)

' Capture hobbiesIsTravel = TravelBoxIsMovie = MovieBoxIsSports = SportsBoxIsComputer = ComputerBox

Page 14: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

'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)SubmitButton_Click Event Code (Cont’d)

Page 15: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

'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 formEnd Sub

SubmitButton_Click Event Code (Cont’d)SubmitButton_Click Event Code (Cont’d)

Page 16: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

NotesNotes

• 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.

Page 17: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

Displaying a User FormDisplaying 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 SinglePublic Gender As String, Standings As StringPublic 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 IfEnd Sub

– Then, assign this Main sub to a button on the worksheet.

Page 18: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

User Forms Design Tip 2:User Forms Design Tip 2:Guidelines for Application Development (1)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

Page 19: Http://blackboard.umbc.edu Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application

User Forms Design Tip 2 (cont.):User Forms Design Tip 2 (cont.):Guidelines for Application Development (2)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.