21 UserForms

,

21.1 Using UserForms

An input box is a simple way to gather information from the user. But if there is a lot of information it may not be sufficient. Fortunately, VBA lets us create our own dialogue boxes where input boxes are not enough. Such a dialogue box is called a UserForm.

UserForms can be used for both displaying and gathering information. They can contain components such as labels, pictures, text boxes, command buttons and list boxes. We can actually build almost the entire user interface with the help of UserForms.

To create a UserForm select UserForm from the Insert menu in VBE. This will open a new window with an empty dialogue box and a small toolbox window with components that can be dragged onto the dialogue box surface (see figure 21.1). If the small toolbox window is not visible you can select Toolbox from the View menu, or simply click the Toolbox button on the toolbar.

After you have created a new UserForm you will notice that a new category (Forms) has been added in the Project Explorer window. Under the Forms category you will find all UserForms that have been created. Right-click on the name of one of the UserForms and then select View object or View code. If the first selection is made the window shown in figure 21.1 will open. If View code is selected a new code window will be opened in the right pane. In this code window we will write event handlers that will be executed when certain events are taking place, for example a button is clicked or an item is selected from a list box.

When a new UserForm is created you must give it a name. Select a name that will give an indication of the purpose of the form. If it will be used to show or read personal information the name frmPerson may be suitable. frm is a prefix that is often used when naming forms so that it is easy to see that the name represents a form and not another kind of object.

Setting the name of a form

Follow these steps to name a UserForm (see figure 21.2).

1  Click on the UserForm in the window.

2  Set the Name property in the Properties window to a new name.

3  Optionally click on Caption and type in a new caption for the form (see below).

The Name property represents the name of the form (object). This name will be used in code to refer to the form. Caption is the text that is shown in the title line of the form and is what the user sees when he opens the form. Name and Caption can be equal, but they don’t have to be.

images

Figure 21.1   New blank UserForm and Toolbox window.

Placing components on the form

Components, or controls as they are also called, are objects that are contained within UserForm objects. They are used for displaying information or for gathering information from the user. For example, a label may be used to display text on the form, while a check box may be used to select an option. To place a control on a form there are two methods available, as follows.

First click on the control icon in the toolbox window to select a control. Then click on the surface of the form where you want the upper left corner of the control to appear.

Or, click on the control icon in the toolbox window to select a control. Draw the outline of a rectangle on the surface of the form while holding the left mouse button down. When the button is released the control is placed within the rectangle.

In both cases you can change the size of the control by clicking on it and then dragging one of the handles. The control can be moved by clicking on it and then dragging it while the left mouse button is held down. Release the button when the control is in the right position.

images

Figure 21.2   Setting the Name of a UserForm.

To select a control on a form, all we have to do is click on it. If you want to select more than one control (for example you want to move them) you must hold down the Ctrl-key and then click on each control in turn. Alternatively you can draw a rectangle on the screen by holding down the left mouse button. All the controls within or partly within this rectangle will be selected when you release the button.

Shortcut

To place many controls of the same type on the form just double-click on the control icon in the toolbox window. Then click repeatedly on the form where you want to place the controls.

Controls

Table 21.1 gives a description of the most common controls in the toolbox window.

Using the grid

Every form has a grid, i.e. a set of intersecting lines used to align controls. The grid may not be visible, and it can also be turned off. When you drag a control onto the form it will snap to the nearest intersection of lines in the grid. This happen even if the grid is invisible. In this way it is easy to make sure that all controls on the form are perfectly aligned and thereby give the form a professional look and feel.

Table 21.1 Controls in the Toolbox window

Control

Description

Select object

This is not actually a control. We must click on this before we can select controls on the form.

Label

Displays descriptive text such as titles, captions, pictures, or brief instructions. It cannot be changed by the user.

TextBox

Most commonly used to display information entered by a user. Also, it can display a set of data, such as a calculation result.

ComboBox

Combines the features of a TextBox and a ListBox. The user can select an existing value, or enter a new value.

ListBox

Used to select one or more values from a list of values.

CheckBox

Use to select between two options (Yes/No, On/Off, True/False, etc.).

OptionButton
(or RadioButton)

Used to select one of several options in a group.

ToggleButton

Used to show if some state is active (button is shown as pushed in) or inactive (button is shown as released).

Frame

Used for grouping controls on a form.

CommandButton

Used to start or interrupt an action or series of actions when clicked by the user.

TabStrip

Contains a collection of one or more tabs. Similar to MultiPage.

