Visual Basic in Excel

download Visual Basic in Excel

of 14

Transcript of Visual Basic in Excel

  • 8/8/2019 Visual Basic in Excel

    1/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    Macro and Visual Basic in ExcelMacro and Visual Basic in Excel

    One of the best features of Visual Basic is that it is a powerful scriptinglanguage for writing macros and extensions to other programs including

    Excel, AutoCAD, and ArcView. This tool is called Visual Basic for Applications

    (VBA). This document gives a basic introduction on how to use VBA with

    Excel.

    ContentsContents

    1. Getting Started

    a. The Visual Basic Toolbarb. Design Mode vs. Run Modec.The VB Editor

    2. Adding Controls to a Spreadsheet

    3. Working with Cells and Ranges

    a. The Range Objectb. The Cells objectc.Working with Multiple Cellsd. Looping Through Cells

    4. Recording Macros

    5. Trapping for Worksheet Events

    a. Workbooks and Worksheetsb. The Calculate and Change Eventsc.Checking on the Target

    6. Creating Custom Functions

    a. Formatb. Examplesc.Using Functions in VB

    7. Calling Excel Worksheet Functions from VB Code

    8. Custom Graphics

    9. Getting Help

    1. Getting Started

    Writing VBA code for Excel is easy and fun!! Once you learn a fewbasics, you will be creating highly professional spreadsheets. VBAallows you to design a spreadsheet that will do things that areimpossible with the basic spreadsheet options. It also allows you tomake your spreadsheets more user-friendly.

    The Visual Basic Toolbar

    The first step in adding Visual Basic to your spreadsheet is to turn on

    the VB Toolbar. To turn on the toolbar, select the View menu, click on

    the Toolbars command, and turn on the Visual Basic option. The followingtoolbar will appear:

    The options in the toolbar are as follows:

    These buttons are used to run VB macros.

    Thit k Thi nghim va X ly S liu trong Mi trng 1/14

  • 8/8/2019 Visual Basic in Excel

    2/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    These buttons are used to record VB macros.

    This option is used to establish the security settings for the VB code. VBmacros can be used to write computer viruses. The security settingsare used to minimize danger from such viruses.

    This tool displays the Visual Basic Editor. This is where you write the

    Visual Basic code.

    This tool displays the Control Toolbar. This toolbar is used to add VBcontrols such as check boxes, combo boxes, and radio groups to aspreadsheet.

    This tool is used to toggle the spreadsheet in and out ofDesign Mode.

    This option brings up the spreadsheet (both the spreadsheet and anyunderlying VB code in the Microsoft Development Environment. Thiseditor allows you to edit the underlying spreadsheet code in an HTMLformat and develop powerful web applications.

    Design Mode

    When you are writing VB code and adding controls to a spreadsheet, there

    are two basic modes: Design mode and Run mode. In design mode, when youclick on a button or a control, you can edit the properties of the

    control in the VB Editor. If you double click on a control, you can editthe code associated with the control. If you are in Run mode, when youclick on the control, the code associated with the control is executed.When developing your spreadsheet, you will be moving in and out of Designmode.

    The VB Editor

    The VB Editor is where you edit the Visual Basic code. It is very similarto the regular Visual Basic compiler. The code is shown in a set of

    windows on the right. The Project window on the left lists the components

    of the project. The Microsoft Excel Objects folder lists each of the sheets

    in your spreadsheet and the workbook. The Modules folder lists the code

    associated with Macros.

    2. Adding Controls to a Spreadsheet

    To add a control to a spreadsheet, simply select a control in the Control

    Toolbar and create the tool in the spreadsheet, just like you would createa control on a form in the Visual basic editor. Once you create the

    control, right click on it and select the Properties option. This willbring up the Properties window. Once this window is open, it refreshesautomatically each time you select a control. To edit the codeassociated with a control, simply double click on the control.The controls behave similarly to the controls in the regular VB compiler,but there are some differences. For example, when you create a combo boxin the VB compiler, there is a "List" field in the Properties where youcan type in the components of the list. In VBA for Excel, there is no"List" field but there is a "ListFillRange" field. To define the list,you need to enter the list items in some cells somewhere on thespreadsheet. Typically, you use one of the extra sheets in thebackground for this type of information. For example, if I have a sheetcalled "Extra" where I have defined the list items, I would type "Extra!C5:C7" in the ListFillRange field.

    3. Working with Cells and Ranges

    Thit k Thi nghim va X ly S liu trong Mi trng 2/14

  • 8/8/2019 Visual Basic in Excel

    3/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    When writing VB code, you can use variables, for loops, and all other VBtypes and statements. However, most of your code will be dealing withvalues stored in cells and ranges.

    The Range Object

    A range is set of cells. It can be one cell or multiple cells. A rangeis an object within a worksheet object. For example, the following

    statement sets the value of cell C23 to a formula referencing a set ofnamed cells:

    Worksheets("Sheet3").Range("C23").Value = "=5^(1/2)"

    If the " Sheet3" worksheet is the active sheet, the first part can beleft off as follows:

    Range("C23").Value = "=(u/n)*A*Rh^(2/3)*S^(1/2)"

    The ".Value" part is optional. You can also write:

    Range("C23") = "=(u/n)*A*Rh^(2/3)*S^(1/2)"

    You have to remember to put the double quotes around the cell address.If the cell C23 has been named "Q" in the spreadsheet, you can referencethe range as follows:

    Range("Q").Value = "=(u/n)*A*Rh^(2/3)*S^(1/2)"

    To get something from a cell and put it in a variable, you just do thingsin reverse:

    x = Range("B14").Value

    If X is a double or integer, you may also want to use the Val function:

    x = val(Range("B14").Value)

    The Cells Object

    Another way to interact with a cell is to use the Cells(rowindex,

    columnindex) function. For example:

    Cells(2, 5).Value = "=(u/n)*A*Rh^(2/3)*S^(1/2)"

    or

    x = val(Cells(2, 14).Value)

    Once again, the value part is optional since it is the default propertyof both the cell and range object.

    Working with Multiple Cells

    A range can also encompass a set of cells. The following code selects ablock of cells:

    Range("A1:C5").Selector

    Range("A1", "C5").SelectIn some cases, it is useful to reference a range of cells using integersrepresenting the row and column of the cell. This can be accomplishedwith the Cells object. For example:

    Thit k Thi nghim va X ly S liu trong Mi trng 3/14

  • 8/8/2019 Visual Basic in Excel

    4/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    Range(Cells(1,1), Cells(3,5)).SelectThe problem with referring to specific cells in your code is that if youchange the location of data on your spreadsheet, you need to go throughyour code and make sure all of the addresses are updated. In some casesit it useful to define the ranges you are dealing with using globalconstants at the top of your VB code. Then when you reference a range,you can use the constants. If the range ever changes, you only need toupdate your code in one location. For example:

    Const TableRange As String = "A4:D50"Range(TableRange).ClearContents..

    An even better approach is to get into the habit of naming cells andranges on your spreadsheet. Then your VB code can always refer to rangesby names. Then, if you change the location or domain of a named range,you generally don't need to update your VB code. For example:

    .

    .Range("TableRange").ClearContentsRange("NameRange").ClearContentsRange("ScoreRange").ClearContents..

    Looping Through Cells

    One of the most common things we do with VB code is to traverse or loopthrough a set of cells. There are several ways this can be

    accomplished. One way is to use the Cells object. The following codeloops through a table of cells located in the range B4:F20:

    Dim row As IntegerDim col As Integer

    For row = 4 To 20For col = 2 To 6

    If Cells(row, col) = "" ThenCells(row, col).Interior.Color = vbRed

    End IfNext col

    Next rowIn most cases, it doesn't matter what order the cells are traversed, aslong as each cell is visited. In such cases the For Each ... Nextlooping style may be used. The following code does the same thing as the

    nested loop shown above:

    Dim cell As Variant

    For Each cell In Range("B4:F20")If cell = "" Then

    cell.Interior.Color = vbRedEnd If

    Next cell

    Another option is to create your own range objects. A range object isessentially a range type variable. The following code defines threeranges:

    Dim coordrange As RangeDim xrange As Range

    Thit k Thi nghim va X ly S liu trong Mi trng 4/14

  • 8/8/2019 Visual Basic in Excel

    5/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    Dim yrange As Range

    Set xrange = Range(Cells(3, 1), Cells(100, 1))Set yrange = Range(Cells(3, 2), Cells(100, 2))Set coordrange = Range(Cells(3, 1), Cells(100, 2))

    Once a set of range objects has been defined, you can easily manipulate

    the cells in the range object. For example, the following code clearsthe contents of all the cells in the coordrange object:coordrange.Clear

    Once again, these ranges can be traversed using the For Each ... Nextsyntax.

    Dim cell As Variant

    For Each cell In xrangecell.Value = "0.0"

    Next cell

    One of the most useful things you can do with VBA in Excel is to allow

    the user to enter a list of numbers where the size of the list can vary.The following code searches through a list and copies the numbers in thelist into an array. It stops copying the numbers when it reaches a blankcell.

    'Get the x valuesi = 0For Each cell In Range("B4:B23")

    If cell.Value = "" Thennumpts = iExit For

    Elsei = i + 1

    x(i) = Val(cell.Value)End If

    Next cell

    4. Recording Macros

    A VB Macro is essentially a VB subroutine that executes a series of VB

    statements. To generate a macro, click on the Record Macro button inthe VB Toolbar. You will then be prompted for the name of the macro.Then you select a series of menu commands and/or make changes to your

    spreadsheet. When finished, you select the Stop Recording button . To

    view the code associated with the macro, go to the Project window, expandthe Modules folder and double click on the Module1 item.Macros are extremely useful when you are first learning how to write VBAcode in Excel. If you want to do something in code such as change thebackground color of a cell, but you don't know to do it, simply run amacro, change the color manually, and then look at the macro. You canlearn how to do just about anything simply by running macros.

    5. Trapping for Worksheet Events

    When writing VB code associated with a spreadsheet, it is common to add abutton to the spreadsheet that the user pushes to execute the VB codewhen the desired changes have been made to the controls and the valueshave been entered in the cells. For example, the following code performs

    some simple tests to see if someone is ready to take the ResearchQualification test:

    Thit k Thi nghim va X ly S liu trong Mi trng 5/14

  • 8/8/2019 Visual Basic in Excel

    6/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    In this case, we don't need any code for the click events for the optionand checkbox controls. We simply need to add the following code for the"Do I Qualify" button:

    This code works fine, but why require the user to click on the button?Why not set up the spreadsheet so that anytime the user clicks on acontrol or changes the value of a cell, the VB code is automaticallyexecuted and the results are updated? This can be easily accomplishedusing the "Change" event for the worksheet.

    Workbooks and Worksheets

    Before discussing the Change event, we need to first define a couple ofterms. When the VB compiler for Excel is open, you will see a list ofobjects in a tree on the left side of the window. At the bottom of thetree you will see the following objects:

    Thit k Thi nghim va X ly S liu trong Mi trng 6/14

  • 8/8/2019 Visual Basic in Excel

    7/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    A "Workbook" object represents the entire spreadsheet, including all ofthe sheets. If you double click on this object, it will bring up the

    source code related to the workbook as a whole. The other objects("Sheet1", "Sheet2", & "Sheet3"). Double clicking on these objectsbrings up the code related to these objects.Once you open the window related to a particular sheet, some importantinformation related to the sheet is displayed at the top of the sheet asfollows:

    The combo box on the left (the one that is open) lists all of the objectsassociated with the sheet. Note that each of the controls on thespreadsheet are listed along with the worksheet itself. If you highlightone of the objects, you can then select an event from the combo box onthe right:

    Selecting one of these events creates the subroutine for the selectedevent. For example, if I click on the "Change" item, the following code

    appears:

    The Calculate and Change Events

    Note that the list of available events for the worksheet include the"Calculate" event and the "Change" event. By selecting these items, wecan then fill in the code for these events. The resulting code will beexecuted as follows:

    Calculate Event

    The Calculate event looks like this:

    Thit k Thi nghim va X ly S liu trong Mi trng 7/14

  • 8/8/2019 Visual Basic in Excel

    8/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    and is called each time the formulas in the worksheet are recalculated.Note that you must have at least one formula in your spreadsheet in orderfor this event to be called.

    Change EventThe change event looks like this:

    and is called each time any of the cells in the spreadsheet are changed.Note that the subroutine takes one argument which is the range that hasbeen changed. If we want the spreadsheet to be updated any time the userenters new data, this is the event we want to use. First of all, we

    remove the button so that the spreadsheet looks as follows:

    Next, we will modify the code in the Change event to update thespreadsheet. However, this event is not called when a control ischanged, it is only called when a cell is changed. Therefore, we willfirst create a subroutine that performs the calculations:

    Thit k Thi nghim va X ly S liu trong Mi trng 8/14

  • 8/8/2019 Visual Basic in Excel

    9/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    Next, we will modify the Change event so that it calls this subroutine:

    Finally, to ensure that the click events for the controls cause theresults to be updated, we add a call to the click event subroutines foreach of the controls as follows:

    At this point, clicking on any of the controls, or updating the value inthe "years" cell triggers the VB code to update the results.

    Checking on the Target

    Thit k Thi nghim va X ly S liu trong Mi trng 9/14

  • 8/8/2019 Visual Basic in Excel

    10/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    Note that in the code for the Worksheet_Change event, we must do a checkto determine which cells have changed. If we simply call theUpdate_Results subroutine every time the Change event is called, we willget an infinite loop. This is because the Update_Results subroutine endsup changing the cells in the range B13 and B15:B17. This causes a Changeevent, which then calls Update_Results again, which causes another Changeevent, etc. etc. If we only call the Update_Results subroutine if the"years" cell is changed, we can ensure that we don't cause an infiniteloop. Another way to handle this is to check to ensure that the targetcell is not one of the output cells. For example:

    While this approach is fairly simple and it works in most cases, it doeshave two flaws. First of all, this method is cumbersome when either theinput range or the output range contains a large number of cells.

    Second, as a range object, Target may correspond to one cell or multiplecells. If Target contains one cell, the two versions of theWorksheet_Change sub shown above will work fine. However, in some casesthe user may change multiple cells at once. For example, the user mayselect a set of cells and press the Delete key to clear the contents ofthe cells. In this case, Target will contain a multi-cell range andstatements of the form:

    Target = Range("B4")

    Or

    Target Range ("B13")

    will generate an error message. A more efficient and robust approach isto use the Intersect method associated with theApplication object. Thismethod returns the intersection between two ranges. The idea is tointersect the target range and the range corresponding to the input cellsand see if the result is non-empty. This can be accomplished as follows:

    This approach will work with input ranges spanning multiple cells. Forexample:

    Thit k Thi nghim va X ly S liu trong Mi trng 10/14

  • 8/8/2019 Visual Basic in Excel

    11/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    6. Custom Functions

    One of the easiest ways to take advantage of VBA in Excel is to writecustom functions. Excel has a large number of built-in functions thatyou can use in spreadsheet formulas. Examples include:

    =Average("A4:A20")Returns the average value in a range of cells=Sum("A4:A20") Returns the sum of a range of cells=Cos(0.34) Returns the cosine of a number

    In general, a function takes one or more objects (values, ranges, etc.)as input and returns a single object (typically a value). The things

    that are sent to a function as input are called arguments and the thing

    that is returned by a function is often called the return value.In some cases, we may encounter situations where we need a function to dosomething but the function is not provided by Excel. We can easily fixthis problem by creating a custom function in VBA.

    Format

    The basic format for a custom function is as follows:

    [Public] Functionfunction_name(args) AsType...function_name = ......End Function

    The Public statement is optional. This means that the function can becalled by VB code outside the module where the function is declared andfrom Excel formulas in cells. If you omit the Public statement, thefunction is public by default (as opposed to Private).The function_name is the name you provide to the function. This can be

    any name you want, as long as you follow the same rules we use fordefining VB variable names.The args are the arguments to the function. You can have any number ofarguments. The arguments are listed in the same way you declarevariables, except that you omit the Dimpart. The args list serves twopurposes: 1) it defines how many arguments are used, and 2) it definesthe type for each argument. The following are some sample argumentlists:

    (x As Double, n As Double)(r As Range)(str1 As String, str2 As String, num As Integer)

    The Type part defines the type of object returned by the function.Typical examples are Double, Integer, String, and Boolean.Somewhere in the code, you must have line where you set the function nameequal to a value. You should think of the function name as a variable.You must store the value returned by the function in the variable at somepoint before you hit the End Function statement.There is one more important point, whenever you create a function thatyou want to use in an Excel formula, it should always be placed in amodule under theModules folder in the VBE.

    Examples

    Now let's look at some examples. The following function takes twonumbers as arguments and returns the minimum of the two numbers. This

    basically duplicates the Min function provided by Excel, but it serves asa useful example:

    Function my_min(a As Double, b As Double) As Double

    Thit k Thi nghim va X ly S liu trong Mi trng 11/14

  • 8/8/2019 Visual Basic in Excel

    12/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    If a < b Thenmy_min = a

    Elsemy_min = b

    End IfEnd Function

    Once this function is created, you can then use it in one of your Excelformulas as follows:

    =my_min(A5, B7)=my_min(Sum(C3:C10), 0)

    Now let's look at something a little more complicated. In many cases, wewant our function to use a cell range as one of the arguments. Thefollowing function returns the number of negative values in a range:

    Function num_neg(r As Range) As IntegerDim c As Variant

    For Each c In rIf c.Value < 0 Then

    num_neg = num_neg + 1End IfNext cEnd Function

    The function could then be called from an Excel formula as follows:

    =num_neg(A5:B7)

    The next function takes two arguments: a range and an integer n. Itcomputes the sum of values in the range minus the lowest n values. Thisfunction takes advantage of the standard Excel functions Sumand Small.The Small function returns the nth lowest value in a range.

    Function dropsum(r As Range, n As Integer) As DoubleDim i As Integerdropsum = Application.WorksheetFunction.Sum(r)For i = 1 To n

    dropsum = dropsum - Application.WorksheetFunction.Small(r,i)Next iEnd Function

    This function could then be used in an Excel formula as follows:

    =dropsum(A5:B7, C10)=dropsum(A5:B7, 5)

    Functions in VB

    Finally, it should be noted that you can call custom functions from otherplaces in your VB code as well as from Excel formulas. For example, youcould use the my_min function defined above as follows:

    Dim x As DoubleDim y As DoubleDim z As Double

    x = ...y = ......

    Thit k Thi nghim va X ly S liu trong Mi trng 12/14

  • 8/8/2019 Visual Basic in Excel

    13/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    z = my_min(x, y)...

    7. Calling Excel Functions from VB Code

    One of the nice things about writing VB code inside Excel is that you cancombine all of the power and flexibility of Visual Basic with the manytools and options in Excel. One of the best examples of this is that you

    can take advantage of all of the standard Excel worksheet functionsinside your VB code. Calling an Excel worksheet function is simple. The

    Excel functions are available as methods within the WorksheetFunctionobject. You simply invoke the method and pass the arguments that thefunction requires (typically a range).For example, if we were writing a simple formula to put in a cell to findthe maximum value in a range of cells, we would write the following:

    =Min(B4:F30)

    The following code uses the same Min function, but invokes the function

    using VB code. The min value is stored in a variable called minval:

    Dim minval As Doubleminval = Application.WorksheetFunction.Min(Range("B4:F30"))

    Notice the difference in how the range is specified. In the VB code, therange is specified as a range object.The Application. portion is actually optional and can be omitted in mostcases. Thus, the following code achieves the same thing:

    Dim minval As Doubleminval = WorksheetFunction.Min(Range("B4:F30"))

    Here are some more examples:

    Range("e5") = WorksheetFunction.sum(Range("b5:b29"))

    'This is useful since VB does not have an inverse sinfunctionDim x As Doublex = WorksheetFunction.Asin(0.223)

    Dim i As Integeri = 5Range("H4") = WorksheetFunction.Fact(i)

    8. Custom Graphics

    A common task faced by programmers is how to display custom graphicsusing source code. It is often useful to display an object that isproperly dimensioned in terms of the input parameters supplied on theuser. For example, one could display the geometry of a cantilever beamor a column based on the user input. At the other end of the spectrum,it is possible to write sophisticated computer programs with 3D graphicsand animation.

    Thit k Thi nghim va X ly S liu trong Mi trng 13/14

  • 8/8/2019 Visual Basic in Excel

    14/14

    Quan ly quan h s liu mi trngQuan ly quan h s liu mi trng Thc hanh: S dung Macro trongMS ExcelThc hanh: S dung Macro trongMS Excel

    Standard VB (applied to a VB form) has a simple, yet powerful set ofgraphics options. You create a Picture object and then use a series ofcommands to draw lines and simple shapes in the Picture object. However,none of these tools can used for VBA in Excel. With Excel, an entirelydifferent approach must be used. This approach involves a special typeof object called a "Shape". Shapes can be created manually by the user

    of the spreadsheet using the standard MS Office drawing toolbar:

    Any of the graphical objects in this menu (lines, connectors, basicshapes, etc.) are classified as shapes. Once created, they can bemanipulated via VB code. Since the basic shapes include lines,rectangles, circles, and polygons, you can create just about any customdrawing that you can think of.

    9. To Get Help

    To learn more about using VBA in Excel, bring up the Help file and go to

    the Contents section. Open up the Programming Information topic and thenopen up the Microsoft Excel Visual Basic Reference topic.

    1 12

    2 23

    3 23

    4 25

    5 34

    Thit k Thi nghim va X ly S liu trong Mi trng 14/14