Original editado por Roberto Mirelman (

Size: px
Start display at page:

Download "Original editado por Roberto Mirelman (http://www.mirelman.com)"

Transcription

1 Original editado por Roberto Mirelman ( Contenido 1 Excel VBA Tutorial Part 1 - VBA Code Presentation 3 11 Comments 3 12 Code Indentation 4 13 Line Breaks 5 2 Excel VBA Tutorial Part 2 - VBA Variables & Constants 6 21 Data Types 6 22 Declaring Variables & Constants 7 Option Explicit 9 23 Scope of Variables and Constants 9 3 Excel VBA Tutorial Part 3 - Excel Visual Basic Arrays Multi-Dimensional Excel Visual Basic Arrays Declaring Excel Visual Basic Arrays Dynamic Arrays 14 4 Excel VBA Tutorial Part 4 - VBA Functions & Subroutines User-Defined VBA Functions & Subroutines Arguments VBA Functions VBA Subroutines Scope of VBA Functions & Subroutines Early Exit From VBA Functions & Subroutines 22 5 Excel VBA Tutorial Part 5: VBA Conditional Statements The Visual Basic If Then Statement The Visual Basic If Then Statement The Visual Basic Select Case Statement 24 6 Excel VBA Tutorial Part 6 - VBA Loops The Visual Basic For Loop 26 The For Next Loop 26

2 The For Each Loop 27 The Exit For Statement The Visual Basic Do While Loop The Visual Basic Do Until Loop 30 7 Excel VBA Tutorial Part 7 - VBA Operators & Built-In Functions Excel VBA Operators 31 Mathematical Operators 31 String Operators 31 VBA Comparison Operators 32 VBA Logical Operators Built-In Functions 33 8 Excel VBA Tutorial Part 8 - Excel Objects 37 The Active Object 39 Assigning an Object to a Variable Examples 40 Example 1 40 Example 2 40 Example Excel VBA Tutorial Part 9 - Excel Events Example Excel VBA Tutorial Part 10 - VBA Error Types Compile Errors Runtime Errors 46 Trapping Runtime Errors Logical Errors 49

3 Excel VBA Tutorial Part 1 - VBA Code Presentation When learning to produce VBA code, it is important, from the very start, that you adopt good habits in terms of code presentation, so that it is easy to see what the purpose of the code is, and how it works While you may, at the time you are writing the code, have a clear idea of what it does and how it works, you need to consider what the code will look like when you return to it in 6 months' time Worse still, what if someone else needs to work on your code and has to figure out how it works? This page discusses comments, code indentation and line breaks all of which will assist in making your code clearer and easier to interpret Comments The single most important practice for writing clear, decipherable code is to add frequent comments Comments are lines in your code which act as notes to yourself or others, to explain what the code means or what it is doing Comments are not executed during the running of the program, so have no impact on the result your macro VBA considers any line that starts with an apostraphe (') to be a comment and the Excel VBA editor highlights these lines by colouring them in green, so you can see, at a glance, that they are comments and will not be executed See the example below, which shows comments used to clarify the details of a simple subroutine: ' Subroutine to search cells A1-A100 of the current active ' sheet, and find the cell containing the supplied string Sub Find_String(sFindText As String) Dim i As Integer ' Integer used in 'For' loop Dim irownumber As Integer ' Integer to store result in irownumber = 0 ' Loop through cells A1-A100 until 'sfindtext' is found For i = 1 To 100 If Cells(i, 1)Value = sfindtext Then ' A match has been found to the supplied string

4 ' Store the current row number and exit the 'For' Loop irownumber = i Exit For End If Next i ' Pop up a message box to let the user know if the text ' string has been found, and if so, which row it appears on If irownumber = 0 Then MsgBox "String " & sfindtext & " not found" Else MsgBox "String " & sfindtext & " found in cell A" & irownumber End If End Sub Don't worry if you don't understand some of the code in the example above - this will be explained later in this tutorial The example has been included simply to show how comments are used to to explain what each section of the code is for It is easy to get lazy about adding comments to your code, but it really is worth making the effort - the minutes invested in ensuring your code is well commented could save you hours of frustration in the long run! Code Indentation Another way of assisting in making your code readable is by adding indentations to it VBA code is generally indented inside Functions, Subroutines, If blocks or Loops These indented sections enable you to easily see where each block of code starts and ends If you look at the code block above (in the previous 'Comments' section), you will see how the indentations highlight where the 'For' Loop and the 'If' blocks start and begin The Excel VBA editor helps you by automatically inserting indentations into certain parts of code, but you may sometimes need to add further indentations when you are editing your code

5 Line Breaks Your code can also be made more readable and easier to work with by inserting line breaks in the middle of long lines of code In VBA, if you are going to split a line up, you need to add a space followed by an underscore ( _) just before the line break This tells the VBA compiler that the current line of code continues on the following line The following example shows how simple line breaks can be used to make long lines of code much easier to read and understand Consider the following line of code: If (index = 1 And scolor1 = "red") Or (index = 2 And scolor1 = "blue") Or (index = 3 And scolor1 = "green") Or (index = 4 And scolor1 = "brown") Then By adding line breaks the code can be presented as follows: If (index = 1 And scolor1 = "red") Or _ (index = 2 And scolor1 = "blue") Or _ (index = 3 And scolor1 = "green") Or _ (index = 4 And scolor1 = "brown") Then The above presentation enables you to see the different conditions within the 'If' statement much more clearly and will therefore assist you in producing, and maintaining, effective bug-free code

6 Excel VBA Tutorial Part 2 - VBA Variables & Constants In any programming language Variables and Constants are names that represent values As suggested by the names, Variables can change their values, while Constants tend to have fixed values For example, the constant "Pi" is used to refer to the value The value of "Pi" does not change throughout the course of a program, but it is useful to store this value in a Constant for ease of use Also, we might use a variable named "svat_rate", to store the VAT Rate to be paid on purchased goods The value of svat_rate may vary, according to the type of goods being purchased Data Types All variables and constants have a data type Therefore, before working with constants and variables in VBA, it is useful to understand the data types that are available to you The following table shows the VBA data types, along with a description of each type and the range of possible values Data Type Size in Memory Description Range of Values Byte 1 byte Represents an unsigned (non-negative) number - often used for binary data 0 to 255 Boolean 2 bytes A simple True or False value True or False Integer 2 bytes Integer (no decimals) -32,768 to +32,767 Long 4 bytes Long Integer (no decimals) -2,147,483,648 to +2,147,483,647 Single 4 bytes Single Precision Floating Point Number -34e38 to +34e38 Double 8 bytes Double Precision Floating Point Number -18e308 to +18e308 Currency 8 bytes A Floating Point Number with a fixed number of decimal places -922,337,203,685, to +922,337,203,685,

7 Date 8 bytes Date & Time - The Date type is represented internally by a floating point number The integer part of the number represents the date, and the decimal portion represents the time 1st January 100 to 31st December 9999 Object 4 bytes A reference to an object Any Object Reference String varies Holds a series of characters The String type can be defined to have a fixed or a variable length, although it is most commonly define to have a variable length Fixed - Up to 65,500 characters Variable - Up to approx 2 billion characters Variant varies Can hold Dates, Floating Point Numbers or Strings of Characters, and should therefore be used when you are not sure what type of data to expect Number - same as Double Type String - same as String Type From the above table, it is clear that you can save on memory by using specific data types (eg Integers rather than Longs or Singles rather than Doubles) However, if you are planning to use the 'smaller' data types, you must be sure that your code will not encounter larger values than can be handled by the data type Declaring Variables & Constants Before using a variable or constant, you can declare it This is done by adding a simple line of code to your macro, as follows To declare a variable: Dim Variable_Name As Data_Type Note that in the above line of code, Variable_Name should be replaced by your actual variable name and Data_Type should be replaced by one of the previously listed data types For example: Dim svat_rate As Single Dim i As Integer Constants are declared in a similar way, except a constant should always be assigned a value when it is declared Examples of the declaration of constants in VBA are:

8 Const imaxcount = 5000 Const imaxscore = 100 Excel does not force you to declare variables - by default, all variables in Excel will have the Variant type, and can be assigned a number or text Therefore, at any point during your program, you can use any variable name (even if it has not been declared), and Excel will, by default assign the Variant type to it However, this is not good programming practice for the following reasons: 1 Memory & Calculation Speed: If you do not declare a variable to have a data type, it will, by default, have the Variant type This takes up more memory than many of the other data types While a few extra bytes per variable might not seem to be a lot of memory, it is not uncommon for users to have thousands of variables in their programs (especially when you start to use arrays) Therefore, the additional memory used to store Variants instead of Integers or Singles, can add up significantly Variant data types also take more time to process than some of the other data types, so if you have thousands of unnecessary Variant data types, this can slow down your calculations 2 Prevention of 'Typo' Bugs: If you always declare your variables, then you can use a VBA option to force you to declare variables (see Option Explicit discussed below) This will prevent you from introducing bugs into your code by accidentally typing a variable name incorrectly For example, you might be using a variable called "svat_rate" and, when assigning a value to this variable, you might accidentally type "VATRate = 0175" From this point onwards, you are expecting your variable "svat_rate" to have the value 0l75, but of course it doesn't, because this value has been assigned to a different variable (the variable "VATRate") However, if you were using the VBA option to force you to declare all variables before using them, this error would be highlighted by the VBA compiler, as the variable "VATRate" would not have been declared 3 Highlighting Unexpected Data Values: If you declare a variable to have a specific data type, and you attempt to assign the wrong type of data to it, this will generate an error in your program which, if not handled within your code, can cause your macro to crash While this may initially seem to be a good reason not to declare variables, you should think about this more carefully - you actually need to know as soon as possible if your variable receives an unexpected data type Otherwise, if the program continues to run, you could end up with incorrect or unexpected results at a later time, when it is likely to be much more difficult to detect the causes of the errors Also, it is possible that the macro may complete with incorrect results, and you may not notice the error at all - and continue to work with incorrect data! It is therefore preferable to detect the unexpected data type at an early stage and add code to handle this appropriately

9 Therefore, it is recommended that you always declare all variables when programming in VBA Option Explicit The option 'Explicit' forces you to declare all variables that you use in your VBA code, by highlighting any undeclared variables as errors during compilation (before the code will run) To use this option, simply type the line Option Explicit at the very top of your VBA file If you want to always include the option Explicit at the top of every new VBA module that you open up, this will be done automatically via the 'Require Variable Declaration' option of your VBA editor To do this: In the Visual Basic Editor, select Tools Options Ensure the Editor tab is selected Check the box next to the option Require Variable Declaration and click OK Once the 'Require Variable Declaration' option is selected, all new modules will have Option Explicit included at the top Scope of Variables and Constants Each time you declare a variable or a constant, this only has a limited Scope (ie a limited part of the program over which the declaration applies), which depends on the location where you placed your declaration For example, imagine you are using the variable "svat_rate" within the function, "Total_Cost" The following table discusses the scope of "svat_rate" when it is declared in 3 different parts of the module : Option Explicit Dim svat_rate as Single Function Total_Cost() As Double If you declare "svat_rate", at the top of your module file, then the scope of this variable is the whole of the module (ie "svat_rate" will be recognised throughout all procedures within the module) Therefore, if you assign a value to "svat_rate" in the Total_Cost function and then step into another function in the current module, the value of "svat_rate" will be remembered However, if you step into a function that resides in a different

10 End Function module and attempt to use the variable "svat_rate", the variable will not be recognised Option Explicit Function Total_Cost() As Double Dim svat_rate as Single End Function If you declare "svat_rate", at the start of the Total_Cost function, the scope of this variable will be the whole of this function, (ie "svat_rate" will be recognised throughout the Total_Cost function, but not outside of this function) Therefore, if you attempt to use "svat_rate" in any other function or subroutine, the VBA compiler will raise an error, as the variable has not been declared outside of the Total_Cost function (and the Option Explicit is in use) Option Explicit Function Total_Cost() As Double If Total_Cost > 0 Then Dim svat_rate as Single End If End Function If you declare "svat_rate", within an 'If' block, then the scope of this variable will be the interior of the 'If' block (ie up to the 'End If') Therefore, if you attempt to use "svat_rate" after you have exited the 'If' block, the VBA compiler will raise an error, as the variable has not been declared outside of this block (and the Option Explicit is in use) The same scoping rules would apply to variables or constants declared within Loops In the above example, the module level variable has been declared using the 'Dim' keyword However, it is possible that we may wish to declare variables that we want to share with other modules This can be specified by using the keyword Public in the declaration, instead of 'Dim' For a module-level variable, the 'Dim' keyword could also be replaced with the keyword Private to indicate that the scope of the variable is limited to the current module Constants can also use the 'Public' and 'Private' keywords, but in this case, the 'Public' or 'Private' keyword is used in addition to the 'Const' keyword (not instead of) The following examples show the use of the Public and Private keywords to variables and constants : Option Explicit Public svat_rate as Single This example shows the 'Public' keyword used to declare the variable, "svat_rate", and the constant, "imax_count" The scope

11 Public Const imax_count = 5000 of these two declarations is the whole of the current project Therefore "svat_rate" and "imax_count" can be accessed from any procedure in any module in the project Option Explicit Private svat_rate as Single Private Const imax_count = 5000 This example shows the 'Private' keyword used to declare the variable, "svat_rate", and the constant, "imax_count" The scope of these two declarations is the current module Therefore "svat_rate" and "imax_count" can be accessed from any procedure in the current module, but can not be accessed from procedures that reside in different modules

12 Excel VBA Tutorial Part 3 - Excel Visual Basic Arrays Excel Visual Basic arrays are structures which are used to stored several related variables, of the same type Each of the entries in the array can be accessed by an index number For example, if you had 20 members of a team and you wanted to store all the names for use in your VBA code You could declare 20 variables to hold the team member names, as follows: Dim Team_Member1 As String Dim Team_Member2 As String Dim Team_Member3 As String Alternatively, you could use the much simpler and more organised method of storing the Team members in an array of 20 String variables : Dim Team_Members(1 To 20) As String Following the array declaration, each entry of the array is accessed by indexing as follows: Team_Members(1) = "John Smith" A further advantage of storing your data in an array, rather than in individual variables is if you want to perform the same action on member of the list If your team member names are stored in 20 individual variables, you will need 20 lines of code to carry out a specific action on each name However, if you have stored your names in an array, you can use a simple loop to carry out the action for each entry in the array This is shown in the example below, which prints out each name in the Team_Members array to a cell in Column A of Sheet1 of the current Excel Workbook: For i = 1 To 20 Cells(i, 1)Value = Team_Members(i) Next i It is clear from the above that the handling of an array of 20 names is much less cumbersome and more organised than handling 20 individual variables, but imagine if you had 1,000 names to store! And imagine that

13 you wanted to store Surnames separately from Forenames! It is clear that it would soon become impossible to handle this amount of data without the use of Arrays in your VBA code Multi-Dimensional Excel Visual Basic Arrays The Visual Basic Arrays discussed above are one-dimensional, in that they refer to one list of Names of team members However, arrays can have multiple dimensions An array having two dimensions acts as a grid of values For example, imagine that you want to store daily sales figures for the month of January, for 5 different sales teams You would need a 2-dimensional array, consisting of 5 sets of figures over 31 days You would then declare the array as follows: Dim Jan_Sales_Figures(1 To 31, 1 To 5) As Currency In order to access the entries in the array 'Jan_Sales_Figures', you need to use two indices, refering to the day of the month and the team number For example, the sales figures for Team2 on January 15th would be referenced as: Jan_Sales_Figures(15, 2) You can declare arrays with 3 or more dimensions in the same way - ie by adding further dimensions into the declaration and using a further index to reference the array entries Declaring Excel Visual Basic Arrays The above sections have already given some examples of Visual Basic Array declarations, but it is worth discussing this further As seen above, a one-dimensional array can be declared as follows: Dim Team_Members(1 To 20) As String This declaration tells the VBA compiler that the array 'Team_Members' has 20 variables, which are referenced by indices 1 to 20 However, we could also decide to number our array variables from 0 to 19, in which case the declaration would be: Dim Team_Members(0 To 19) As String In fact, the default form of array indexing is to start at 0, so if you omit the start index from the declaration, and simply declare the array as:

14 Dim Team_Members(19) As String Then the VBA compiler will understand this to be an array of 20 variables, which are indexed from 0 to 19 The same rules are applied to declarations of multi-dimensional Visual Basic arrays As shown in the previouse example, a two-dimensional array is declared by separating the dimension indices by a comma: Dim Jan_Sales_Figures(1 To 31, 1 To 5) As Currency However, if we omit the start indices from both dimensions, as follows: Dim Jan_Sales_Figures(31, 5) As Currency this is understood to be a two-dimensional array in which the first dimension has 32 entries, indexed from 0 to 31 and the second dimension has 6 entries, indexed from 0 to 5 Dynamic Arrays In the above examples, the arrays all have fixed dimensions However, in many cases, we don't know how big an array is going to be before runtime We could solve this be declaring a huge array, in an attempt to cover the maximum possible size needed, but this would use up an unnecessarily large amount of memory and could slow down your program A better option would be to use a Dynamic array, which is an array that can be sized and re-sized as many times as you like, during the execution of a macro A dynamic array is declared with empty parentheses, as follows: Dim Team_Members() As String You then need to declare the dimension of the array during the execution of the code, using the ReDim statement: ReDim Team_Members(1 To 20) If, during the execution of the code, you need to extend the size of your array, you can use ReDim again: If Team_Size > 20 Then ReDim Team_Members(1 To Team_Size) End If

15 It should be noted that resizing a dynamic array in this way will result in the loss of all the values that had previously been stored in the array If you want to avoid this loss, and keep the values that had previously been assigned to the array, you need to use the "Preserve" keyword, as shown below: If Team_Size > 20 Then ReDim Preserve Team_Members(1 To Team_Size) End If The disadvantage of using the "Preserve" keyword when resizing Visual Basic Arrays is that you can only change the upper bound of an array, not the lower bound Also, if you have a multi-dimensional array, the use of the "Preserve" keyword limits you to changing only the last dimension of the array

16 Excel VBA Tutorial Part 4 - VBA Functions & Subroutines Built-In VBA Functions Although this page focuses on user-defined VBA functions and subroutines, you should be aware that Excel VBA already has a large number of built-in functions that you can use in your macros To view a list of these: From an Excel Workbook, open up the VBA Editor (by pressing ALT-F11), and then press F2 Select VBA in the drop-down list at the top left of the screen The list that appears shows the VBA built in classes, members and functions If you click on a function name a brief description appears at the bottom of the window; Pressing F1 brings up the online help for that function Alternatively, a list of built-in VBA functions, with examples, can be found at the Visual Basic Developer Center website or the Tech on the Net website User-Defined VBA Functions & Subroutines In Excel Visual Basic, a set of commands to perform a specific task is placed into a procedure, which can be a function or a subroutine The main difference between a VBA function and a VBA subroutine is that a function returns a result, whereas a subroutine does not Therefore, if you wish to perform a task that returns a result (eg summing of a group of numbers), you will generally use a function, but if you just need a set of actions to be carried out (eg formatting a set of cells), you might choose to use a subroutine Arguments In VBA, both functions and subroutines can be passed data via arguments, which are declared in the VBA function or subroutine definition For example, we might have a VBA subroutine that adds an Integer to every cell in the current range You could supply the value of the integer to the subroutine via an argument, as follows: Sub AddToCells(i As Integer) End Sub

17 Optional Arguments You can also define VBA functions or subroutines to have Optional arguments These are arguments that the user can supply if they want, but if they are omitted, the procedure will still work To return to the example above, if we wanted to make the supplied integer optional, this would be declared as follows: Sub AddToCells(Optional i As Integer) Of course this needs to be considered in the subroutine code We need to tell the subroutine to check if the argument i has been supplied, before attempting to use it You can check if an argument has been supplied to a procedure, using the IsMissing command, as follows: Sub AddToCells(Optional i As Integer) If IsMissing(i) Then Else End If End Sub VBA allows you to use multiple Optional arguments in a procedure, as long as the Optional arguments are positioned at the end of the argument list Passing Arguments By Value and By Reference When arguments are passed to VBA functions, they can be passed in two ways: ByVal - The argument is passed by Value This means that just the value (ie a copy of the argument) is passed to the procedure and therefore, any changes that are made to the argument inside the procedure will be lost when the procedure is exited ByRef - The argument is passed by Reference This means that the actual address of the argument is passed to the procedure Any changes that are made to the argument inside the procedure will be remembered when the procedure is exited

18 We can specify whether an argument is passed to a VBA function by value or by reference by using the ByVal or the ByRef keyword when defining the procedure This is shown below: Sub AddToCells(ByVal i As Integer) End Sub In this case, the integer i is passed by Value Any changes that are made to i will be lost when we exit the subroutine Sub AddToCells(ByRef i As Integer) End Sub In this case, the integer i is passed by Reference When we exit the subroutine, any changes that have been made to i will be remembered by the variable that was passed into the subroutine It should be noted that, by default, in VBA, arguments are passed by Reference, so if you do not use the ByVal or the ByRef keyword, the arguments will be passed by Reference Before discussing further properties of VBA Functions and Subroutines, it is useful to look at the two types of procedure individually The following two sections provide a brief discussion of VBA Functions and VBA Subroutines, along with simple examples : VBA Functions The VBA editor recognises a function, because the commands are positioned between the following start and end commands: Function End Function As previously mentioned, VBA functions (unlike subroutines) return a value The return values have the following rules: The data type of the returned value must be declared in the function header

19 The value to be returned must be assigned to a variable having the same name of the function This variable does not need to be declared, as it already exists as a part of the function The value returned from the function is the last value to be assigned to this variable before the function is exited This is best illustrated by the example below VBA Function Example: Perform Mathematical Operations on 3 Numbers The following code shows an example of a simple VBA function that receives three arguments, each of which are 'Doubles' (double precision floating point numbers) The function returns a further 'Double', which is the sum of the first two arguments, minus the third argument : Function SumMinus(dNum1 As Double, dnum2 As Double, dnum3 As Double) As Double SumMinus = dnum1 + dnum2 - dnum3 End Function The above very simple VBA function illustrates the way in which data arguments are supplied to a function, and the way the return type is defined as being a 'Double' (ie by the term "As Double" which is included after the function arguments) The above example also shows how the function result is stored in a variable that has the same name as the function Calling VBA Functions If the above simple function is typed into a Module in the Visual Basic Editor, it will then be available to be used in the worksheets of your Excel workbook, in the same way as Excel's Built-In Functions Therefore if cells A1, A2 and A3 contain numeric values, you could call the SumMinus function by typing the following into any cell: =SumMinus(A1, A2, A3) VBA Subroutines The VBA editor recognises a Subroutine, because the commands are positioned between the following start and end commands:

20 Sub End Sub VBA Subroutine Example 1: Center and Apply Font Size to a Selected Range of Cells The following code shows an example of a simple VBA subroutine that applies formatting to the current selected cell range The cells are formatted to be aligned centrally (both horizontally and vertically) and to have a user-supplied font size : Sub Format_Centered_And_Sized(Optional ifontsize As Integer) SelectionHorizontalAlignment = xlcenter SelectionVerticalAlignment = xlcenter If Not IsMissing(iFontSize) Then SelectionFontSize = ifontsize End Sub The above example illustrates how subroutines perform actions but do not return values This example also includes the Optional argument, ifontsize If ifontsize is not supplied to the subroutine, then the current range's font size is not changed However, if ifontsize is supplied to the function, then the current range is set to have the supplied font size VBA Subroutine Example 2: Center and Apply Bold Font to a Selected Range of Cells The following code is similar to example 1, but instead of supplying a font size to the selected range, the cells are set to have a bold font This example has been included to show a subroutine that does not receive any arguments : Sub Format_Centered_And_Sized() SelectionHorizontalAlignment = xlcenter SelectionVerticalAlignment = xlcenter SelectionFontBold = True End Sub

21 Calling Excel VBA Subroutines Subroutines cannot be typed directly into a cell in Excel, in the same way that VBA functions can, because subroutines don't return a value However, provided they have no arguments (and are Public - see below), Excel VBA subroutines are available to the user of a spreadsheet Therefore, if the above simple subroutines are typed into a Module in the Visual Basic Editor, Example 2 will then be available to be used in the worksheets of your Excel workbook but Example 1 will not (as it has an argument) For those subroutines that are accessible from the workbook, a simple way to run (or execute) the subroutine is : Press ALT-F8 (ie press the ALT key and while this is pressed down, press F8) From the list of macros that appear, select the macro you wish to run Click Run Alternatively, you can assign a key combination to your subroutine, to enable quick and easy execution of the code To do this: Press ALT-F8 (ie press the ALT key and while this is pressed down, press F8) From the list of macros that appear, select the macro you wish to assign a key combination to Click Options, and in the box that appears, type in a key combination Click OK and then shut down the macro window WARNING: When assigning a key combination to a macro, take care not to select one of Excel's predefined key combinations (eg CTRL-C) If you do select an existing Excel key combination, this will be overwritten by your macro, and you, or other users, may end up accidentally executing your macro code! Scope of VBA Functions & Subroutines In Part 2 of this tutorial, we discussed the scope of variables and constants and the role of the Public and Private keywords These keywords have the same meaning when applied to VBA Functions and Subroutines : Public Sub AddToCells(i As Integer) End Sub If a function or subroutine declaration is preceded by the keyword Public, this makes the procedure accessible to all other modules in the VBA Project

22 Private Sub AddToCells(i As Integer) End Sub If a function or subroutine declaration is preceded by the keyword Private, this makes the procedure only available to the current module It cannot be accessed from any other modules, or from the Excel workbook It should be noted that if no keyword is inserted at the start of a VBA function or subroutine declaration, then the default is for the procedure to be Public (ie to be accessible from anywhere in the VBA Project (This is different to variable declarations, which are Private by default) Early Exit From VBA Functions & Subroutines If you want to exit a VBA function or subroutine before its natural end point, you can do this using the Exit Function or the Exit Sub command This is illustrated below, in a simple function that expects to receive a positive value to work with If the value received is not positive, the function cannot continue, so it highlights the error to the user and exits the function immediately: Function VAT_Amount(sVAT_Rate As Single) As Single If svat_rate <= 0 Then MsgBox "Expected a Positive value of svat_rate but Received " & svat_rate Exit Function End If End Function

23 Excel VBA Tutorial Part 5: VBA Conditional Statements The main Excel VBA Conditional Statements are the If Then statement and the Select Case statement Both of these evaluate one or more conditions and, depending on the result, execute specific actions The two Conditional Statement types are discussed individually below 11 The Visual Basic If Then Statement The If Then statement tests a condition and if it evaluates to true, carries out a set of actions Alternative actions can be specified if the condition evaluates to false The format of the If Then statement is: The main Excel VBA Conditional Statements are the If Then statement and the Select Case statement Both of these evaluate one or more conditions and, depending on the result, execute specific actions The two Conditional Statement types are discussed individually below The Visual Basic If Then Statement The If Then statement tests a condition and if it evaluates to true, carries out a set of actions Alternative actions can be specified if the condition evaluates to false The format of the If Then statement is: If Condition1 Then Actions if Condition1 evaluates to True ElseIf Condition2 Then Actions if Condition2 evaluates to True Else Actions if none of the previous conditions evaluate to True End If In the above if statement, the ElseIf and the Else parts of the conditional statement can be left out if desired

24 The example below shows the If Then statement being used to color the current active cell, depending on the value of the cell contents If ActiveCellValue < 5 Then ActiveCellInteriorColor = ' Color cell interior green ElseIf ActiveCellValue < 10 Then ActiveCellInteriorColor = ' Color cell interior orange Else ActiveCellInteriorColor = 255 ' Color cell interior red End If The Visual Basic Select Case Statement The Select Case statement is similar to the If Then statement, in that it tests an expression, and carries out different actions, depending on the value of the expression The format of the Select Case statement is: Select Case Expression Case Value1 Actions if Expression matches Value1 Case Value2 or Expresson2 Actions if Expression matches Value2 Case Else Actions if expression does not match any of listed cases End Select In the above code block, the Case Else part of the conditional statement is optional The example below shows the Select Case statement being used to color the current active cell, depending on the value of the cell contents

25 Select Case ActiveCellValue Case Is <= 5 ActiveCellInteriorColor = ' Color cell interior green Case 6, 7, 8, 9 ActiveCellInteriorColor = ' Color cell interior orange Case 10 ActiveCellInteriorColor = ' Color cell interior yellow Case Else ActiveCellInteriorColor = 255 ' Color cell interior red End Select The above example illustrates different ways of defining the different Cases in the Select Case statement These are: Case Is <= 5 This is an example of how you can test if your expression satisfies a condition such as <= 5 by using the keyword Case Is Case 6, 7, 8, 9 This is an example of how you can test if your expression evaluates to any one of several values, by separating the possible values by commas Case 10 This is an example of the basic test of whether your expression evaluates to a specific value Case Else This is an example of the 'Else' condition, which is executed if your expression hasn't matched any of the previous cases Note that as soon as one case in the Select Case statement is matched, and the corresponding actions executed, the whole Select Case statement is exited Therefore, you will never get entry into more than one of the listed cases

26 Excel VBA Tutorial Part 6 - VBA Loops If you need to perform the same task several times (perhaps for several elements of an array), this can be done using by repeating the same block of code several times, using one of the VBA Loops These Loops are: The For Loop The Do While Loop The Do Until Loop Each of the above loop types are discussed separately in the following sections The Visual Basic For Loop The Visual Basic For loop takes on two separate forms These are the For Next loop and the For Each loop The For Next Loop The For Next loop sets a variable to a specified set of values, and for each value, runs the VBA code inside the loop This is best explained by way of a simple example: For i = 1 To 10 Total = Total + iarray(i) Next i The above simple For Next loop sets the variable i to have the values 1, 2, 3,, 10, and for each of these values, runs through the VBA code inside the loop Therefore, in the above example, the loop adds each of the entries of the array 'iarray' to the variable, 'Total' In the above example, no step size is specified, so the loop uses the default step size of 1, when looping from 1 to 10 However, you may sometimes want to step through a loop using different sized steps This can be done using the Step keyword, as shown in the following simple example

27 For d = 0 To 10 Step 01 dtotal = dtotal + d Next d In the above For loop, because the step size is specified as 01, the value of d is set to the values 00, 01, 02, 03,, 99, 100 for each run through the VBA code inside the loop Although the previous examples all show increasing steps, you can also use negative step sizes, as is illustrated below: For i = 10 To 1 Step -1 iarray(i) = i Next i In this example, the step size is specified as -1, and so the loop sets the variable, i, to have the values, 10, 9, 8,, 1 in turn The For Each Loop The For Each loop is similar to the For Next loop but, instead of running through a set of values for a variable, the For Each loop runs through every object within a set of objects For example, the following code shows the For Each loop used to list every Worksheet in the current Excel Workbook: Dim wsheet As Worksheet For Each wsheet in Worksheets MsgBox "Found Worksheet: " & wsheetname Next wsheet The Exit For Statement If, you want to exit a 'For' Loop early, you can use the Exit For statement This statement causes VBA to jump out of the loop and continue with the next line of code outside of the loop For example, you may be searching for a particular value in an array You might loop through each entry of the array, but when you find the value you are looking for, you no longer wish to continue searching, so you might exit the loop before you get to the end of it

28 The Exit For statement is illustrated in the following example, which loops through 100 array entries, comparing each to the value 'dval' The loop is exited early if dval is found in the array : For i = 1 To 100 If dvalues(i) = dval Then IndexVal = i Exit For End If Next i The Visual Basic Do While Loop The Do While loop repeatedly executes a section of code while a specified condition continues to evaluate to True This is shown in the following subroutine, where a Do While loop is used to print out all values of the Fibonacci Sequence until the values exceed 1,000 : ' Subroutine to list the Fibonacci series for all values below 1,000 Sub Fibonacci() Dim i As Integer ' counter for the position in the series Dim ifib As Integer ' stores the current value in the series Dim ifib_next As Integer ' stores the next value in the series Dim istep As Integer ' stores the next step size ' Initialise the variables i and ifib_next i = 1 ifib_next = 0 ' Do While loop to be executed as long as the value ' of the current Fibonacci number exceeds 1000 Do While ifib_next < 1000 If i = 1 Then ' Special case for the first entry of the series istep = 1 ifib = 0 Else ' Store the next step size, before overwriting the

29 ' current entry of the series istep = ifib ifib = ifib_next End If ' Print the current Fibonacci value to column A of the ' current Worksheet Cells(i, 1)Value = ifib ' Calculate the next value in the series and increment ' the position marker by 1 ifib_next = ifib + istep i = i + 1 Loop End Sub It can be seen that, in the above example, the condition ifib_next < 1000 is executed at the start of the loop Therefore, if the first value of ifib_next were greater than 1,000, the loop would not be executed at all Another way that you can implement the Do While loop is to place the condition at the end of the loop instead of at the beginning This causes the loop to be executed at least once, regardless of whether or not the condition initially evaluates to True This makes no difference to the above Fibonacci Sequence loop, as the variable ifib_next has been initialised to 0 and so the 'While' condition is always satisfied the first time it is tested However, if the variable ifib_next had previously been used for other calculations and was set to a value greater than zero, the initial 'While' condition would be False, and the loop would not be entered One way to solve this would be to place the condition at the end of the loop, as follows: Do Loop While ifib_next < 1000

30 The Visual Basic Do Until Loop The Do Until loop is very similar to the Do While loop The loop repeatedly executes a section of code until a specified condition evaluates to True This is shown in the following subroutine, where a Do Until loop is used to extract the values from all cells in Column A of a Worksheet, until it encounters an empty cell : Do Until IsEmpty(Cells(iRow, 1)) ' Store the current cell value in the dcellvalues array dcellvalues(irow) = Cells(iRow, 1)Value irow = irow + 1 Loop In the above example, since the condition IsEmpty(Cells(iRow, 1)) is at the start of the Do Until loop, the loop will only be entered if the first cell encountered is non-blank However, as illustrated in the Do While loop, you may on some occasions want to enter the loop at least once, regardless of the initial condition In this case, the condition can be placed at the end of the loop, as follows: Do Loop Until IsEmpty(Cells(iRow, 1))

31 Excel VBA Tutorial Part 7 - VBA Operators & Built-In Functions Excel VBA Operators There are a number of built-in VBA operators that can be used in Excel VBA code These are mathematical operators, string operators, comparison operators and logical operators These are discussed individually below Mathematical Operators The main Mathematical VBA operators are listed in the table below Note that, the precedences that are listed alongside the operators are the defaults, which are applied in the absence of brackets However, the order in which the VBA operators are applied can be controlled by adding brackets to an expression: Operator Action Precedence (1=top; 5=bottom) ^ The power operator 1 * The multiplication operator 2 / The division operator 2 \ The integer division operator - this operator divides two numbers and returns the integer result (eg 7\4 gives a result of 1) 3 Mod The modulus operator - this operator divides two numbers and returns the remainder (eg 8 Mod 3 gives a result of 2) 4 + The addition operator 5 - The subtraction operator 5 String Operators The main string operator in Excel VBA is the concatenate operator, &:

32 Operator Action & The concatenate operator (eg "A" & "B" gives the result "AB") VBA Comparison Operators Comparison operators compare two numbers or strings and return a logical (True or False) result The main Excel VBA comparison operators are listed in the table below: Operator Action = Equal To <> Not Equal To < Less Than > Greater Than <= Less Than or Equal To >= Greater Than or Equal To VBA Logical Operators Comparison operators also return a logical (True or False) result The main Excel VBA logical operators are listed in the table below: Operator Action And Logical Operator And (eg the expression 'A And B' returns True if BOTH A AND B are true and returns False otherwise) Or Logical Operator Or (eg the expression 'A Or B' returns True if EITHER A OR B is true and returns False otherwise) Not Negates an evaluation (eg the expression 'Not A' returns True if A is false and returns False if A is true)

33 It should be noted that the above tables are not an exhaustive list of VBA operators A more complete list can be obtained from the Visual Basic Developer Center Website Built-In Functions VBA also has a large number of built-in functions that are available to be used in your VBA code Some of the more commonly used VBA functions are listed below Function Action Abs If supplied with a numeric value, the Abs function returns the absolute numeric value, with a positive sign eg Abs(-20) returns the value 20 Abs(20) returns the value 20 Chr If supplied with a numeric value, the Chr function returns ansi character associated with that value eg Chr(10) returns a line break Chr(97) returns the character "a" Date Returns the current system date DateAdd Adds a specified time period to a date The function has the format DateAdd(Interval, Number, Date), where the Interval argument specifies the type of time interval to be added to the supplied date This can takes on one of the following values: Interval yyyy q m Represents year quarter month

34 y d w ww h n s day of the year day weekday week hour minute second eg DateAdd("d", 32, "01/01/2009") adds 32 days to the date "01/01/2009" and so returns the date "02/02/2009" DateAdd("ww", 8, "01/01/2009") adds 88 weeks to the date "01/01/2009" and so returns the date "09/09/2010" DateDiff Calculates the number of specified intervals between now and a supplied date eg DateDiff("d", "01/01/2009", "02/02/2009") calculates the number of days between the dates "01/01/2009" and "02/02/2009", and so returns the value 32 DateDiff("d", "01/01/2009", "09/09/2010") calculates the number of weeks between the dates "01/01/2009" and "09/09/2010", and so returns the value 88 Day Returns the day of the month for a supplied date eg Day("01/29/2009") returns the value 29 InStr If supplied with an integer, n, and 2 strings, the InStr function returns the position of the second string within the first string, starting the search from the n'th position in the first string eg InStr(1, "Here is the searchword", "searchword") returns the value 13 InStr(14, "Here is the searchword but here is another searchword", "searchword") returns the value 44

35 Int If supplied with a numeric value, the Int function returns the integer part of the value eg Int(579) returns the value 5 Isdate If supplied with a value, the IsDate function returns True if the value is a date, and False otherwise eg IsDate("01/01/2009") returns the value True IsDate(100) returns the value False IsError If supplied with a value, the IsError function returns True if the value is an error, and False otherwise IsMissing If supplied with the name of an optional argument to a function, the IsMissing function returns True if no argument value was passed to the function IsNumeric If supplied with a value, the IsNumeric function returns True if the value can be evaluated as a number Left Returns a specified number of characters from the start of a supplied string The format of the function is Left(String, Length), where String is the original text string and Length is the number of characters to be returned from the start of the supplied String eg Left("abcdefghijklm", 4) returns the string "abcd" Left("abcdefghijklm", 1) returns the string "a" Len If supplied with a text string, the Len function returns the length of the string eg Len("abcdefg") returns the value 7 Month Returns the month number for a supplied date eg Month("01/29/2009") returns the value 1 Mid Returns a specified number of characters from the middle of a supplied string The format of the function is Mid(String, Start, Length),

36 where String is the original text string, Start is the start position of the section of String that is to be returned and Length is the length of the returned string eg Mid("abcdefghijklm", 4, 5) returns the string "defgh" Mid("abcdefghijklm", 10, 2) returns the string "jk" Now Returns the current system date and time Right Returns a specified number of characters from the end of a supplied string The format of the function is Right(String, Length), where String is the original text string and Length is the number of characters to be returned from the end of the supplied String eg Right("abcdefghijklm", 4) returns the string "jklm" Right("abcdefghijklm", 1) returns the string "m" Sqr If supplied with numeric value, the Sqr function returns the square root of that value eg Sqr(4) returns the value 2 Sqr(16) returns the value 4 Time Returns the current system time Ubound If supplied with an array, the UBound function returns the upper subscript of the array Year Returns the year of a supplied date eg Year("01/29/2009") returns the value 2009 Note that the above list only provides a selection of the more commonly used Excel Visual Basic built-in functions If you want a more comprehensive list of the VBA functions available for use in your Excel Macros, this can be found on the Visual Basic Developer Center website or the Tech on the Net website

37 Excel VBA Tutorial Part 8 - Excel Objects The term Excel Objects (collectively referred to as the Excel Object Model) refers to the entities that make up an Excel workbook, such as Worksheets, Rows, Columns, Cell Ranges, and the Excel Workbook itself Each object in Excel has a number of Properties, which are stored as a part of that object For example, an Excel Worksheet object's properties would include the Worksheet's Name, Protection, Visible Property, Scroll Area, etc Therefore, if during the execution of a macro, we needed to hide an Excel worksheet, we would need to access the Worksheet object, and alter the 'Visible' property Excel VBA also has a special type of object, which is known as a Collection As the name suggests, a Collection refers to a group (or collection) of Excel objects For example, the Rows collection is an object containing all the rows of a Worksheet The main Excel Objects can all be accessed (directly or indirectly) from the Workbooks object, which is a collection of all the currently open Workbooks Each Workbook object contains the Sheets object (consisting of all the Worksheets and Chart sheets in the Workbook), and in turn, each Worksheet object contains a Rows object (consisting of all Rows in the Worksheet) and a Columns object (consisting of all Columns in the Worksheet), etc The following chart shows the structure of some of the more commonly used Excel objects In the chart, the objects are positioned below the other objects that they are accessed from It is stressed that the list below is just a selection of the Excel objects and is, by no means, a complete list of Excel objects The Excel Objects in the above chart are discussed in turn below

38 Object Type Description Workbooks The Workbooks object is a collection of all of the open Excel Workbooks in the current Excel Application An individual Workbook can be extracted from the Workbooks object by using an individual Workbook index number or name (ie Workbooks(1) or Workbooks("Book1")) Workbook The Workbook is a member of the Workbooks Collection As previously mentioned, a Workbook object can be accessed from the Workbooks Collection by using a Workbook index number or a Workbook name (ie Workbooks(1) or Workbooks("Book1")) You can also use 'ActiveWorkbook' to access the current active Workbook From the Workbook object, you can access the Sheets object, which is a collection of all the Sheets (Worksheets and Chart Sheets) in the Workbook, and also the Worksheets object, which is a collection of all the Worksheets in the Workbook Sheets The Sheets object is a collection of all the Sheets in a Workbook These Sheets can be Worksheets or Charts An individual Sheet can be extracted from the Sheets object by using an individual Sheet index number or name (ie Sheets(1) or Sheets("Sheet1")) Worksheets The WorkSheets object is a collection of all the WorkSheets in a Workbook (ie all the Sheets, except the Charts) An individual Worksheet can be extracted from the Worksheets object by using an individual Worksheet index number or name (ie Worksheets(1) or Worksheets("Wksheet1")) Worksheet The Worksheet object is a member of the Worksheets collection, and also a member of the Sheets collection As previously mentioned, a Worksheet object can be accessed from the Sheets or the Worksheets object by using a Sheet or Worksheet index number or a Sheet or Worksheet name (ie Sheets(1), Worksheets(1), Sheets("Sheet1") or Worksheets("Wksheet1")) You can also use 'ActiveWorksheet' to access the current active Worksheet From the Worksheet object, you can access the Rows and Columns objects, which are collections of Range objects relating to the Rows and Columns of the Worksheet You can also access an individual cell or any Range of contiguous cells on the Worksheet Rows The Rows object is a collection of all the Rows of a Worksheet A Range object consisting of an individual Worksheet row can be accessed by using an index number (ie Rows(1))

39 Columns The Columns object is a collection of all the Columns of a Worksheet A Range object consisting of an individual Worksheet column can be accessed by using an index number (ie Columns(1)) Range The Range object represents any number from of contiguous cells on a Worksheet This can be just one cell or it can be all the cells on the Worksheet A range consisting of just one cell can be returned from the Worksheet, using the Cells property (ie WorksheetCells(1,1)) Alternatively, a range can be referenced by specifying either a cell range or a start and end cell (ie WorksheetRange("A1:B10") OR WorksheetRange("A1", "B10") OR WorksheetRange(Cells(1,1), Cells(10,2))) Note that if the second cell reference is omitted from the Range (ie WorksheetRange("A1") OR WorksheetRange(Cells(1,1)), this will return a range that consists of only one cell The above table describes how you access Excel objects via 'parent' objects For example, a range of cells may be referenced by the expression: Workbooks("WB1")Worksheets("WS1")Range("A1:B10") However, if "WB1" is the current active Workbook, you don't need to include the reference to this This is because, when no Workbook is specified, a reference to Worksheets automatically accesses the current active Workbook Therefore, the following will return the required Range: Worksheets("WS1")Range("A1:B10") Similarly, if "WS1" is the current active Worksheet, you don't need to include the reference to this This is because, when no Worksheet is specified, a call to Range automatically accesses the current active Worksheet Therefore, the following simple statement will still return the required Range: Range("A1:B10") The Active Object We have previously mentioned that, the current Active Workbook or Worksheet is selected by default if no Workbook or Worksheet is specified Also, the current active Workbook, Worksheet or Sheet can be referred to, in your vba code as ActiveWorkbook, ActiveSheet or ActiveWorksheet, and the current selected range can be accessed by referring to Selection When a macro starts running, the current active Workbook and Worksheet are those that you call the macro from, and the current selected Range is that (if any) which have been selected just before the macro was run

40 However, if, during the running of a macro, you want to change the current selected Worksheet, Range, etc, this can be done by using the 'Select' command, as shown in the examples below: Worksheets("Data")Select Range("A1", "B10")Select Assigning an Object to a Variable Another point to note, when working with Excel objects is that, when an object is being assigned to a variable in your vba code, you must use the Set keyword as follows: Dim DataWb As Workbook Set DataWb = WorkbooksOpen("C:\Dataxls", False, True) Examples Example 1 The following VBA code snippet was previously used to illustrate the use of the For Each loop It is now useful to re-visit this code to examine the references to the Worksheets object (taken from the current active Workbook by default), and the reference to each individual Worksheet Note that the Worksheet Name property is accessed, to display the name of each Worksheet ' Cycle through each Worksheet in the current Workbook ' and display the Worksheet name in a message box Dim wsheet As Worksheet For Each wsheet in Worksheets MsgBox "Found Worksheet: " & wsheetname Next wsheet Example 2 The following section of VBA code has been included to illustrate how you might access Worksheets and Ranges from other Workbooks and how the current Excel Objects are accessed by default if no specific object is referenced This example also illustrates the use of the Set keyword to assign an Excel object to a variable ' Copy a range of cells from Sheet1 of another Workbook (named "Dataxlsx"), ' and paste the values into the "Results" Worksheet of the current Workbook ' (named "CurrWbxlxm") Dim datawb As Workbook Set DataWb = WorkbooksOpen("C:\Data")

41 ' Note that DataWb is the current Active Workbook ' Therefore the following accesses the 'Sheets' Object in DataWb Sheets("Sheet1")Range("A1:B10")Copy ' Paste the values from the copied Range into the "Results" Worksheet of ' the current Workbook Note that, as CurrWb is not the current Active ' Workbook, we need to specify this Workbook Workbooks("CurrWb")Sheets("Results")Range("A1")PasteSpecial Paste:=xlPasteValues Example 3 The following section of VBA code provides an example of the Columns object and the way in which this is accessed from the Worksheet object It is also seen how, when accessing a cell or cell range on the current active Worksheet, we can omit the reference to the Worksheet Again the code provides an illustration of the use of the Set keyword to assign a Range object to the variable 'Col' ' Loop through the values in Column A of the Worksheet "Sheet2", ' perform arithmetic operations on each value, and write the result into ' Column A of the current Active Worksheet ("Sheet1") Dim i As Integer Dim Col As Range Dim dval As Double ' Set the variable 'Col' to be Column A of Sheet 2 Set Col = Sheets("Sheet2")Columns("A") i = 1 ' Loop through each cell of the column 'Col' until ' a blank cell is encountered Do Until IsEmpty(ColCells(i)) ' Apply arithmetic operations to the value of the current cell dval = ColCells(i)Value * 3-1 ' The command below copies the result into Column A ' of the current Active Worksheet - no need to specify ' the Worksheet name as it is the active Worksheet Cells(i, 1) = dval i = i + 1

42 Loop

43 Excel VBA Tutorial Part 9 - Excel Events The term 'Excel Events' refers to specific user actions within Excel For example, if the user selects a Worksheet, enters data into a cell, or saves a Workbook, these actions are all Excel events Events are linked to Excel Worksheets, Charts, Workbooks, or to the Excel Application itself Their purpose is to enable the programmer to create vba code to be executed automatically at the time of an event For example, if you wanted to run a macro every time a user selected any Worksheet in the Workbook, this could be done by writing vba code that is linked to the Workbook event "SheetActivate" Alternatively, if you wanted to run a macro every time a specific Worksheet (eg "Sheet1") was selected, you would link your code to the Worksheet event "Activate" for Sheet1 The vba code linked to Excel events should be housed in the individual Sheet or Workbook objects in the VBA Editor (accessed by pressing ALT-F11) This is shown in the image below: You can view the set of Excel Events that are available for the Workbook, Worksheets or Charts in the Excel VBA Editor Just open up the code window for the object and, in the left drop-down menu, at the top of the window, select the object type The dropdown menu in the right window will then display the events that are defined for that object This is shown below, for the Excel Worksheet:

44 If you click on an event in the drop-down menu above the vba code window, a subroutine will automatically be inserted into the code window for that object The arguments that Excel automatically feeds into that function (if there are any) are included into the Subroutine header - you then just need to add the vba code to define what you want to do when that event is fired Example The following example displays a message box every time the cell B1 in the Worksheet "Sheet1" is selected For this action, we need to use the Worksheet Event "Selection_Change", which 'fires' every time a different cell or range of cells is selected The "Selection_Change" function receives, as an argument, a Range object called "Target" This tells you the range of cells that has been selected As the "Selection_Change" event relates to any new selection, we need to check the supplied Range, 'Target', as soon as the 'Worksheet_Selection_Range' function is entered, so that we can perform our specific actions, only when the cell B1 has been selected The code for this is shown below:

45 ' Code to display a Message Box if Cell B1 of the current ' Worksheet is selected Private Sub Worksheet_SelectionChange(ByVal Target As Range) ' Check if the selection is cell B1 If TargetCount = 1 And TargetRow = 1 And TargetColumn = 2 Then ' The selection IS cell B1, so carry out required actions MsgBox "You have selected cell B1" End If End Sub

46 Excel VBA Tutorial Part 10 - VBA Error Types There are 3 types of VBA error that you may encounter when executing your macro These are Compile Errors, Runtime Errors and Logical Errors (or 'bugs') These VBA error types are discussed in turn, below, although more space is allocated to the Runtime Errors, and the way in which you can cater for these in your VBA code Compile Errors Compile Errors are recognised by the VBA compiler as being illegal and therefore, are highlighted as errors before your macro even starts to run If a compile error is an incorrectly formatted line of VBA code, the VBA editor will immediately detect and highlight this, as soon as you attempt to move your cursor away from the specific line of code Alternatively, a compile error may be detected at the time you attempt to run your macro (but before execution has started) A compile error is generally easy to fix, as the VBA compiler will give you information on the nature of this type of VBA error For example, if you get the message "Compile error: Variable not defined" when you attempt to run your code, this indicates that you are attempting to use, or access, a variable that has not been declared in the current scope (This error is only generated when you are using Option Explicit) Runtime Errors Runtime errors occur during the execution of your code, and cause the code to stop running This type of VBA error is also generally easy to fix, as you will be given details of the nature of the error, and shown the location where the code has stopped running For example, if your code attempts to divide by zero, you will be presented with a message box, which states "Run-time error '11': Division by zero" If you click on the Debug button on this message box, the line of code that generated the VBA error will be highlighted in your vba editor This is shown below

Hands-on Exercise 1: VBA Coding Basics

Hands-on Exercise 1: VBA Coding Basics Hands-on Exercise 1: VBA Coding Basics This exercise introduces the basics of coding in Access VBA. The concepts you will practise in this exercise are essential for successfully completing subsequent

More information

1. a procedure that you perform frequently. 2. Create a command. 3. Create a new. 4. Create custom for Excel.

1. a procedure that you perform frequently. 2. Create a command. 3. Create a new. 4. Create custom for Excel. Topics 1 Visual Basic Application Macro Language What You Can Do with VBA macro Types of VBA macro Recording VBA macros Example: MyName () If-Then statement Example: CheckCell () For-Next Loops Example:

More information

Excel Formatting: Best Practices in Financial Models

Excel Formatting: Best Practices in Financial Models Excel Formatting: Best Practices in Financial Models Properly formatting your Excel models is important because it makes it easier for others to read and understand your analysis and for you to read and

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

OpenOffice.org 3.2 BASIC Guide

OpenOffice.org 3.2 BASIC Guide OpenOffice.org 3.2 BASIC Guide Copyright The contents of this document are subject to the Public Documentation License. You may only use this document if you comply with the terms of the license. See:

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan DATA 301 Introduction to Data Analytics Microsoft Excel VBA Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca DATA 301: Data Analytics (2) Why Microsoft Excel Visual Basic

More information

Programming in Access VBA

Programming in Access VBA PART I Programming in Access VBA In this part, you will learn all about how Visual Basic for Applications (VBA) works for Access 2010. A number of new VBA features have been incorporated into the 2010

More information

Creating Applications using Excel Macros/Visual Basic for Applications (VBA)

Creating Applications using Excel Macros/Visual Basic for Applications (VBA) Creating Applications using Excel Macros/Visual Basic for Applications (VBA) A macro is a sequence of instructions that tells Microsoft Excel what to do. These macros allow you to automate everyday tasks

More information

RIT Installation Instructions

RIT Installation Instructions RIT User Guide Build 1.00 RIT Installation Instructions Table of Contents Introduction... 2 Introduction to Excel VBA (Developer)... 3 API Commands for RIT... 11 RIT API Initialization... 12 Algorithmic

More information

Microsoft Excel 2010 Tutorial

Microsoft Excel 2010 Tutorial 1 Microsoft Excel 2010 Tutorial Excel is a spreadsheet program in the Microsoft Office system. You can use Excel to create and format workbooks (a collection of spreadsheets) in order to analyze data and

More information

Final Exam Review: VBA

Final Exam Review: VBA Engineering Fundamentals ENG1100 - Session 14B Final Exam Review: VBA 1 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi Final Programming Exam Topics Flowcharts Assigning Variables

More information

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9.

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9. Working with Tables in Microsoft Word The purpose of this document is to lead you through the steps of creating, editing and deleting tables and parts of tables. This document follows a tutorial format

More information

Python Lists and Loops

Python Lists and Loops WEEK THREE Python Lists and Loops You ve made it to Week 3, well done! Most programs need to keep track of a list (or collection) of things (e.g. names) at one time or another, and this week we ll show

More information

ICAEW IT FACULTY TWENTY PRINCIPLES FOR GOOD SPREADSHEET PRACTICE

ICAEW IT FACULTY TWENTY PRINCIPLES FOR GOOD SPREADSHEET PRACTICE ICAEW IT FACULTY TWENTY PRINCIPLES FOR GOOD SPREADSHEET PRACTICE INTRODUCTION Many spreadsheets evolve over time without well-structured design or integrity checks, and are poorly documented. Making a

More information

Microsoft Excel 2010 Part 3: Advanced Excel

Microsoft Excel 2010 Part 3: Advanced Excel CALIFORNIA STATE UNIVERSITY, LOS ANGELES INFORMATION TECHNOLOGY SERVICES Microsoft Excel 2010 Part 3: Advanced Excel Winter 2015, Version 1.0 Table of Contents Introduction...2 Sorting Data...2 Sorting

More information

Introduction to Python

Introduction to Python WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language

More information

ECDL. European Computer Driving Licence. Spreadsheet Software BCS ITQ Level 2. Syllabus Version 5.0

ECDL. European Computer Driving Licence. Spreadsheet Software BCS ITQ Level 2. Syllabus Version 5.0 European Computer Driving Licence Spreadsheet Software BCS ITQ Level 2 Using Microsoft Excel 2010 Syllabus Version 5.0 This training, which has been approved by BCS, The Chartered Institute for IT, includes

More information

Q&As: Microsoft Excel 2013: Chapter 2

Q&As: Microsoft Excel 2013: Chapter 2 Q&As: Microsoft Excel 2013: Chapter 2 In Step 5, why did the date that was entered change from 4/5/10 to 4/5/2010? When Excel recognizes that you entered a date in mm/dd/yy format, it automatically formats

More information

Formatting Formatting Tables

Formatting Formatting Tables Intermediate Excel 2013 One major organizational change introduced in Excel 2007, was the ribbon. Each ribbon revealed many more options depending on the tab selected. The Help button is the question mark

More information

Excel & Visual Basic for Applications (VBA)

Excel & Visual Basic for Applications (VBA) Excel & Visual Basic for Applications (VBA) The VBA Programming Environment Recording Macros Working with the Visual Basic Editor (VBE) 1 Why get involved with this programming business? If you can't program,

More information

Excel & Visual Basic for Applications (VBA)

Excel & Visual Basic for Applications (VBA) Excel & Visual Basic for Applications (VBA) Object-oriented programming (OOP) Procedures: Subs and Functions, layout VBA: data types, variables, assignment 1 Traits of Engineers Florman s Engineering View

More information

Excel: Introduction to Formulas

Excel: Introduction to Formulas Excel: Introduction to Formulas Table of Contents Formulas Arithmetic & Comparison Operators... 2 Text Concatenation... 2 Operator Precedence... 2 UPPER, LOWER, PROPER and TRIM... 3 & (Ampersand)... 4

More information

Moving from C++ to VBA

Moving from C++ to VBA Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry

More information

Excel Level Two. Introduction. Contents. Exploring Formulas. Entering Formulas

Excel Level Two. Introduction. Contents. Exploring Formulas. Entering Formulas Introduction Excel Level Two This workshop introduces you to formulas, functions, moving and copying data, using autofill, relative and absolute references, and formatting cells. Contents Introduction

More information

Introduction. Syntax Statements. Colon : Line Continuation _ Conditions. If Then Else End If 1. block form syntax 2. One-Line syntax. Do...

Introduction. Syntax Statements. Colon : Line Continuation _ Conditions. If Then Else End If 1. block form syntax 2. One-Line syntax. Do... 3 Syntax Introduction Syntax Statements Colon : Line Continuation _ Conditions If Then Else End If 1. block form syntax 2. One-Line syntax Select Case Case Case Else End Select Do...Loop For...Next While...Wend

More information

USC Marshall School of Business Marshall Information Services

USC Marshall School of Business Marshall Information Services USC Marshall School of Business Marshall Information Services Excel Dashboards and Reports The goal of this workshop is to create a dynamic "dashboard" or "Report". A partial image of what we will be creating

More information

Add an Audit Trail to your Access Database

Add an Audit Trail to your Access Database Add an to your Access Database Published: 22 April 2013 Author: Martin Green Screenshots: Access 2010, Windows 7 For Access Versions: 2003, 2007, 2010 About This Tutorial My Access tutorials are designed

More information

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0 VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 UX Software - 2009 TABLE OF CONTENTS INTRODUCTION... ii What is this book about?... iii How to use this book... iii Time to start...

More information

Like any function, the UDF can be as simple or as complex as you want. Let's start with an easy one...

Like any function, the UDF can be as simple or as complex as you want. Let's start with an easy one... Building Custom Functions About User Defined Functions Excel provides the user with a large collection of ready-made functions, more than enough to satisfy the average user. Many more can be added by installing

More information

Macros in Word & Excel

Macros in Word & Excel Macros in Word & Excel Description: If you perform a task repeatedly in Word or Excel, you can automate the task by using a macro. A macro is a series of steps that is grouped together as a single step

More information

Commonly Used Excel Functions. Supplement to Excel for Budget Analysts

Commonly Used Excel Functions. Supplement to Excel for Budget Analysts Supplement to Excel for Budget Analysts Version 1.0: February 2016 Table of Contents Introduction... 4 Formulas and Functions... 4 Math and Trigonometry Functions... 5 ABS... 5 ROUND, ROUNDUP, and ROUNDDOWN...

More information

National Database System (NDS-32) Macro Programming Standards For Microsoft Word Annex - 8

National Database System (NDS-32) Macro Programming Standards For Microsoft Word Annex - 8 National Database System () Macro Programming Standards For Microsoft Word Annex - 8 02/28/2000 /10:23 AM ver.1.0.0 Doc. Id: RNMSWS softcopy : word page : 1/6 Objectives A well-defined system needs to

More information

Excel for Mac Text Functions

Excel for Mac Text Functions [Type here] Excel for Mac Text Functions HOW TO CLEAN UP TEXT IN A FLASH This document looks at some of the tools available in Excel 2008 and Excel 2011 for manipulating text. Last updated 16 th July 2015

More information

Abstract. For notes detailing the changes in each release, see the MySQL for Excel Release Notes. For legal information, see the Legal Notices.

Abstract. For notes detailing the changes in each release, see the MySQL for Excel Release Notes. For legal information, see the Legal Notices. MySQL for Excel Abstract This is the MySQL for Excel Reference Manual. It documents MySQL for Excel 1.3 through 1.3.6. Much of the documentation also applies to the previous 1.2 series. For notes detailing

More information

Getting Started with Excel 2008. Table of Contents

Getting Started with Excel 2008. Table of Contents Table of Contents Elements of An Excel Document... 2 Resizing and Hiding Columns and Rows... 3 Using Panes to Create Spreadsheet Headers... 3 Using the AutoFill Command... 4 Using AutoFill for Sequences...

More information

PL / SQL Basics. Chapter 3

PL / SQL Basics. Chapter 3 PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic

More information

Migrating to Excel 2010 from Excel 2003 - Excel - Microsoft Office 1 of 1

Migrating to Excel 2010 from Excel 2003 - Excel - Microsoft Office 1 of 1 Migrating to Excel 2010 - Excel - Microsoft Office 1 of 1 In This Guide Microsoft Excel 2010 looks very different, so we created this guide to help you minimize the learning curve. Read on to learn key

More information

Performing Simple Calculations Using the Status Bar

Performing Simple Calculations Using the Status Bar Excel Formulas Performing Simple Calculations Using the Status Bar If you need to see a simple calculation, such as a total, but do not need it to be a part of your spreadsheet, all you need is your Status

More information

Visual Basic - Modules and Procedures

Visual Basic - Modules and Procedures Visual Basic - Modules and Procedures Introduction A procedure is a unit of code enclosed either between the Sub and statements or between the Function and statements. A procedure should accomplish a simple

More information

Excel 2007: Basics Learning Guide

Excel 2007: Basics Learning Guide Excel 2007: Basics Learning Guide Exploring Excel At first glance, the new Excel 2007 interface may seem a bit unsettling, with fat bands called Ribbons replacing cascading text menus and task bars. This

More information

Using Parametric Equations in SolidWorks, Example 1

Using Parametric Equations in SolidWorks, Example 1 Using Parametric Equations in SolidWorks, Example 1 (Draft 4, 10/25/2006, SW 2006) Introduction In this example the goal is to place a solid roller on a solid wedge. Their relationship will be governed

More information

Introducing VBA Message Boxes

Introducing VBA Message Boxes Introducing VBA Message Boxes It's All About Communication When you build a tool for someone else to use it is important that that person, "the user", knows what's going on and feels confident using it.

More information

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved.

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved. 1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,

More information

Introduction to Microsoft Access 2003

Introduction to Microsoft Access 2003 Introduction to Microsoft Access 2003 Zhi Liu School of Information Fall/2006 Introduction and Objectives Microsoft Access 2003 is a powerful, yet easy to learn, relational database application for Microsoft

More information

Excel 2007 Basic knowledge

Excel 2007 Basic knowledge Ribbon menu The Ribbon menu system with tabs for various Excel commands. This Ribbon system replaces the traditional menus used with Excel 2003. Above the Ribbon in the upper-left corner is the Microsoft

More information

Excel macros made easy

Excel macros made easy IT Training Excel macros made easy Jane Barrett, IT Training & Engagement Team Information System Services Version 1.1 Scope Learning outcomes Understand the concept of what a macro is and what it does.

More information

Microsoft Excel Basics

Microsoft Excel Basics COMMUNITY TECHNICAL SUPPORT Microsoft Excel Basics Introduction to Excel Click on the program icon in Launcher or the Microsoft Office Shortcut Bar. A worksheet is a grid, made up of columns, which are

More information

Microsoft Access 2010 Overview of Basics

Microsoft Access 2010 Overview of Basics Opening Screen Access 2010 launches with a window allowing you to: create a new database from a template; create a new template from scratch; or open an existing database. Open existing Templates Create

More information

A Concise Guide for Beginners LIEW VOON KIONG

A Concise Guide for Beginners LIEW VOON KIONG I A Concise Guide for Beginners LIEW VOON KIONG Disclaimer II Excel VBA Made Easy- A Concise Guide for Beginners is an independent publication and is not affiliated with, nor has it been authorized, sponsored,

More information

Using the For Each Statement to 'loop' through the elements of an Array

Using the For Each Statement to 'loop' through the elements of an Array Using the For Each Statement to 'loop' through the elements of an Array This month's article was inspired by a Visual Basic tip I saw recently that touted the advantages of using LBound and Ubound functions

More information

Excel Reporting with 1010data

Excel Reporting with 1010data Excel Reporting with 1010data (212) 405.1010 info@1010data.com Follow: @1010data www.1010data.com Excel Reporting with 1010data Contents 2 Contents Overview... 3 Start with a 1010data query... 5 Running

More information

Excel 2010 Sorting and Filtering

Excel 2010 Sorting and Filtering Excel 2010 Sorting and Filtering Computer Training Centre, UCC, tcentre@ucc.ie, 021-4903749/3751/3752 Table of Contents Sorting Data... 1 Sort Order... 1 Sorting by Cell Colour, Font Colour or Cell Icon...

More information

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

Visual Basic: Objects and collections

Visual Basic: Objects and collections : Objects and collections is an (OO) object-oriented language. Performing a task in (VB) or for Applications (VBA) involves manipulating various types of objects, each of which may have several different

More information

Excel 2003 Tutorial I

Excel 2003 Tutorial I This tutorial was adapted from a tutorial by see its complete version at http://www.fgcu.edu/support/office2000/excel/index.html Excel 2003 Tutorial I Spreadsheet Basics Screen Layout Title bar Menu bar

More information

INTRODUCTION TO EXCEL

INTRODUCTION TO EXCEL INTRODUCTION TO EXCEL 1 INTRODUCTION Anyone who has used a computer for more than just playing games will be aware of spreadsheets A spreadsheet is a versatile computer program (package) that enables you

More information

The FTS Interactive Trader lets you create program trading strategies, as follows:

The FTS Interactive Trader lets you create program trading strategies, as follows: Program Trading The FTS Interactive Trader lets you create program trading strategies, as follows: You create the strategy in Excel by writing a VBA macro function The strategy can depend on your position

More information

EXCEL Tutorial: How to use EXCEL for Graphs and Calculations.

EXCEL Tutorial: How to use EXCEL for Graphs and Calculations. EXCEL Tutorial: How to use EXCEL for Graphs and Calculations. Excel is powerful tool and can make your life easier if you are proficient in using it. You will need to use Excel to complete most of your

More information

Highline Excel 2016 Class 26: Macro Recorder

Highline Excel 2016 Class 26: Macro Recorder Highline Excel 2016 Class 26: Macro Recorder Table of Contents Macro Recorder Examples in this video... 2 1) Absolute Reference Macro: Format report that always has the same number of columns and rows...

More information

The VB development environment

The VB development environment 2 The VB development environment This chapter explains: l how to create a VB project; l how to manipulate controls and their properties at design-time; l how to run a program; l how to handle a button-click

More information

Creating Basic Excel Formulas

Creating Basic Excel Formulas Creating Basic Excel Formulas Formulas are equations that perform calculations on values in your worksheet. Depending on how you build a formula in Excel will determine if the answer to your formula automatically

More information

Excel Programming Tutorial 1

Excel Programming Tutorial 1 Excel Programming Tutorial 1 Macros and Functions by Dr. Tom Co Department of Chemical Engineering Michigan Technological University (8/31/07, 11/11/07) Excel Version: Excel 2007 Basic Concepts: Features:

More information

Excel. Microsoft Office s spreadsheet application can be used to track. and analyze numerical data for display on screen or in printed

Excel. Microsoft Office s spreadsheet application can be used to track. and analyze numerical data for display on screen or in printed Excel Microsoft Office s spreadsheet application can be used to track and analyze numerical data for display on screen or in printed format. Excel is designed to help you record and calculate data, and

More information

MICROSOFT EXCEL FORMULAS

MICROSOFT EXCEL FORMULAS MICROSOFT EXCEL FORMULAS Building Formulas... 1 Writing a Formula... 1 Parentheses in Formulas... 2 Operator Precedence... 2 Changing the Operator Precedence... 2 Functions... 3 The Insert Function Button...

More information

How to Use Excel for Law Firm Billing

How to Use Excel for Law Firm Billing How to Use Excel for Law Firm Billing FEATURED FACULTY: Staci Warne, Microsoft Certified Trainer (MCT) (801) 463-1213 computrainhelp@hotmail.com Staci Warne, Microsoft Certified Trainer (MCT) Staci Warne

More information

Intellect Platform - The Workflow Engine Basic HelpDesk Troubleticket System - A102

Intellect Platform - The Workflow Engine Basic HelpDesk Troubleticket System - A102 Intellect Platform - The Workflow Engine Basic HelpDesk Troubleticket System - A102 Interneer, Inc. Updated on 2/22/2012 Created by Erika Keresztyen Fahey 2 Workflow - A102 - Basic HelpDesk Ticketing System

More information

Excel 2007 A Beginners Guide

Excel 2007 A Beginners Guide Excel 2007 A Beginners Guide Beginner Introduction The aim of this document is to introduce some basic techniques for using Excel to enter data, perform calculations and produce simple charts based on

More information

Exercise 4 Learning Python language fundamentals

Exercise 4 Learning Python language fundamentals Exercise 4 Learning Python language fundamentals Work with numbers Python can be used as a powerful calculator. Practicing math calculations in Python will help you not only perform these tasks, but also

More information

Microsoft Excel 2013 Tutorial

Microsoft Excel 2013 Tutorial Microsoft Excel 2013 Tutorial TABLE OF CONTENTS 1. Getting Started Pg. 3 2. Creating A New Document Pg. 3 3. Saving Your Document Pg. 4 4. Toolbars Pg. 4 5. Formatting Pg. 6 Working With Cells Pg. 6 Changing

More information

Create Charts in Excel

Create Charts in Excel Create Charts in Excel Table of Contents OVERVIEW OF CHARTING... 1 AVAILABLE CHART TYPES... 2 PIE CHARTS... 2 BAR CHARTS... 3 CREATING CHARTS IN EXCEL... 3 CREATE A CHART... 3 HOW TO CHANGE THE LOCATION

More information

Excel basics. Before you begin. What you'll learn. Requirements. Estimated time to complete:

Excel basics. Before you begin. What you'll learn. Requirements. Estimated time to complete: Excel basics Excel is a powerful spreadsheet and data analysis application, but to use it most effectively, you first have to understand the basics. This tutorial introduces some of the tasks and features

More information

Introduction to Python

Introduction to Python Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment

More information

MAS 500 Intelligence Tips and Tricks Booklet Vol. 1

MAS 500 Intelligence Tips and Tricks Booklet Vol. 1 MAS 500 Intelligence Tips and Tricks Booklet Vol. 1 1 Contents Accessing the Sage MAS Intelligence Reports... 3 Copying, Pasting and Renaming Reports... 4 To create a new report from an existing report...

More information

Microsoft Access 2010 handout

Microsoft Access 2010 handout Microsoft Access 2010 handout Access 2010 is a relational database program you can use to create and manage large quantities of data. You can use Access to manage anything from a home inventory to a giant

More information

How to Excel with CUFS Part 2 Excel 2010

How to Excel with CUFS Part 2 Excel 2010 How to Excel with CUFS Part 2 Excel 2010 Course Manual Finance Training Contents 1. Working with multiple worksheets 1.1 Inserting new worksheets 3 1.2 Deleting sheets 3 1.3 Moving and copying Excel worksheets

More information

One Dimension Array: Declaring a fixed-array, if array-name is the name of an array

One Dimension Array: Declaring a fixed-array, if array-name is the name of an array Arrays in Visual Basic 6 An array is a collection of simple variables of the same type to which the computer can efficiently assign a list of values. Array variables have the same kinds of names as simple

More information

MS Excel. Handout: Level 2. elearning Department. Copyright 2016 CMS e-learning Department. All Rights Reserved. Page 1 of 11

MS Excel. Handout: Level 2. elearning Department. Copyright 2016 CMS e-learning Department. All Rights Reserved. Page 1 of 11 MS Excel Handout: Level 2 elearning Department 2016 Page 1 of 11 Contents Excel Environment:... 3 To create a new blank workbook:...3 To insert text:...4 Cell addresses:...4 To save the workbook:... 5

More information

How To Use Excel With A Calculator

How To Use Excel With A Calculator Functions & Data Analysis Tools Academic Computing Services www.ku.edu/acs Abstract: This workshop focuses on the functions and data analysis tools of Microsoft Excel. Topics included are the function

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

DATA VALIDATION and CONDITIONAL FORMATTING

DATA VALIDATION and CONDITIONAL FORMATTING DATA VALIDATION and CONDITIONAL FORMATTING Data validation to allow / disallow certain types of data to be entered within a spreadsheet Using Data Validation to choose a value for a cell from a dropdown

More information

Programming MS Excel in Visual Basic (VBA)

Programming MS Excel in Visual Basic (VBA) Programming MS Excel in Visual Basic (VBA) Part 2-Branching & Looping, Message Boxes & Alerts by Kwabena Ofosu, Ph.D., P.E., PTOE Abstract This course is the second of a four-part series on computer programming

More information

Microsoft Excel Tips & Tricks

Microsoft Excel Tips & Tricks Microsoft Excel Tips & Tricks Collaborative Programs Research & Evaluation TABLE OF CONTENTS Introduction page 2 Useful Functions page 2 Getting Started with Formulas page 2 Nested Formulas page 3 Copying

More information

What is Microsoft Excel?

What is Microsoft Excel? What is Microsoft Excel? Microsoft Excel is a member of the spreadsheet family of software. Spreadsheets allow you to keep track of data, create charts based from data, and perform complex calculations.

More information

Module 2 - Multiplication Table - Part 1-1

Module 2 - Multiplication Table - Part 1-1 Module 2 - Multiplication Table - Part 1 TOPICS COVERED: 1) VBA and VBA Editor (0:00) 2) Arrays (1:15) 3) Creating a Multiplication Table (2:34) 4) TimesTable Subroutine (3:08) 5) Improving Efficiency