MultiPage

Used to display several pages of information. Only one page is displayed at a time. Each page is selected by clicking on a tab.

ScrollBar

Used for creating scrollbars on the form.

SpinButton

Increments or decrements numbers. Can be combined with a text box so that the user can click on small arrows to increase or decrease the value in the text box.

Image

Used to display a picture on the form.

RefEdit

Used for selecting a cell area from the spreadsheet.

images

Figure 21.3   UserForm with various controls.

If you don’t want to use the grid you can turn it off, or if you want another distance between the points in the grid, or you want to make the grid visible you can select Options under the Tools menu item. This will bring up the dialogue box shown in figure 21.4.

images

Figure 21.4   The VBE Options dialogue.

Select the General tab. On this page you can set the properties of the grid.

There is also another way to align controls on a form. Select Align under the Format menu item. If you want to align a number of controls so they have the same distance from the left edge of the form you first select them (by holding down the Ctrl key and then clicking on each one in turn, or by drawing a rectangle around them). Thereafter you click on the Format menu item, and then on Align and Left. The Format menu also has other interesting options. You can make the controls the same size by selecting Make Same Size. The first control selected determines the size. If you want to make sure that the controls are evenly distributed, either horizontally or vertically, you can select Horizontal Spacing or Vertical Spacing.

Tab Order

When a dialogue box is displayed on the screen the user may move the focus from control to control by pressing the Tab key, or move backwards by pressing Shift+Tab. The control that will receive the focus is determined by the control’s tab order. The control with the least tab order will be the next to receive the focus. When the dialogue box is opened the control with tab order 0 will be selected. The user may also move the focus to a control simply by clicking on it with the mouse.

The tab order of a control can be set by clicking on the control and then type in a value for TabIndex in the properties window. This is repeated for every control that can receive the focus (see below). Use integer numbers starting with 0 and increment by 1 for each new control.

Some controls, for example labels, do not need a tab order because they never will need to receive the focus. Therefore the property TabStop is set to False for these controls. The controls with TabStop set to False cannot receive the focus.

For frames, which may contain other controls, you first need to set the tab order for the frame. After you have done this you set the tab order for the controls within the frame. Within the frame the numbers should start with 0 again.

The tab order can also be set from a dialogue box by selecting Tab Order from the View menu. See figure 21.5. To the left is a list of the controls on the form. The tab order increases from the top down. You change the order by clicking on a control name and then on the Move Up or Move Down button. Repeat this until the order is how you want it to be, and then click OK.

images

Figure 21.5   The Tab Order dialogue.

After all controls are placed on the form and their tab order is set you can check the result by pressing the F5 key. Then press the Tab key to see that the focus moves as you want it to. Also try Shift+Tab. Before you press F5 the form must be active. Click on the title line of the form to activate it. Alternatively, you may write a small subroutine to open the form:

Sub TestForm()

frmPerson.Show    ' Show the form with the name frmPerson

End Sub

Example 21.1

We will create a macro that calculates the value of a call option or a put option by using a simple One Period Binomial Model. The macro will read the current price of the underlying asset, the one period interest rate, the exercise price, the increase and decrease, and whether it is a call or a put option. See chapter 13.3 for the necessary formulas.

images

Figure 21.6   The Call/Put Option dialogue.

We’ll start by creating a form that can be used to get information from the user.

Create a new form by selecting UserForm from the Insert menu.

Place two frames, five text boxes, six labels, two option buttons, and two command buttons on the form. Some of the controls will be placed within a frame. Activate the frame by clicking on it before you place the control there. The control will then be moved if you move the frame.

Make sure that the form looks like the one in figure 21.6.

Set the Tab order of the controls such that one can move the focus from text box to text box and then to the buttons.

Every control on the form (and also the form itself) is an object with its own methods and properties. The properties can be set by first clicking on the control and then setting the value in the Properties window.

Set the names of every control to the values listed below:

frmOption (name of the form)

txtCurrent, txtExercise, txtRise, txtFall, txtInterest

(names of text boxes)

optBuy, optSell (names of option buttons)

btnClose, btnCalculate (names of command buttons)

lblMessage (name of message label at the bottom of the form)

You may keep the default names for the frames and other labels.

You are free to choose whatever name you want for the controls, but the same rules that apply to variables also apply to control names. Many programmers use a prefix for each control name so that it is easy to tell what kind of control it is just by looking at the name. This naming convention is called Hungarian notation. See table 21.2 for the most common prefixes used.

