+ All Categories
Home > Documents > exlvba-t2

exlvba-t2

Date post: 04-Oct-2015
Category:
Upload: jmcc2
View: 2 times
Download: 0 times
Share this document with a friend
Description:
excel
Popular Tags:
21
University of Bristol Information Services document exlvba-t2 VB Excel 97/2000: Custom dialog boxes Practical workbook Aims and Learning Objectives By the end of these notes, you will be able to use the Visual Basic Editor (VBE) in Excel to create a custom dialog box (referred to throughout as a form) for use within your Visual Basic modules. You will be able to: Create a user form Add controls to the form and set control properties Specify an initial state for each control Write the associated event procedures Update worksheets based on values taken from the form
Transcript
  • University of Bristol Information Services document exlvba-t2

    VB Excel 97/2000: Custom dialog boxes

    Practical workbook

    Aims and Learning Objectives

    By the end of these notes, you will be able to use the Visual Basic Editor (VBE) in Excel to create a custom dialog box (referred to throughout as a form) for use within your Visual Basic modules.

    You will be able to:

    Create a user form

    Add controls to the form and set control properties Specify an initial state for each control Write the associated event procedures Update worksheets based on values taken from the form

  • VB Excel 97/2000: Custom dialog boxes (01.04) http://www.bristol.ac.uk/is/selfhelp/documentation/exlvba-t2/exlvba-t2.doc

    If you have any comments or queries about this document mail [email protected].

    This document may be used wholly or in part by the academic community, providing suitable acknowledgment is made. It may not be used for any commercial or profit-making purpose without permission. 2004 University of Bristol. All rights reserved.

    Document information

    Format conventions The following format conventions are used in this document:

    Computer input that you type is shown in a boldCourier font

    http://www.bristol.ac.uk/

    Computer output, menu names and options, buttons, URLs are shown in a Courier font

    Save, Go to, Refresh

    Text that you must replace is shown in italics Enter your username Computer keys that you must press are in a boldCourier font and enclosed in angle brackets

    , , ,

    Instructions for users of other software versions are displayed in a shaded area.

    Example text like this

    Shortcut keys The following shortcut keys are used throughout the document:

    To open the Visual Basic Editor or to switch between the editor and the worksheet.

    To display the properties window for the selected object (for example, a form or control).

    From the user form window, press to select or open the user form code window.

    From the user form code window, press to select the user form window.

    Related documentation The following local documents are available from the Web:

    Visual Basic for Excel 97/2000 (document exlvba-t1).

    Other books are available:

    Writing Excel macros, Steve Roman, (Excel 97 and 2000) O'Reilly http://www.oreilly.com/

    Excel 97 Programming for Windows for Dummies, John Walkenbach

    Excel 2000 Programming for Dummies, John Walkenbach

  • Contents

    Format Conventions

    Shortcut keys

    Related documentation

    Task 1 Creating a user form......................................................................... 1

    Task 2 Adding controls ................................................................................. 2

    Task 3 Setting control properties................................................................. 3

    Task 4 Initialising controls ........................................................................... 5

    Task 5 Event procedures .............................................................................. 6

    Task 6 Displaying your custom box............................................................. 7

    Task 7 ListBoxes............................................................................................ 8

    Task 8 Using variables in label controls ...................................................... 9

    Task 9 Dealing with numerical input......................................................... 11

    Task 10 Performing calculations................................................................. 12

    Task 11 Unloading forms............................................................................. 13

    Appendix A Combo boxes ....................................................................... A-1

    Appendix B Spin buttons......................................................................... B-1

    Appendix C Initialising controls............................................................. C-1

    Appendix D Keyboard shortcuts ............................................................ D-1

    Appendix E Inserting formulae .............................................................. E-1

  • Introduction

    When only a few pieces of information are required from the user (for example, a text string or a Yes/No/Cancel answer), then the use of InputBox and MsgBox commands (described in the document Visual Basic for Excel 97/2000) is adequate. If you need to gather more information for your Visual Basic application, then Custom dialog boxes (known as User Forms) are required.

    These tasks lead you through the steps involved in creating a custom dialog box using the facilities available in Microsoft Excel's Visual Basic Editor.

    Prerequisites

    It is essential that you are a competent Excel user and have successfully completed the macro tasks in Visual Basic for Excel 97/2000 (document exlvba-t1). You will also require access to the Microsoft Excel 97 or 2000 software.

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 1

    Task 1 Creating a user form Objectives To create a custom Dialog Box for use within an Excel workbook.

    Method You will use the Insert UserForm menu command. Comments A user form is the basis of a dialog box and will contain most of the programming

    required to display and run a dialog box.

    1.1 Open the workbook vbdialog.xls. If you are working in the Computer Centre training rooms, this file is in the folder C:\User\Excel.

    The first sheet, Orders, contains a list of fictitious office supply orders. The other sheet, Items, contains a list of items and a simple account code lookup table. Take a few moments to look at the structure of the workbook and the defined ranges.

    1.2 The user form you are going to create will ask the user to type in an order number, choose an item from a list box and enter the quantity of items required. The unit cost for the selected item will be displayed on the form. The finished form will resemble figure 1.

    We will start with a simplified version with an Order number text box and an OK command button.

    1.3 Open the Visual Basic editor (VBE) by pressing .

    1.4 From the Insert menu, select UserForm.

    A new form, UserForm1, is added to your VBA project as in figure 2.

    Figure 1 - completed user form

    Figure 2 Visual Basic user form window

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 2

    Task 2 Adding controls Objectives To add Command buttons and other controls to your user form.

    Method You will use the control toolbox. Comments Unlike most Windows commands, Excels VBE does not have alternative menu

    commands to allow you to add controls to a user form. To add controls, you must use the toolbox.

    2.1 The controls toolbox should be displayed when you select the user form (figure 2). If not, from the View menu, select Toolbox.

    2.2 Drag a Label from the toolbox to the top left hand corner of the user form. Dont worry about the text or the precise positioning at this stage. For now the label will contain the text, Label1.

    2.3 Drag a TextBox just to the right of Label1.

    2.4 Add a CommandButton to the bottom right of the user form.

    Your form should now resemble Figure 3.

    Figure 3 - user form containing label, text box and command button controls

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 3

    Task 3 Setting control properties Objectives To name and label the controls created in the previous task and explore form layout

    options.

    Method You will use the Properties window and the Format menu commands. Comments If the Properties window is not displayed; from the View menu, select

    Properties window (or press ).

    3.1 Select Label1 (click once on the relevant control in your user form).

    The properties window (figure 4) displays a table of properties relevant to that control. The left hand side gives the property name and the right hand side contains its value.

    3.2 Click in the box to the right of (Name), overwrite Label1 with OrderLabel and press .

    Note The name is used throughout your programming modules to refer to this part of the user form. It should contain no spaces. Remember to press after typing the label name.

    3.3 Select the Caption value, type Order number: and press .

    The caption is the text that is displayed in the control on the form.

    3.4 From the user form, select the text box added in task 2.3 and set its (Name) property to OrderNo

    3.5 With the text box OrderNo still selected, press and select the OrderLabel control.

    Both the textbox and label controls should now be selected.

    From the Format menu, select Align / Tops.

    Take a few moments to examine the other commands available from the Format menu.

    Note Controls can also be aligned and sized using the mouse or by adjusting the values Left, Top and Width in a controls properties window. For precise positioning and sizing of these controls, see the list of property values in appendix 3.

    3.6 Click once on the command button to select it and set its (Name) property to OKButton

    Set Caption to OK and Default to True.

    3.7 Finally, select the user form, UserForm1 and set its properties: (Name) NewOrderForm Caption Add new order

    The title bar of the user form is amended as you type.

    Note There are many properties associated with different control types. The help screens will explain the purpose of each one. Controls can also be set or altered by programmed subroutines as we will see later.

    Figure 4 - properties window (Label1)

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 4

    Task 4 Initialising controls Objectives To set the initial state of controls created so far.

    Method You will use the user form code window.

    4.1 Double-click on your user form.

    The user form code window opens displaying a subroutine structure to contain the commands to be run when your user form is clicked:

    Private Sub UserForm_Click()

    End Sub

    4.2 To write the code required to set the initial state of the user form, click on the Procedure window (currently displaying Click) and select Initialize (figure 5).

    A new procedure, UserForm_Initialize() is inserted.

    4.3 At the current cursor position enter the following code to set the focus to the textbox control when the form is initialised: OrderNo.SetFocus

    You will add more code to this window after you add the other controls (displayed in Figure 1) to this form.

    Figure 5 - procedure window

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 5

    Task 5 Event procedures Objectives To create the event procedures required when the OK control is selected.

    Method You will use the user form code window. Comments Event procedures are those subroutines that are executed when a user selects or

    changes the value of any of the controls on a form.

    5.1 From the Window menu, select the user form window, NewOrderForm (UserForm) (or press ).

    5.2 Double-click on the OK command button to create a procedure to contain the commands to be run when the OK button is selected.

    Complete the code in bold: Private Sub OKButton_Click()Sheets("Orders").ActivateIf IsEmpty(Range("A2")) thenRow = 2

    ElseRange("A1").End(xlDown).SelectRow = ActiveCell.Row + 1

    End IfCells(Row, 1).SelectCells(Row, 1) = OrderNo.Text

    End Sub

    When the OK button is selected, the orders sheet is activated and the cell A2 is checked to make sure it contains an entry. If not, the orders entered by the user will start at this point.

    If A2 is not empty, then the end of the current column is located and selected. A variable Row is then assigned to the row beneath the current selected cell and in turn selected.

    The value for OrderNo is then placed in the first column (column 1).

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 6

    Task 6 Displaying your custom box Objectives To display the dialog box.

    Method You will use the Insert Module command and the Show property. Comments The procedure used to display the dialog box is stored in a new module.

    6.1 From the Insert menu, select Module.

    A new module, Module1 is inserted in your VBA project.

    6.2 Add the following code: Sub AddOrder()NewOrderForm.Show

    End Sub

    6.3 From the File menu, select Save vbdialog.xls.

    6.4 Return to your Excel worksheet (click on the workbook icon in the Windows taskbar).

    6.5 From the Tools menu, select Macro/Macros.

    Select the AddOrder macro and assign a shortcut key (+) (under Options).

    Click on Cancel.

    6.6 Test your macro by pressing +.

    6.7 Enter an order number (for example, BA1001) and click on OK.

    The order number should be entered in the next available row (in this case A2).

    6.8 Check that your Visual Basic works as expected.

    Click the close button (x) in the top right-hand corner of the form to exit your macro.

    6.9 Highlight and delete any rows you have added whilst testing your code

    6.10 Switch back to the VBE (press or click on the icon in the Windows taskbar).

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 7

    Task 7 ListBoxes Objectives To display a list of office items.

    Method You will use the control toolbox.

    7.1 Using the toolbox, add a ListBox

    control beneath the order number controls.

    Position and resize it as in figure 6.

    7.2 Set its name property to ItemBox

    7.3 Locate the property RowSource and set this to Items the listbox will display the first column of the

    defined range Items.

    Note If you wanted to display additional columns from that range, you could increase the value of the ColumnCount property.

    7.4 When the user of the form selects an option from the list of items, the value of this option is assigned to the Text property of that control. This property then needs to be added to column 2 (B) of the Orders worksheet. To do this, double-click on the OK button and add the following code, immediately above the End Sub statement:

    Cells(Row, 2) = ItemBox.Text

    7.5 Switch to the workbook, save and test the form.

    7.6 Close the form (x) and return to theVBE.

    Note A ComboBox control could also be used to contain a list of items. For guidance on populating a combo box, see appendix 1.

    Figure 6 - user form with ListBox control

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 8

    Task 8 Using variables in label controls

    Objectives To obtain a value from the current workbook and display the result in the form. Method You will use the Properties window to insert more controls and you will write code to

    update a label control with the unit price of the selected item.

    Comments The unit price is contained in the range Items, stored in the Items worksheet.

    8.1 Using the user form window, add two

    label controls and a textbox

    control as in figure 7.

    8.2 Using the Properties window (as in task 3) assign names to labels Label1 and Label2 (QuantityLabel and UnitCost respectively) and a name

    to the textbox (Quantity).

    8.3 Select QuantityLabel and set its caption to Quantity:

    Select UnitCost and set its caption property to Cost per item: 0.00

    This caption is initially set to display a zero amount. The steps below explain how to update this figure in line with the current list box selection.

    8.4 Double-click on ItemBox (the list box).

    The code window is displayed showing a new procedure, ItemBox_Click().

    8.5 Select the Procedure dropdown box (currently displaying Click) and change the selection to Change.

    8.6 Enter the following code (in bold): Private Sub ItemBox_Change()Set ir = Range("Items")mCost = WorksheetFunction.VLookup(ItemBox.Text, ir, 5)tCost = Format(mCost, "#,##0.00")UnitCost.Caption = "Cost per item: " & tCost

    End Sub

    These lines of code are run whenever the value in ItemBox is changed. The variable tCost is used to contain the text format of the variable mCost.

    Note Excel 2000 users may prefer to use the FormatCurrency() function as follows:

    tCost = FormatCurrency(mCost)

    8.7 Switch to your workbook, save and test the form. Check that the unit cost figure displayed in the form changes when you change the item selection in the item box.

    8.8 Close the form (x) and switch back to the VBE.

    Note This example assumes that we will be using a text box to input the quantity value. Assuming that the minimum and maximum quantity values are known, it might be

    Figure 7 - quantity and unit cost controls

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 9

    preferable to use a spin button to increment/decrement the numbers input. Appendix 2 explains how to use a spin button control.

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 10

    Task 9 Dealing with numerical input Objectives To limit the Quantity control to numerical values only.

    Method You will use the VB editor.

    9.1 Using the forms window, double-click on the Quantity text box control.

    The procedure Quantity_Change() is inserted in order to contain the code to be run whenever the value Quantity is altered.

    9.2 To ensure that the form accepts only numerical input, enter the following code to blank the value of Quantity if any non-numerical value is entered.

    9.3 If Not IsNumeric(Quantity.Text) ThenQuantity.Text = ""

    End If

    9.4 To enter the quantity into column 4 (D) of the worksheet, locate the OKButton_Click() procedure and add the following code, immediately above the End Sub statement: Cells(Row, 4) = Quantity.Text

    9.5 To enter the unit cost into column 5 (E) of the worksheet, you can use the value calculated in the ItemBox.Change() procedure (added in task 8.6):

    Press and type the following:

    Cells(Row, 5) = mCostCells(Row, 5).NumberFormat = "$#,##0.00"

    As the mCost variable is now being used outside a single procedure or function, you will need to declare it at the top of the module:

    Press to go to the top of the user form code window and insert a new line.

    9.6 Enter the following declaration: Dim mCost As Double

    9.7 Switch to the worksheet, save and test your form. Try entering a non-numerical value and then enter a numerical value to check that your quantity and unit cost are entered into columns D and E correctly.

    Note You may wish to add additional coding to the Quantity_Change() procedure so that only whole numbers are accepted.

    9.8 Close (x) the form and switch back to the VBE.

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 11

    Task 10 Performing calculations Objectives To apply functions to values collected from a form and update the worksheet.

    Method You will use the user form code window. Comments An alternative method would be to insert the formulae for Acc. Code and Total

    into the worksheet (see Appendix 5).

    10.1 From the user form window, double-click on the OK button to return to the OKButton_Click() procedure.

    10.2 Insert a new line above the End Sub statement.

    10.3 To calculate the total in column 6 (F), enter the following code: Cells(Row, 6) = mCost * Quantity.Text

    10.4 The account code in column 3 (C) is calculated from the table named Items using the lookup function. To do this, enter the following code:

    acc_code = Application.WorksheetFunction.VLookup(ItemBox.Text,Range("Items"),4,False)

    Cells(Row, 3) = acc_code

    Note The variable acc_code is used to calculate the string containing the result of the sum. In more complex examples, this could be used to break the string construction into simpler chunks.

    10.5 Finally, tidy up the worksheet, ensuring that all the columns are best-fit by adding the line:

    Columns("A:H").AutoFit

    10.6 Switch to your workbook, save and test the form.

    10.7 Switch back to the VBE.

    Note To improve this application further you should introduce additional error checking to deal with the scenario where an entry is not found in the lookup table, on the lines of the following:

    On Error Goto NotFoundacc_code = Application (etc)

    Exit Sub

    NotFound:Cells(Row,3) = "Not found"

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 12

    Task 11 Unloading forms Objectives To create a Cancel or Close button for the user form and perform additional error

    checking.

    Method You will use the control toolbox and the VBE user form code window. Comments The user form was initially displayed using the Show property. To close down or stop

    displaying the form the command Unload is used.

    11.1 From the NewOrderForm (UserForm) window and using the control toolbox,

    add a CommandButton control to the left of the OK button (as task 2.4).

    11.2 Modify its properties as follows:

    Give the button a name (for example, CancelButton), set the Cancel property to True and the Caption property to Close (or Cancel).

    The Default property should now be set to False.

    11.3 Double-click on your Close button to create and insert the code to unload the user form when this button is selected:

    Unload NewOrderForm

    11.4 At the beginning of the OKButton.Click procedure insert the following code: If ItemBox.Text="" or Quantity.Text="" ThenMsgBox "You must specify a valid item and" & _" a Valid number of items.", VBOkOnly, "AddItems"Exit Sub

    End If

    11.5 Click on the Save button in the toolbar.

    11.6 From the File menu, select Close and Return to Microsoft Excel.

    11.7 Run your macro and test that the cancel command button works.

    11.8 The solution file, vbdialog_complete.xls, contains a working version of this macro.

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) A-1

    Appendix A Combo boxes Comments This appendix supplies some code to allow you to populate a combo box with a

    named range in a workbook.

    These notes assume that you have a form containing a combo box named ItemBox. You should also have a range named Items containing the values you wish to populate the combo box with.

    To populate ItemBox with the values in the first column of the range Items, you need to write some code that is run when the form is initialised.

    Double-click on the user form to go to the UserForm_Initialize() procedure.

    Immediately above the End Sub command of this procedure, add the following code:

    Set ItemRange = Range("Items")nItems = ItemRange.Rows.CountFor r = 1 To nItemsItemBox.AddItem ItemRange.Cells(r, 1)

    Next rItemBox.ListIndex = 0

    Note The variable ItemRange is used to refer to the range named Items in the workbook.

    The number of rows in this range is calculated and stored in the variable r.

    A fornext loop is then used to add the value of the cell in the first column of each row, r to the control named ItemBox.

    The ListIndex property is used to display the first item in the list (0, not 1).

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) B-1

    Appendix B Spin buttons Comments To use a spin button control effectively you need to link it to another control, such as

    a textbox, so that when the value of the spin button is altered, the value displayed in the text box is likewise altered. The text box value must also not be allowed to exceed the Minimum/Maximum range set by the spin button control properties.

    These instructions assume you have a form containing a text box control (named Quantity) and a spin button control (named SpinButton). In the example worked through above, this should be placed on the form immediately to the right of Quantity.

    When the text box value changes Set the spin buttons Min property to 1 (the Max property is set to 100 by default).

    Select Quantity and set its Value property to 1.

    Double-click on the Quantity control and amend the code as follows:

    Sub Quantity_Change()Dim n As IntegerIf Not IsNumeric(Quantity.Text) ThenQuantity.Text = 1

    Elsen = Quantity.ValueIf n < SpinButton.Min Then n = SpinButton.MinIf n > SpinButton.Max Then n = SpinButton.MaxQuantity.Value = n

    End IfSpinButton.Value = Quantity.Value

    End Sub

    In the above code, Quantity.Value = n is used to set the value of Quantity in case the original value was outside the chosen bounds. SpinButton.Value =Quantity.Value ensures that the spin button is coordinated with the Quantity boxs value.

    When the spin button value changes From the NewOrderForm window, double-click on the SpinButton and add the code (in bold):

    Private Sub SpinButton_Change()Quantity.Text = SpinButton.Value

    End Sub

    In other words, when the value of the spin button is changed, the current value of the textbox (text property) is changed to match it.

    Note An alternative to the code used above (when the text box value changes) is to not enter any size checking at this stage. Instead, add the code to the OKButton_Change procedure and produce a message explaining why the entered value is not acceptable. This is particularly useful in cases where the code is not appropriate for text box changes (try setting the minimum value to 2, the maximum to 10 or greater in the spin button control panel and then using this macro to enter a quantity of 10).

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) C-1

    Appendix C Initialising controls Comments This appendix is provided for those who wish to align and size all the controls in this

    exercise precisely.

    Left (distance from the left hand side of the user form) Top (distance from the top of the user form) Width (width of the control)

    (Name) Caption Left Top Width

    OrderLabel Order number: 6 6 72

    OrderNo 96 6 72

    ItemBox 6 30 180

    QuantityLabel Quantity : 6 72 42

    Quantity 54 72 36

    UnitCost Unit cost: 0.00 102 72 72

    CancelButton Close 24 102 72

    OKButton OK 108 102 72

    NewOrderForm Add new order 0 0 192

    These control properties can be set by selecting each control in order and working through the properties window to set the desired properties. As already mentioned the mouse and the Format menu commands can be used to set the size and position of controls.

    It is also possible to set properties in the UserForm_Initialize procedure as in the example below. With ItemBox.Left = 6.Top = 30.Width = 180

    End WithNewOrderForm.Height = 144

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) D-1

    Appendix D Keyboard shortcuts Comments Not all computer users use the mouse to select fields when filling in a form or dialog

    box. When producing a form for others to use, it is courteous to provide an alternative method of selecting the controls.

    Tabs The tab order is the order in which the user tabs through controls on the form when using the keyboard.

    To demonstrate the use of tabs within a user form, examine the form created above. Using the user form window, click once to select the first label control (Ordernumber:).

    Press several times and watch the order in which the controls are selected.

    This order is defined by the TabIndex property on each control in the order in which they were added to the form. To rearrange the order, you could select the Tabindex property for each control in turn and assign the new order.

    An easier method is to use the Tab Order window.

    From the View menu, select Tab Order and move the window so that you can see both the user form and this window.

    Rearrange the tab order of the controls by selecting a control and using the Move Up and Move Down buttons as required.

    Accelerators An accelerator assigns a shortcut key to a control on the form.

    Cancel and OK buttons do not require accelerators as the and keys respectively are generally used as keyboard alternatives to selecting these keys by mouse.

    To assign accelerators to other controls, select the control and use the Accelerator property. In many cases, you will choose the first letter of the controls caption. However, where two or more controls share the same initial letter you may need to use a different letter.

    You can also use Visual Basic to set the accelerator property in the UserForm_Initialize procedure. For example, OrderLabel.

  • VB Excel 97/2000: Custom dialog boxes

    VB Excel 2000: Creating custom dialog boxes (exlvba-t2) E-1

    Appendix E Inserting formulae Comments Task 10 used the figures collected in the user form and performed various

    calculations before inputting the result in the worksheet. It would also be possible to insert the formulae directly into the worksheet so that the formula was recalculated each time a figure in a dependant cell was altered.

    Simple calculations The Totals column (column F in the worksheet) would contain the simplest formula (namely =D3*E3 where 3 is the current row). Build this formula up, using the variable Row, by using the following code:

    Cells(Row, 6) = "=D" & Row & "*E" & Row

    In the example above (task 10) this line would replace the line entered in task 10.3, namely:

    Cells(Row, 6) = mCost * Quantity.Text

    Functions To build up a more complex formula for inserting into a worksheet, it may be easier to break the task into smaller chunks, using one or more variables as in the example below using the current value of the Row variable:

    mFormula = "=VLOOKUP(" & "B" & Row & _",Items,4,False)"

    Cells(Row, 3) = mFormula

    In the example above (task 10) this line would replace the line entered in task 10.4, namely:

    acc_code = Application.WorksheetFunction. _VLookup(ItemBox.Text,Range("Items"),4,False)

    Using quotation marks in formulae If you need to pass quotation marks within the function you are constructing, you must use the character string instead. For example,

    ans = "=Vlookup(" & Chr(34) & _ItemBox.Text & Chr(34) & _",Items,4,False) "


Recommended