IEOR 198 – Visual Basic for the Rest of Us Week 9 Notes Carson Gross Ian Vacin Week 9: “GUI Elements and Excel Events” Controls in Visual Basic In last lecture, controls in Excel were discussed. In this lecture we will discuss them within the VB environment through the VB Editor. Controls can be programmatically displayed in Excel spreadsheets, but are usually placed in userforms prior to application runtime. Although userforms are critical for control placement and design, it will be discussed a little later. There are three important components of controls in VB: Properties Methods Events Control Properties The Basics A simple definition is that control properties are variables that belong to a particular object or control. These properties can be set at design or runtime. Using the Properties View (in VB Editor), one can visually change the possible properties of a particular control. Once a property is altered, the Visual Basic design interface, immediately modifies the control. Availability When working with properties, one can: 1. Set and inspect their value at design time 2. Retrieve the property’s value at runtime 3. Assign a value to the property at runtime Some properties are only available at runtime only o Ex. ListIndex property of ListBox or ComboBox controls (indicates which member of the control is selected). Since the data for these controls is loaded at runtime, selecting a member can only occur during runtime as well. Some properties are only available as read-only o Ex. The Name property represents a control’s identifier and is the reference point in any code that addresses that control. Once it is set, it cannot be altered during runtime. Some properties are only available as write-only o Ex. The ADO Data Control’s Password property (sets the user’s password for a connection request). One can set the password, but one cannot retrieve it due to security concerns. Control Methods The Basics Methods are the verbs of controls. Where properties change the attributes of a control, methods allow a user to affect a control’s precise operation. Methods can be procedures or functions. Procedures perform some operation while functions return some value. The Move method is a procedure while the ListItems.Add method is a function (returns a reference) Example Move method of any control moves a control from its current position to a new position. Syntax is as follows: Move(Left, [Top], [Width], [Height]) ListItems.Add method adds an item to a collection and returns a reference if the addition is successful. This reference allows one to easily set values of the object’s other properties. Control Events The Basics Page 1 of 8 Week 9 Notes IEOR 198 – Visual Basic for the Rest of Us Carson Gross Ian Vacin Events are methods that are usually executed by the VB runtime engine in response to some event. An event has an event procedure or an event handler that determines how the object responds when an event is invoked. Example The Click event is a common example. When a button is used, if a Click event does not have an event handler, then the action of clicking a button by a user would create nothing more than a visual click where the VB runtime engine does nothing more than check to see if a “cmdButton_Click” event handler exists. If an event handler does exist, then any code written underneath it will be executed. Event handlers are procedures that will be executed when a particular event has occurred. Control Creation Tasks (for your reference) The following is a list of activities that should be performed when creating a VB control: Set Properties 1. Define the form or the control’s name. The following is a commonly used naming convention scheme: CONTROL ADO Data Control Animation CheckBox ComboBox CommandButton CommonDialog CoolBar Data DataCombo DataGrid DataList DTPicker DBCombo DBGrid DBList FlatScrollbar Form Frame HScrollbar Image ImageCombo ImageList Internet Transfer Label Line ListBox ListView MaskedEditBox Menu MonthView MSChart MSFlexGrid MSHFlexGrid ABBREVIATION ado ani chk cbo cmd dlg cbr dat dtc dtg dtl dtp dbc dbg dbl fsb frm fra hsz img icb iml itc lbl lin lst lvw meb mnu mvw cht flx hfl Page 2 of 8 IEOR 198 – Visual Basic for the Rest of Us Week 9 Notes Multimedia OLE Option Button PictureBox ProgressBar RichTextBox Shape StatusBar SysInfo TabStrip TextBox Timer Toolbar TreeView UpDown VScrollBar Winsock Carson Gross Ian Vacin mci ole opt pic pbr rtf sha sta sin tab txt tmr tlb tre upd vsb sck 2. Specify the control’s position in the tab order. The tab order is the order by which the controls gain focus when the user “tabs” through the form. a. TabStop (set to True then the control is accessed by tabbing) b. TabIndex (zero is the first and n is the last) 3. Set caption and tool tip Caption (Allows for description to be written on a control; if the & precedes the name, then the control can be quick keyed with the Alt + (Preceding letter after &) when it is pressed. For example, &Exit makes the Alt + E command gain focus of that particular control) ToolTipText (when the mouse hovers over the control, a string appears over the control providing more information) 4. Adjust control location (Left, Top, Width, Height) 5. Set control’s general appearance Enabled (If “False” then a control cannot gain focus and does not respond to user actions; grey-out) Visible (If “False” then a control cannot be seen by a user) BackColor (Determines the background color of the control. It is represented by a long integer that represents an RGB color or an index to the system color palette.) 6. Define other properties Useful Methods Zorder o Determines if the control is brought to the front of a container or behind other controls (position = 0 = vbBringtoFront, 1 = vbSendtoBack) Drag o Allows for a control to be dragged and dropped (action = vbBeginDrag, vbEndDrag, vbCancel). Move o Allows for a control to be moved to a new position using 4 parameters (Left, Top, Width, Height). SetFocus o Makes the selected control the ActiveControl and overrides the form’s Tab Order. Page 3 of 8 IEOR 198 – Visual Basic for the Rest of Us Week 9 Notes Carson Gross Ian Vacin Important Event Handlers Click, DblClick, MouseDown, MouseUp, and MouseMove o Mouse events respond to actions taken with the mouse. Change, KeyPress, KeyDown, and KeyUp o Checks for keyboard interaction by the user. LostFocus and GetFocus o When a tabstop is reached, a control gets a GotFocus and when it changes it gets a LostFocus. UserForms Forms are the heart of a GUI interface in VB and are essentially a container for a set of controls. In an effort to bridge the gap between full application development and Excel, the userform allows for a limited application to exist. Forms are the screen panes for which controls, dialog, and graphics reside for display and interaction with the user. If numerous forms are created and linked together, an almost full fledged application can be initiated in Excel. As with controls, userforms have properties, methods, and events. As given with the control section, the following is a list of creation tasks and useful information about UserForms. Forms Creation Tasks (for your reference) The following is a list of features and functionalities of forms. Set Properties 1. Determine form type. BorderStyle o Sets the border and the type of form displayed (values include 0 = no border - no caption - no buttons, 1 = cannot be resized, show buttons & caption, 2 = standard form – resizeable – show caption & buttons, 3 = cannot resize – show some buttons, etc.) Caption (description on titlebar) ControlBox (show control box and close button on form) MinButton, MaxButton (displays min and max size buttons) ShowInTaskbar (Taskbar display settings) 2. Set graphical properties. AutoRedraw ClipControls (limits the form redraw to everything but the controls) PaletteMode, Palette (changes the way color images are displayed) 3. Set behavioral properties. KeyPreview (True = form receives keyboard events before controls, False = controls in the form receive keyboard events before the form) Moveable (whether the form can be moved) ScaleHeight, ScaleWidth, ScaleLeft, ScaleTop, ScaleMode (resizing options) StartUpPosition (where the form appears on the screen when it is loaded) WindowState (determines whether the form is minimized, normal, or maximized when loaded) 4. Set or retrieve general properties ActiveControl (returns a reference to the control that has Focus) Controls collection, Control object Page 4 of 8 Week 9 Notes IEOR 198 – Visual Basic for the Rest of Us Carson Gross Ian Vacin Useful Methods Circle, Cls, Line, PaintPicture, Point, Pset Hide (Hides the form until it is unloaded or shown) PopupMenu (Displays pop up menu) PrintForm (Sends the image to the printer) Show (Loads and/or displays a form that has not been loaded or is hidden) TextHeight, TextWidth (returns the height or width of a string) Important Event Handlers Activate (Fired when the form receives focus from another form) Initialize (Fired when the form is loaded or shown) Load (Fired when the form is loaded) Paint (Fired when the form needs to be repainted) QueryUnload (Called when a form is about to be unloaded) Resize (Fired when the form is resized) Terminate (Fired when all references to the form have been set to Nothing) Unload (Fired when the form is unloading from memory) Order of Form Events Since event handlers may appear to have a bit of overlap, the sequence of events when a form is loaded and unloaded are listed below: Loaded Sequence Initialize event Load event Resize event Activate event GotFocus event Paint event Unloaded Sequence QueryUnload evnet Unload event Terminate event (if last form) Page 5 of 8 Week 9 Notes IEOR 198 – Visual Basic for the Rest of Us Carson Gross Ian Vacin An Example of GUI Elements Here is a simple example to show how to create a simple drop down and then respond to the users input from that drop down as well as some text boxes. Say that we wish to design an admittedly boring form that has four major elements: Two text boxes that take numbers in them; a drop down that can be set to “Min”, “Max” or “Average”; and a button that will do the selected operation on the two entered numbers. It looks something like this at design time: ComboBox1 txtDlb1 txtDlb2 CommandButton1 And something like this at run time: There are three pieces to complete this task: Create the UserForm Create the Controls Add the necessary code Create the UserForm To create a userform, go to the VB Editor and select “Insert” from the menu. Choose “Insert -> UserForm”. A UserForm will appear in the object window. In addition the Properties menu will populate with fields to edit. As outlined above, fill in the necessary properties for the UserForm (name, graphical representation, etc.). Once completed, controls can be added to the form. Through the “View” menu, select the “Toolbox” option for the “Toolbox” to appear. As you can see, it is very similar to the one shown in Excel. Like the one in Excel, other controls can be added. Please see the VB Help for additional controls. Create the Controls To add controls, just select the type in use your left-mouse button to draw on the form. Adjust the properties for each control and repeat for the two labels, two Text Boxes, ComboBox, and Button. Note the “(Name)” not the “Caption” is what is used by VB to call or perform an action on a control. Page 6 of 8 IEOR 198 – Visual Basic for the Rest of Us Week 9 Notes Project Explorer Carson Gross Ian Vacin UserForm Properties Add the Necessary Code We trust that you know how to draw the text boxes and dropdowns and command buttons correctly, but you might not know how to write code that, for example, fills in the drop down with options. Here is the code for this UserForm, in it’s entirety: 'This occurs when the button is clicked Private Sub CommandButton1_Click() Dim dbl1 As Double, dbl2 As Double 'Get the numbers from the textboxes dbl1 = CDbl(txtDbl1.Value) dbl2 = CDbl(txtDbl2.Value) 'See what the user asked us to do If ComboBox1.Value = "Max" Then Call MsgBox("The max value is " & _ Application.WorksheetFunction.Max(int1, int2)) ElseIf ComboBox1.Value = "Min" Then Call MsgBox("The min value is " & _ Application.WorksheetFunction.Min(int1, int2)) ElseIf ComboBox1.Value = "Average" Then Call MsgBox("The average value is " & _ Application.WorksheetFunction.Average(int1, int2)) Else Call MsgBox("Please select an action") End If End Sub 'This occurs when the form is activated Private Sub UserForm_Activate() 'add in three choices Page 7 of 8 IEOR 198 – Visual Basic for the Rest of Us Week 9 Notes Carson Gross Ian Vacin Call ComboBox1.AddItem("Max") Call ComboBox1.AddItem("Min") Call ComboBox1.AddItem("Average") 'set the first item selected ComboBox1.ListIndex = 0 End Sub Not too much to it, eh? Like much in VBA, it is relatively simple. You just need to know where to look. Remember that you can see all the events that a control can respond to by selecting its name in the drop down just above the left hand side of the code window when you are editing the form that it is on. The events will come up in the drop down on the right hand side. Remember you use F5 to launch the form, just like you would any other code. Excel Events Like the Userform we discussed above, the ThisWorkbook and each Sheet has events that are associated with them which can trigger code to execute. These prove useful if you wish something to happen when, for example, a user opens up a workbook. The ThisWorkbook has the following events (among others) that it can respond to: Open, BeforeClose, BeforePrint, BeforeSave, SheetCalculate and SheetChange. You might want a dialog box to pop up before the user prints a sheet asking if they would rather print a data summary of the page. You might want to check what sheet has been activated on SheetChange in order to make sure that no user messes up certain crucial sheets. The list goes on… Each Sheet can respond to (among other events) Activate, Change and Calculate. Activate can be used if you want to clean up the page before a user sees it. Change can be (and has been) used to track changes that users make to worksheets. Calculate can be used to make some code act like a worksheet function, for example if you wanted to update a histogram every time a user entered some new data. You can get to these events by the same means you can get to UserForm events. You select the object you are interested in (by double clicking on ThisWorkbook or whatever Sheet) and then use the drop down above the upper left corner of the code sheet to select Workbook (in ThisWorkbook) or Worksheet (in a Sheet) and the events will show up in the drop down to the right. (Maddeningly, VBA will “guess” which one you want an create the code for it. Keep behavior like this in mind when you hear “Artificial Intelligence” bandied about as a solution to all of man’s problems.) So there you have it. We gave a concrete example of how to use a UserForm and controls and we talked about the events that the Excel object model allow you to respond to (and annoy users with). FINISH Page 8 of 8