In addition to the name we will also set a few other properties. Since the text boxes will be used for numbers we want to right-align the numbers within the box. Set the property TextAlign to TextAlignRight for every text box.

Table 21.2 Hungarian notation

Control

Prefix

UserForm

frm

TextBox

txt, edt

OptionButton

opt, rad

CommandButton

cmd, btn

CheckBox

chk

ListBox

lb, lst

ComboBox

cbo

RefEdit

ref

Label

lbl

The two option buttons belong in a group. Set the property Value to True for the button optBuy. This will automatically select the Buy option when the form opens.

Properties can also be set while the program is running. We’ll show you how in the next section.

More on OptionButtons and CommandButtons

Option buttons are used when you want to let the user select just one option from a set of alternatives. If more options are to be allowed at the same time you should use check boxes instead. Option buttons that belong together can be placed in a group. One simple way to do that is to place the buttons within a frame. Another way is to set the GroupName property to the same value (a string) for all the buttons in the group.

A command button with the Default property set to True will act as a default button, meaning that if you hit the Enter key it will have the same effect as a click on the button. Only one button on a form can have this property set to True. Setting the Cancel property to True for a button means that you can press the Esc key to simulate a click on the button. Do this for only one button on the form.

The Accelerator property allows us to assign a key to a button so that we can press Alt+key to simulate a click on the button. Let’s give a small example. We want to simulate a click on the Calculate button in example 21.1 with the key combination Alt+C. All we have to do is set the Accelerator property to one of the letters in the caption (C in our case). After we have done this the C in the caption will be underlined, telling us that we can press Alt+C to activate the button.

Also set the Cancel property to True for the Close button to close the form if the user presses Esc.

Writing code

Having created the form the next step is to write some code that will be executed when the user does something with the form such as clicking on a button or writing text in a text box. This means we will have to write some event handlers. Event handlers are written in a code module for the form. The code window can be opened in several ways:

•  right-click on the name of the form in the project window and select View code

•  double-click somewhere in the form

•  right-click somewhere in the form and select View code

•  select Code from the View menu

•  press F7.

The combo box in the upper left corner in the code window shows a list of all the controls (objects) on the form including the form itself (see figure 21.7). The form will always be shown as UserForm in this list even if you have assigned a name to the form. When you are writing an event handler you always select the name of the object from this list first, and then you select a particular event handler from the list in the upper right corner.

images

Figure 21.7   UserForm Code window.

When you first open the window there is already an empty event handler in the code. UserForm_Click is an event handler that will be executed each time the user clicks in the form. You may try this by writing the following code:

Private Sub UserForm_Click()

MsgBox “Oops, I’m clicked”

End Sub

Then press F5 to run the program and click in the form to see what happens.

Notice that the message box does not show if you click on a control on the form or in the title line of the form.

Event handlers have names that put together the name of the object and the name of the event. The names are separated by an underscore character.

We do not need the UserForm_Click event handler in this example, so you can delete it.

Event handlers

The Initialize event happens when the form is opened, but before it is shown on the screen. As the name implies, it is used for initialization purposes. For example, option buttons must be initialized such that one of them is selected. We selected the optBuy button by setting the property Value to True while designing the form. We could have done the same in the Initialize event handler.

Private Sub UserForm_Initialize()

optBuy.Value = True

End Sub

The form has two command buttons. We must write event handlers for a click on the buttons. We’ll start with btnClose. Select btnClose from the object list and Click from the event list. A faster way to write a click handler is to double-click the button.

Private Sub btnClose_Click()

Unload Me

End Sub

Unload Me is a statement that will close the form. It is common to use the name Me when referring to the form from within one of the event handlers. The name of the form can also be used:

Unload frmOption

The event handler for the Calculate click event is more involved. When the user clicks on this button the function CalcOV will be called to calculate the option value. The function CalcOV is an ordinary VBA function written in a code module. It will be called from the event handler. The function is declared as

Public Function CalcOV(ByVal currentPrice As Double, _

ByVal exercisePrice As Double, _

ByVal rise As Double, _

ByVal fall As Double, _

ByVal interest As Double, _

ByVal opt As Boolean) As Double

'  We’ll just let the function return 0 for now

CalcOV = 0

End Function

Before continuing, create a code module and write this function. Let the function return the value 0 for the time being.

Let’s get back to the form. The arguments for the CalcOV function can be extracted from the text boxes by reading the Value property. For example the interest rate can be read as