More information

paragraph(s). The bottom mark is for all following lines in that paragraph. The rectangle below the marks moves both marks at the same time.

paragraph(s). The bottom mark is for all following lines in that paragraph. The rectangle below the marks moves both marks at the same time. MS Word, Part 3 & 4 Office 2007 Line Numbering Sometimes it can be helpful to have every line numbered. That way, if someone else is reviewing your document they can tell you exactly which lines they have

More information

Microsoft Excel 2007 Consolidate Data & Analyze with Pivot Table Windows XP

Microsoft Excel 2007 Consolidate Data & Analyze with Pivot Table Windows XP Microsoft Excel 2007 Consolidate Data & Analyze with Pivot Table Windows XP Consolidate Data in Multiple Worksheets Example data is saved under Consolidation.xlsx workbook under ProductA through ProductD

More information

3 What s New in Excel 2007

3 What s New in Excel 2007 3 What s New in Excel 2007 3.1 Overview of Excel 2007 Microsoft Office Excel 2007 is a spreadsheet program that enables you to enter, manipulate, calculate, and chart data. An Excel file is referred to

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

ACADEMIC TECHNOLOGY SUPPORT

ACADEMIC TECHNOLOGY SUPPORT ACADEMIC TECHNOLOGY SUPPORT Microsoft Excel: Formulas ats@etsu.edu 439-8611 www.etsu.edu/ats Table of Contents: Overview... 1 Objectives... 1 1. How to Create Formulas... 2 2. Naming Ranges... 5 3. Common

