Ch 11: Userforms CP212 Winter 2010 Topics • Designing User Forms o Controls • Setting Properties • • • • • o Tab Order o Testing Writing Event Handlers o Userform_Initialize o btnCancel_Click Displaying a User Form Looping Through Controls Working with Listboxes Working with Excel Controls Background • some information covered in the lecture on interface design • textbook calls a Userform a “dialog box” o can be much more than that • called simply a form in Visual Basic o related topic: Windows Forms Programming • example in text o complex spreadsheet o form gives the user options to choose from o easier to use this “application” than learn Excel Starting a Form • creating a GUI based application or form starts with designing the form • to insert a form in VBE o Insert -> Userform o Toolbox gets displayed - sometimes it disappears click View -> Toolbox to get it back Designing the Form Need to know 3 things: • Which controls are available • How to place, resize and line up controls in a form • How to set the properties Controls Common Uses • CommandButton: allows user to execute code (subs or macros) • Label: explain something • Textbox: get input from the user (can be readonly - set Enabled property to False) Common Uses • ListBox: choose one or more items from a list • ComboBox: like a listbox, but allows a custom item to be added that isn't in the list. • CheckBox: any, none, or all of the boxes can be selected • OptionButton: also called a radio button, only one option can be selected (usually one is mandatory) per group • Frame: organize a set of options, or grouping of controls • RefEdit: similar to a textbox but also allows user to select a range of cells Custom Controls • Right-click on the toolbox and select Additional Controls • One good one is the Calendar tool: o Calendar Control 12.0 (but there are others) The calendar control was removed in Office 2010. You can either buy a new one, or create your own. That would be a good exercise, and has been used as part of an assignment in the past. Laying Controls • To help, controls can be resized and aligned to each other or the form • Format -> Align, Format -> Make Same Size o Experiment with it Setting Properties • most controls have different properties • some are common • Name: used to refer to the control with • • • VBA Code o name not necessary if you plan on not referring to it with code (like labels) Caption: what you see on the screen, usually on forms, buttons and labels. Text or Value: What gets displayed in a Textbox. Most Properties can be set at design time (in the VBE) or with code Naming controls • use a 3 letter prefix • good exercise on pg 213 of text Tab Order • can greatly improve the usefulness of your form • tab order begins as the order in which you placed them on the form • you can change the TabIndex property • TabIndex starts at 0 • Set TabStop to False if you don't want the user tabbing to it. • Items in a frame are indexed separately from other items on the form. • View TabOrder Writing Event Handlers • a GUI program (or a form) just sits there and waits for events • a subroutine written to execute when the event happens is called an event handler • events handlers are placed in the form's code window, not a module • when viewing a form, click View -> Code or double-click a control • double-clicking a control will open the event handler for that control's default event (like CommandButton1_Click) • event handlers are named controlname_EventName • try it and use the Object Browser to learn more o RefEdit control has its own library... hard to find Displaying a Form • give the form a name • insert a new module and create a sub to display the form Public Sub Display() ' Shows the form I want to use frmMyForm.Show End Sub • form will appear and then the event handlers take over Example Code from text (pg.221) Shown here is a Window XP screenshot. Practice Form.xlsm (pg. 223) • code for adding items to a list o For Loop or RowSource property • variables declared Public at the top of the code window, so they can be accessed from inside the form as well • Useful functions: IsNumeric and IsDate to check for data validation • can use Exit Sub if an error occurs but you still want form to be displayed Practice Form cont'd • use Select Case for option buttons o optTruck.Value = True if it has been selected • Value property of a listbox: Indicates which item was • • selected. o ListIndex: position in the list of the selected item, base 0 o If ListIndex = -1 then no item selected o make bulletproof code: set ListIndex = 0 in UserForm_Initialize, forcing user to make a selection Must Unload the form to remove it from the screen When unloaded, the original calling sub will continue Looping Through Controls • have many controls on a form and you want to check all of them would be easy if they were in an array o can't be done in VBA so use For Each... in the collection of Controls on the form: Dim ctl As Control For Each ctl In Me.Controls If TypeName(ctl) = "TextBox" Then If ctl.Value = "" or Not IsDate(ctl) Then MsgBox "Enter valid dates", vbInformation, "Invalid Entry" ctl.SetFocus ' Allows user to enter data again Exit Sub End If End If Next • • List Boxes • two types: single and multi • use MultiSelect property • Single o ListIndex = -1 means Nothing selected o ListIndex = 3 means the 4th item was selected o lstMyList.Value will also hold the selected item Multi o can't use Value or ListIndex o Selected property is a 0-based array of True or False values o ListCount will count the items in the list For i = 0 to lstProducts.ListCount -1 isChosen(i) = lstProducts.Selected(i) Next • Private Sub btnOk_Click() ' Display the value the user has selected in the list txtOutput.Text = lstBox.Value txtIndexValue.Text = lstBox.ListIndex End Sub Private Sub UserForm_Initialize() ' Restore default height Me.Height = 310.5 ' Add items to the list lstBox.AddItem "One" lstBox.AddItem "Two" lstBox.AddItem ("Four") lstBox.AddItem "Three", 2 lstExtended.AddItem ("One") lstExtended.AddItem ("Two") lstExtended.AddItem ("Four") lstExtended.AddItem "Three", 2 lstExtended.AddItem "Five" lstExtended.AddItem "Six" lstExtended.AddItem "Seven" ' Clear the values in the list box lstMulti.Clear ' Get values from the spreadsheet Dim c As Range For Each c In Worksheets("wksData").Range("defaultValues") ' Add each item to the list lstMulti.AddItem c.Value Next Private Sub btnChooseEnhanced_Click() Dim mySelections As String Dim isChosen() As String ' Resize the array based on the size of items in the list ReDim isChosen(lstExtended.ListCount) ' Show the hidden portion of the form. Me.Height = 396.75 ' Place the selected items in an array For i = 0 To lstExtended.ListCount - 1 ' Check to see if the item was selected If lstExtended.Selected(i) Then ' If it was selected, place it in the array isChosen(i) = lstExtended.List(i) ' This produces gaps in the output if items were not selected. End If Next ' Create a string of all the items joined together mySelections = Join(isChosen, ", ") txtMultiOutput.Text = mySelections End Sub Wrap Up • Check pg. 230 about working with Excel controls (little or no VBA) • read the summary, work on exercises 1, 2, 4