260 likes | 277 Views
Learn the power of arrays in Excel, solving problems effectively by storing data in matrices. Understand array declaration and usage, plus how arrays simplify VBA code. Practice array manipulation with examples.
E N D
259 Lecture 13 Spring 2017 Advanced Excel Topics – Arrays
Topics • Arrays • Why Use Arrays? • Declaring an Array • Working with Arrays • Multiple Valued User Defined Functions • Cell Ranges as Arguments • Array Formulas • Array Outputs for User Defined Functions
Arrays • Definition: An array is a group of elements of the same type that have a common name. • A specific element in an array is referred to by using the array name and an index number. • Arrays are variables that can store multiple values. • Arrays very closely resemble matrices used in mathematics in both form and operation.
Why Use Arrays? (1) Arrays make it possible to solve problems using “Matrices” and “Linear Algebra” techniques. (2) Arrays make it possible for user defined functions to work with cell ranges. For example use the formula =MySum(A1:A5) instead of the formula =MySum(A1,A2,A3,A4,A5). (3) Arrays make it possible for a user defined function to return multiple values. For example: • =BestFitLine() returns the “Slope” of the best-fit line for a set of N ordered pairs of data, {(x1, y1), (x2, y2), … , (xN, yN)}. • =BestFitLine() returns the “YIntercept” of the best-fit line for a set of N ordered pairs of data, {(x1, y1), (x2, y2), … , (xN, yN)}. • =BestFitLine() returns the “Equation” of the best-fit line for a set of N ordered pairs of data, {(x1, y1), (x2, y2), … , (xN, yN)}. • =BestFitLine() returns the slope, y-intercept, and equation for the best-fit line for a set of N ordered pairs of data, {(x1, y1), (x2, y2), … , (xN, yN)} in an array. (4) Arrays often simplify VBA code.
Declaring Arrays • Just like any other variable, arrays should be declared before they are used. • To declare an array, both the size of the array and the data type of the values that the array will hold must be specified.
Declaring Arrays • Here are some examples of array declarations: ‘Declare a “1-dimensional” array named “A” that has 5 elements. ‘Think of A as a matrix with 1 row and 5 columns. Dim A(1 To 5) As Integer ‘Declare a “1-dimensional” array named “Names” that has 10 elements. ‘Think of Names as a matrix with 1 row and 10 columns. Dim Names(1 To 10) As String ‘Declare a “2-dimensional” array named “Table” that has 24 elements. ‘Think of Table as a matrix with 12 rows and 2 columns. Dim Table(1 To 12, 1 To 2) As Double
Working with Arrays • Remember that a specific element in an array is referred to by using the array name and index number. • For example, • A(4) is the fourth element in 1-dimensional array A, or equivalently, the element from Row 1, Column 4 of array A. • Names(1) is the first string in 1-dimensional array Names, or equivalently, the element from Row 1, Column 1 of array Names. • Table(2,3) is the element from Row 2, Column 3 of 2-dimensional array Table.
Working with Arrays • Example 1: Set every element in the array “A” to the value of 1. ‘Assuming that array “A” has already been declared as well as other variables. For K = 1 To 5 A(K) = 1 Next K
Working with Arrays • Example 2: Set every element in the array “Table” to a random number in the interval (0,1). ‘Assuming that array “Table” has already been declared as well as other variables For Col = 1 To 2 For Row = 1 To 12 Table(Row,Col) = Rnd() Next Row Next Col
Working with Arrays • Example 3: Add up all of the elements in the array “A” pre-loaded with random numbers. ‘Assuming that array “A” has already been declared as 'well as other variables ‘Also assuming that array A has already been pre-loaded Total = 0 For K = 1 To 5 Total = Total + A(K) Next K
Working with Arrays • Example 4: Increment every element in the array “A” by 1. ‘Assuming that array “A” has already been declared as ‘well as other variables ‘Also assuming that array A has already been pre-loaded For K = 1 To 5 A(K) = A(K) + 1 Next K
Working with Arrays • Example 5: Determine the frequency of each letter A-Z contained in the phrase “In any right-angled triangle, the area of the square whose side is the hypotenuse is equal to the sum of the areas of the squares whose sides are the two legs” without using arrays. ‘Assume that variables have been previously declared ‘Set counters A-Z to zero Count_A = 0 Count_B = 0 Count_C = 0 ‘ etc., … Phrase = “In any right-angled triangle, the area of the square whose side is the hypotenuse is equal to the sum of the areas of the squares whose sides are the two legs” Phrase = UCase(Phrase) For K = 1 To Len(Phrase) Ch = Mid(Phrase,K,1) If Ch <> “ “ Then If Ch = “A” Then Count_A = Count_A + 1 If Ch = “B” Then Count_B = Count_B + 1 If Ch = “C” Then Count_C = Count_C + 1 ‘ etc., … End If Next K ‘Frequencies for letters A-Z are contained in Count_A, Count_B, … , Count_Z
Working with Arrays • Example 6: Determine the frequency of each letter A-Z contained in the phrase “In any right-angled triangle, the area of the square whose side is the hypotenuse is equal to the sum of the areas of the squares whose sides are the two legs” using arrays. Dim Count(1 to 26) As Integer ‘Assume that all other variables have been previously declared ‘Set counters for A-Z to zero For K = 1 To 26 Count(K) = 0 Next K Phrase = “In any right-angled triangle, the area of the square whose side is the hypotenuse is equal to the sum of the areas of the squares whose sides are the two legs” Phrase = UCase(Phrase) For K = 1 To Len(Phrase) Ch = Mid(Phrase,K,1) If Ch <> “ “ Then Index = Asc(Ch) - 64 Count(Index) = Count(Index) + 1 End If Next K ‘Frequencies for letters A-Z are now contained in Count(1-26)
User Defined Functions and Arrays • Recall that in addition to simplifying VBA code, other advantages of using “Arrays” were to (1) make it possible for user defined functions to work with cell ranges, and (2) make it possible for a User Defined Function to return multiple values.
Cell Ranges as Arguments • It is possible to pass a range of worksheet cells into a User Defined Function as an argument to the function. • A range of worksheet cells passed into a User Defined Function will behave like an “Array” .
Cell Ranges as Arguments • Example 7: A function that takes entries from a range of column values as well as two numbers as inputs! Function Sample(Q As Variant, X As Double, Y As Double) As Variant ‘etc., … End Function • To call the function, use =Sample(A2:A7,12,15.2)
Cell Ranges as Arguments • Example 8: A function that takes more than one array as an argument. Function Sample2(Q As Variant, R As Variant, Z As Variant) As Variant ‘etc., … End Function • To call this function, use =Sample2(B6:B8,C1:D2,E4:G4)
Cell Ranges as Arguments • Example 8: Create a user defined function MyDet22() that will return the determinant of a 2x2 matrix given a range of 2x2 cell range. • For example, MyDet22(C2:D3) should return a value of -2 . Function MyDet22(Mat As Variant) As Double ‘Returns the “Determinant” of a 2x2 matrix ‘The 2x2 matrix is passed into this function as a cell range MyDet22 = Mat(2,2)*Mat(1,1)- Mat(2,1)*Mat(1,2) End Function
Array Formulas • When working with arrays, it is useful to know how to work with array formulas! • An array formula is a formula that can perform multiple calculations on one or more of the items in an array. • Array formulas can return either multiple results or a single result. • For example, an array formula can be placed in a range of cells, such as a column or row, and used to calculate a column or row of subtotals. • An array formula can also be placed in a single cell and be used to calculate a single amount. • An array formula that resides in multiple cells is called a multi-cell formula, and an array formula that resides in a single cell is called a single-cell formula.
Array Formulas • Example 9: Go to the help file web page for Guidelines and examples of array formulas. • Try the examples • Create a multi-cell array formula • Create a single-cell array formula
Array Formulas • Ex. 9 (cont.): Create a multi-cell array formula • Open a new, blank workbook. • Copy the example worksheet data, and then paste it into the new workbook starting at cell A1. • To multiply the values in the array (the cell range C2 through D11), select cells E2 through E11, and then enter the following formula in the formula bar: =C2:C11*D2:D11 • Press CTRL+SHIFT+ENTER. • Excel surrounds the formula with braces ({ }) and places an instance of the formula in each cell of the selected range. • What appears in column E is the total sales amount for each car type for each salesperson.
Array Formulas • Ex. 9 (cont.): Create a single-cell array formula • In cell A13 of the workbook, type Total Sales. • In cell B13, type the following formula, and then press CTRL+SHIFT+ENTER =SUM(C2:C11*D2:D11) • In this case, Excel multiplies the values in the array (the cell range C2 through D11) and then uses the SUM function to add the totals together. • Note that the single-cell formula (in cell B13) is completely independent of the multi-cell formula (the formula in cells E2 through E11).
Array Formulas • For the most part, array formulas use standard formula syntax. • All array formulas begin with an equal sign, and any of the built-in Excel functions can be used in array formulas. • The key difference is that when using an array formula, CTRL+SHIFT+ENTER must be pressed to enter the array formula. • When this is done, Excel surrounds the array formula with braces — if the braces are typed manually, the formula will be converted to a text string, and will not work.
Array Formulas • When working with multi-cell formulas, one needs to follow these rules: • Select the range of cells to hold output results before entering the formula. • The contents of an individual cell in an array formula cannot be changed. • An entire array formula can be moved or deleted, but part of an array formula cannot be moved or deleted. • To “shrink” an array formula, first delete the existing formula, then start over. • To delete an array formula, select the entire formula press DELETE, and then press CTRL+SHIFT+ENTER. • Blank cells cannot be inserted into or deleted from a multi-cell array formula.
Array Outputs for User Defined Functions • For multiple values output as an array for a user defined function, use the idea of array formulas! • For example, try the following function, Sample(): Function Sample(A As Variant, B As Variant) As Variant Dim K As Integer, C(1 To 4, 1 To 2) As Integer For K = 1 To 4 C(K, 1) = A(K) + B(K) C(K, 2) = A(K) + A(K) Next K Sample = C End Function
References • Notes on Arrays – John Albers • Array Formulas (pp. 19-24) – Excel Help Files (Guidelines and examples of array formulas) http://office.microsoft.com/en-us/excel-help/guidelines-and-examples-of-array-formulas-HA010228458.aspx