More information

Welcome to the topic on creating key performance indicators in SAP Business One, release 9.1 version for SAP HANA.

Welcome to the topic on creating key performance indicators in SAP Business One, release 9.1 version for SAP HANA. Welcome to the topic on creating key performance indicators in SAP Business One, release 9.1 version for SAP HANA. 1 In this topic, you will learn how to: Use Key Performance Indicators (also known as

More information

Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick Reference Guide

Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick Reference Guide Open Crystal Reports From the Windows Start menu choose Programs and then Crystal Reports. Creating a Blank Report Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick

More information

Basic Excel Handbook

Basic Excel Handbook 2 5 2 7 1 1 0 4 3 9 8 1 Basic Excel Handbook Version 3.6 May 6, 2008 Contents Contents... 1 Part I: Background Information...3 About This Handbook... 4 Excel Terminology... 5 Excel Terminology (cont.)...

More information

MICROSOFT EXCEL STEP BY STEP GUIDE

MICROSOFT EXCEL STEP BY STEP GUIDE IGCSE ICT SECTION 14 DATA ANALYSIS MICROSOFT EXCEL STEP BY STEP GUIDE Mark Nicholls ICT Lounge Data Analysis Self Study Guide Contents Learning Outcomes Page 3 What is a Data Model?... Page 4 Spreadsheet

More information

CREATING FORMAL REPORT. using MICROSOFT WORD. and EXCEL

CREATING FORMAL REPORT. using MICROSOFT WORD. and EXCEL CREATING a FORMAL REPORT using MICROSOFT WORD and EXCEL TABLE OF CONTENTS TABLE OF CONTENTS... 2 1 INTRODUCTION... 4 1.1 Aim... 4 1.2 Authorisation... 4 1.3 Sources of Information... 4 2 FINDINGS... 4

More information

Microsoft Access 2010

Microsoft Access 2010 IT Training Microsoft Access 2010 Jane Barrett, IT Training & Engagement Team Information System Services Version 3.0 Scope Learning outcomes Learn how to navigate around Access. Learn how to design and

More information

The Center for Teaching, Learning, & Technology

The Center for Teaching, Learning, & Technology The Center for Teaching, Learning, & Technology Instructional Technology Workshops Microsoft Excel 2010 Formulas and Charts Albert Robinson / Delwar Sayeed Faculty and Staff Development Programs Colston

More information

Tutorial 2: Using Excel in Data Analysis

Tutorial 2: Using Excel in Data Analysis Tutorial 2: Using Excel in Data Analysis This tutorial guide addresses several issues particularly relevant in the context of the level 1 Physics lab sessions at Durham: organising your work sheet neatly,

More information

Differences in Use between Calc and Excel

Differences in Use between Calc and Excel Differences in Use between Calc and Excel Title: Differences in Use between Calc and Excel: Version: 1.0 First edition: October 2004 Contents Overview... 3 Copyright and trademark information... 3 Feedback...3

More information

Visual Basic 2010 Essentials

Visual Basic 2010 Essentials Visual Basic 2010 Essentials Visual Basic 2010 Essentials First Edition 2010 Payload Media. This ebook is provided for personal use only. Unauthorized use, reproduction and/or distribution strictly prohibited.

More information