txtInterest.Value

We also need to find out which option button is selected. Again, the Value property will tell.

'  Check if the optBuy button is selected

If optBuy.Value = True Then

'  The Buy button is selected

Else

'  The Sell button is selected

End If

Then we have all the pieces we need to write the event handler.

Private Sub btnCalculate_Click()

Dim value As Double

On Error GoTo PROC_ERR

'  Checking if the text boxes are empty

'  vbNullString is a predefined constant in VBA

'  It may be replaced by “ ”

If txtCurrent.value = vbNullString Then

MsgBox “Current price is missing”

txtCurrent.SetFocus

Exit Sub

End If

If txtExercise.value = vbNullString Then

MsgBox “Exercise price is missing”

txtExercise.SetFocus

Exit Sub

End If

If txtRise.value = vbNullString Then

MsgBox “Rise percentage is missing”

txtRise.SetFocus

Exit Sub

End If

If txtFall.value = vbNullString Then

MsgBox “Fall percentage is missing”

txtFall.SetFocus

Exit Sub

End If

If txtInterest.value = vbNullString Then

MsgBox “Interest rate is missing”

txtInterest.SetFocus

Exit Sub

End If

' Calculate option value

value = CalcOV(txtCurrent.value, txtExercise.value, _

txtRise.value, txtFall.value, _

txtInterest.value, optSell.value)

' Print result in lblMessage

lblMessage= “The calculated value is “& Format (value, “0.00”)

Exit Sub

PROC_ERR:

MsgBox “Error: “ & Err.Number & vbCrLf & _

Err.Description, vbCritical

End Sub

To make sure that the program is as robust as possible we need to check the input against illegal values. In the example we check that none of the text boxes are empty. If an empty text box is found, a message box is displayed to tell the user what is wrong, and the focus is set to the empty text box. Since there is no point in continuing the procedure in such a case, the event handler is exited.

The error checking done here is by no means satisfactory. The user may still type in negative numbers, numbers that are too big, text, etc.

Another way of guarding against errors is to disable the Calculate button until all the values are valid. This can be done with

btnCalculate.Enabled = False

The button will appear grey and cannot be clicked.

The CalcOV function can be written as:

Public Function CalcOV(ByVal currentPrice As Double, _

ByVal exercisePrice As Double, _

ByVal rise As Double, _

ByVal fall As Double, _

ByVal interest As Double, _

ByVal opt As Boolean) As Double

Dim u As Double

Dim d As Double

Dim q As Double

Dim su As Double

Dim sd As Double

Dim cup As Double

Dim cdn As Double

Dim c0 As Double

Dim p0 As Double

u = 1 + rise / 100

d = 1 – fall / 100

interest = interest / 100

'  Calculate risk free probability for a rise

q = (1 + interest − d) / (u − d)

'  Calculate possible cash flows for the stock

su = currentPrice * u

sd = currentPrice * d

'  Calculate possible cash flows for the option:

'

'  If the price rises:

cup = su − exercisePrice

If cup < 0 Then cup = 0

'If the price falls:

cdn = sd − exercisePrice

If cdn < 0 Then cdn = 0

'  Calculate value of call option

c0 = (q * cup + (1 − q) * cdn) / (1 + interest)

Calculate value of put option

p0 = exercisePrice / (1 + interest) + c0 − currentPrice

If opt = True Then

CalcOV = p0

Else

CalcOV = c0

End If

End Function

All that remains now is to write some code to show the form on the screen. This can be done by writing a subroutine in a code module:

Sub Calc()

frmOption.Show

End Sub

The life of a form

A form can be displayed on the screen with a statement such as

frmOption.Show

Before the form is shown on the screen it is loaded from disk into memory if this has not been done before (see below). To hide the form and unload it from memory we write

Unload Me

'  or Unload frmOption

There are two other methods that can be used on forms – Load and Hide. They come in handy if you want to separate the load/unload process from showing/hiding it on the screen.

Load frmOption

'  The form is loaded into memory but is not shown

'  on the screen

frmOption.Show

'  The form is shown on the screen

frmOption.Hide

'  The form is removed from the screen but is still

'  in memory

frmOption.Show

'  The form is now in memory and is shown on the

'  screen again

Unload frmOption

'  The form is removed from memory

Some important events for a form are shown in table 21.3.

Table 21.3 A few UserForm events

Event

Happens when

Activate

the form is displayed on the screen (after Show is called)

Initialize

the form is read into memory

Terminate

the form is removed from memory (after calling Unload)

21.2 Control properties, methods and events

We’ll be looking at only a small selection of the properties, methods and events in this book. Please consult VBA help for more information.

Every control has the properties Name, Top, Left, Width, Height, Visible and Enabled. Top and Left contain the coordinates of the upper left corner of the control. Width and Height is the size (in points). Visible and Enabled are used to show/hide the control and to enable/disable it. Here are a few examples:

txtCurrent.Visible = False

'  Hides the text box

optSell.Visible = True

'  Shows the radio button

btnClose.Enabled = False

'  The button is disabled

txtCurrent.Enabled = True

'  The text box is activated

TextBox

The most important properties of text boxes are Text, Value, MultiLine and WordWrap. The Text property contains the text that is shown in the control. Any value you assign to the Text property is also assigned to the Value property. MultiLine is set to True if we want a multi-line text box. In this case WordWrap indicates whether the contents of the text box wrap at the end of a line. The default value is True which means that the text wraps. If the value is False the text does not wrap. WordWrap only has meaning when MultiLine is True.

The Cut and Copy methods can be used to cut or copy text from a text box. It can be pasted into a text box with the Paste method.

txtCurrent.Text = “240”

txtCurrent.Copy

txtExercise.Paste

The most important events are Click and Change. Click happens when the user clicks the text box with the mouse, and Change occurs when the Value property changes.

OptionButton, CheckBox, and ToggleButton

The most important property is Value which indicates whether the button is selected. The Caption property specifies the text that appears in the control.

The Click event occurs when the button is clicked by the mouse and the Change event when the Value property changes.

CommandButton

The Caption property contains the text shown on the button, and the Click event occurs when the button is clicked.

ListBox

The first thing we want to do is to fill the list box with items. It can be done in two ways. One is to call the method AddItem on the ListBox. The other is to fill the list box with data from the worksheet by assigning a range to the RowSource property. The following examples show both methods. The name of the ListBox is lstNames

lstNames.RowSource = “D1:D5”

lstNames.RowSource = [Bok1.xls]Ark2!D1:D5

In the last statement the values are fetched from another worksheet than the active worksheet. RowSource can be set both in code and in the properties window.

AddItem can only be used when the program is running:

lstNames.RowSource = ””

'  In case RowSource is already set

lstNames.Clear

'  Clears old content

lstNames.AddItem “Popeye”

lstNames.AddItem “Donald Duck”

lstNames.AddItem “Lucky Luke”

lstNames.AddItem “Snoopy”

lstNames.AddItem “Woody Woodpecker”

A third possibility is:

lstNames.List = Array(“Popeye”, “Donald Duck”, “Lucky Luke”, _ “Snoopy”, “Woody Woodpecker”)

When the user selects an item in the list box the text will be saved in the Value property.

MsgBox lstNames.Value

If an item has not been selected the statement above will generate an error message. It is therefore best to check if an item has been selected before we try to anything with it. The ListIndex property contains the index of the selected item starting from 0. If no item has been selected, ListIndex will return −1.

'  A better way to do it

If lstNames.ListIndex >= 0 Then

MsgBox lstNames.Value

End If

The attribute MultiSelect controls whether it is possible to select more than one item from the list box at a time. The default value is frmMultiSelectSingle (0), meaning only one item can be selected. If it is set to frmMultiSelectMulti (1) or frmMultiSelectExtended (2) then several items may be selected. Here’s how to get all the selected values:

Dim i As Integer

For i = 0 To lstNavn.ListCount − 1

If lstNavn.Selected(i) = True Then

MsgBox lstNavn.List (i)

End If

Next i

In this little example we have used some more properties and methods. ListCount is a property that tells us how many items there are in the list box. Selected is an array that contains True if an item with this index is selected. The List method contains the item value for the item.

Both the Click and Change events occur when the value changes.

ComboBox

A combo box is a combination of a list box and a text box. The user can select items from the list or type in a new value in the text box. The Style attribute must be set to frmStyleDropDownCombo to allow the user to type in text in the text box. This is the default value. To prevent a user from adding new items the Style property can be set to frmStyleDropDownList.

Items can be added to the combo box in the same way as they are added to a list box. If you want to set the text in the text box to one of the items in the list box it can be done with

ComboBox1.Text=ComboBox1.List (2)’ Select the 3rd item from the list

ComboBox1 is the name of the combo box.

To guard against an empty list it is better to write

If ComboBox1.ListCount > 2 Then

ComboBox1.Text = ComboBox1.List (2)

End If

It is not possible to select more than one item from a combo box. The most important events are Click and Change.

RefEdit

RefEdit has mostly the same properties and events as a text box. It is used for selecting ranges from a spreadsheet. After the RefEdit control has received focus you can select a range in the worksheet and the reference will be copied into the text box.

21.3 Modal or modeless forms

A form can be either modal or modeless.A modal form must be closed or hidden before the user can continue working with the rest of the application. Modeless forms let you continue working with the rest of the application while the form is displayed.

UserForm1.Show vbModal

' Display a modal form

UserForm1.Show vbModeless

'Display a modeless form

Modeless forms do not appear in the taskbar.

When creating the form you can also set the property ShowModal to True (default) or False in the properties window. It’s read-only at run-time. The form can then be displayed with

UserForm1.Show

It may seem natural to always use modeless forms, but there are caveats. Suppose you have made a form that will automatically write a new value into a cell in the worksheet when it closes. While the form is open you change the cell content directly in the worksheet. This value will then be overwritten when the form closes.

Modal forms are simpler to program and gives you more control of the application.

Office 97 UserForms are always modal.

Example 21.2

In this example we’ll create an application that can help the user to find a restaurant to his or her liking. The application uses a worksheet containing data for a number of restaurants. A small excerpt of this worksheet is shown below. For each restaurant is stored the name, place, type of food, quality rating (1 to 3 stars), and price category (1 to 3).

images

Figure 21.8   The Restaurant worksheet.

To make it simple to find restaurants from this list we’ll create a form that is shown in figure 21.9. After the user has entered the necessary data and clicked the Find Restaurant button, a list of restaurants that conform to the criteria is shown in the list box on the right.

images

Figure 21.9   The Restaurant Picker Form.

The form has three combo boxes, one list box, one frame, three option buttons, and two command buttons. The names are cboCity, cboType, cboQuality, fraPrice, optPrice1, optPrice2, optPrice3, lstRestaurant, btnClose, and btnFind. The Cancel property is set to True for the Close button so that the form will close when the Esc key is pressed. It will not be possible to type in a new value in the ComboBox cboQuality It therefore has its Style set to frmStyleDropDownList. The tab order is set so that the focus will move to the next control below the current one or to the next column if the bottom of the form is reached.

The UserForm_Initialize handler is used to initialize all the controls.

We will read the names of the different cities from column B in the worksheet and save them in the combo box. We are facing a little problem, though. Since the names are repeated several times we need to remove duplicates before we save them in the combo box. The easiest way to remove duplicates is to sort the names in alphabetical order. Therefore we will copy the names into an array (Variant) and sort this by using the selection sort algorithm from chapter 20. After the table is sorted we remove duplicates by only copying a name back into the combo box if it is different from the previous name in the array. The complete subroutine SortAndRemoveDuplicates is shown below. The same procedure must be done to the type of food in column C.

The project consists of two code modules – a general code module Module1, and a code module for the frmRestaurant form. The source code for both modules is shown below.

images

images

images

images

Two event handlers for button clicks must be written. The first one, btnClose_Click, is very simple and just closes the form. Most of the work is done in the btnFind_Click handler.

The routine starts with validating the input, i.e. checking that all values are given. Two variables are used for counting the number of stars, and for the price category. The number of stars is calculated from the length of the string. The price category is found by checking which option button is selected.

The search for restaurants is done by the ListRestaurants subroutine. See comments in the source code.

To make it easy to run the macro we’ll put a button in the worksheet as shown in figure 21.8. The only thing remaining is to write a procedure that will open the form when this button is clicked.

Sub RestaurantSearch()

frmRestaurant.Show vbModal

End Sub

Problems

21-1.  Suppose you invest £10,000 in stocks (£6,000) and bonds (£4,000). Every quarter you’ll want to rebalance your investments to keep the stock/bond ratio equal to 60/40. Create a UserForm that has two text boxes for typing in the current values of stocks and bonds, and a button for rebalancing the portfolio. The result should be presented in a label on the form, for example “Sell stocks for £200”.

21-2.  Applications uses splash screens to notify the user that the program is in the process of loading. Create a form that can be used as a splash screen. The form will automatically show when a new workbook is opened, and then go away after a few seconds. In the form you can display a picture, the name of the application and some copyright information.

21-3.  Change the restaurant form so that it is possible to select more than one price category at the same time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset