Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) 456-7890 University Name.

Similar presentations


Presentation on theme: "Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) 456-7890 University Name."— Presentation transcript:

1 Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name name@email.com Position (123) 456-7890 University Name

2 2 Overview  17.1 Introduction  17.2 When and Why to Use Arrays  17.3 Defining Arrays  17.4 Dynamic Arrays  17.5 Sorting Arrays  17.6 Applications  17.7 Summary

3 3 Introduction  Arrays and how they are beneficial  Defining one-dimensional and multi-dimensional arrays  Modifying the indexing standard for arrays in VBA  Dynamic arrays  Sorting arrays  An application which uses several arrays

4 4 When and Why to Use Arrays  Arrays store series of data that can be manipulated or referred to later.  The set of values stored in an array must all be of the same data type.  You can refer to the array as a whole or you can refer to its individual elements by an index value.

5 5 Defining Arrays  Multi-Dimensional Arrays  Indexing

6 6 Defining Arrays  To define an array, we can use the Dim, Private, or Public variable declarations.  There is not an array data type however. –The array will be named and the data type will be assigned to all of the elements in that array.  VBA will recognize that your variable is an array and not a scalar variable because you must specify the size of the array in the variable declaration.  Here is a quick example of defining an array of double data type, which has 10 elements and is named data. Dim data(10) As Double

7 7 Array Values  To insert values into this array, we can use the entire array variable and the Array function.  The Array function allows you to list values for each array element.  For example to insert 10 values into the data array, we could type the following. Dim data() As Variant data = Array(12.3, 13.4, 16.5, 13.8, 7, 2.9, 24.2, 5.5, 8, 9.1)

8 8 Array Values (cont’d)  To set the value of a specific element of the array, we use an index.  For example, if we want to change the third value in the above data array from 16.5 to 10.5, we type. –data(3) = 10.5  To enter multiple element values using indices, we use a For, Next loop with a counter variable.  For example, if we want to set each element in the data array as its index number we type. For i = 1 to 10 data(i) = i Next i

9 9 Multi-Dimensional Arrays  For a one-dimensional array, a single number is all that is necessary to specify the size.  To define multi-dimensional arrays, you just need to specify the size of each dimension, separated by a comma.  For example, if we want to define a two-dimensional array of size 5 by 10 (number of rows by number of columns) we could type Dim data(5, 10) As Double

10 10 Multi-Dimensional Arrays (cont’d)  To insert values into a multi-dimensional array or to search for a value, use nested For, Next loops with different counter variables.  For example, to set the value of each element in the above two- dimensional array equal to the product of its index numbers. For i = 1 to 5 For j = 1 to 10 data(i, j) = i*j Next j Next i 12345678910 2468 1214161820 36912151821242730 481216202428323640 5101520253035404550

11 11 Multi-Dimensional Arrays (cont’d)  Let us create a two-­dimensional array where the value of each element of the array shows the order in which it is generated.  For example, the value 25, which corresponds to the 3 rd row and 5 th column of this array, is the 25 th value generated. For i = 1 to 5 For j = 1 to 10 data(i, j) = (i-1)*10+j Next j Next i 12345678910 11121314151617181920 21222324252627282930 31323334353637383940 41424344454647484950

12 12 Indexing  The default initial index value of arrays in VBA is 0. To change the initial index value of all arrays in your module to 1, type Option Base 1 at the top of the module.  If you want to keep the default initial index as 0 but have a specific array which you want to index starting at 1, you can specify the starting index value in the array declaration as (1 to arraysize).  In the example below, Option Base 1 is used. Here both the data and results arrays will have an initial index of 1. Option Base 1 Dim data(10) As Double, results(12) As Double

13 13 Indexing (cont’d)  If we do not specify the Option Base setting but instead change the index of one of the arrays, the data array will begin with index of 1, but the results array will begin with an index of 0. Dim data(1 to 10) As Double, results(12) As Double  There may be situations in which specific arrays need different indexing bounds. In this case, you can start the index at any value, just be aware of the size of your array. –size = upper index bound – lower index bound + 1 –Dim results(2 to 13) As Double  We need to coordinate the initial index value that we chose with the counter variable used in For, Next loops. For i = 2 to 13 results(i) = value Next i

14 14 Dynamic Arrays  If you are not sure what size an array should be, or will be depending on the user or other dynamic programming reasons, you can define a dynamic array.  When declaring a dynamic array, the size is not specified; the parentheses are left empty. Dim input() As Double  However, to use this array or any of its elements, we will need to eventually know its size.  To set the size of a dynamic array at some later point in the code, we use the ReDim statement.

15 15 Dynamic Arrays (cont’d)  Suppose we want to ask the user to insert some input values, which we will store in our input array, but we are unsure how many values they want to insert.  We can first assign a variable to an Input Box which asks for the number of values, and then we can insert the value of each element using a For, Next loop. size = InputBox(“How many values will you enter as input?”) ReDim input(1 to size) As Double For i = 1 to size input(i) = InputBox(“Please enter value for element “ & i ) Next i

16 16 Dynamic Arrays (cont’d)  If you want to change the size of an array but do not want to reset its values, then use the ReDim Preserve statement.  Suppose the user wants to add more elements to the input array in the previous example.  We want to keep, or preserve, the array we used previously but increase its size to account for the new elements. size2 = InputBox(“How many MORE elements to you want to add?”) ReDim Preserve input(1 to size + size2) For i = size+1 to size2 input(i) = InputBox(“Please enter value for element “ & i) Next i

17 17 Sorting Arrays  There are two general ways to sort arrays in VBA. –Output array values to the spreadsheet and use Excel’s sorting functions. –Use a sorting algorithm with loops structures in the VBA code.

18 18 Sorting using Excel  Output an array to a range in the spreadsheet, sort it in this range, and then input it back into the array.  The code to sort an array of size 10 in increasing order using Excel’s sort functions would be as follows. Sub ExcelSort() For i = 1 to 10 Range(“ArrayStart”).Offset(i, 0).Value = data(i) Next i Range(Range(“ArrayStart”).Offset(1,0), Range(“ArrayStart”).Offset(10,0)).Sort Key1:=Range(“ArrayStart”),Order1:=xlAscending For i = 1 to 10 data(i) = Range(“ArrayStart”).Offset(i,0).Value Next i End Sub

19 19 Sorting using VBA  There are many various sorting algorithms which can be implemented in VBA for sorting arrays.  We give an example of the Bubble Sort algorithm.

20 20 Bubble Sort Algorithm  The Bubble Sort algorithm performs passes over the elements to be sorted.  In each pass, it considers an element, say p, in order and compares it with the next element, say q.  If p > q (and we are trying to sort the list in ascending order), then the two elements are switched since they are out of order.  A pass ends when each element has been compared with the next element and switched (it is found to be out of order).  The algorithm terminates when in one complete pass no two elements were found to be out of order (implying that all elements have been sorted).

21 21 Bubble Sort Example  Consider the data array –data(10) = Array(5, 2, 8, 3, 7, 1, 9, 6, 10, 4)  We first compare 5 with 2 and find that 5 is larger, so we switch the two elements.  We now compare 5 with 8 and find that 5 is smaller, so we now select 8 and continue our comparisons.  We compare 8 with 3 and find that 8 is bigger so we switch the elements.  We then compare 8 with 7 and find that 8 is bigger so we again switch the elements.  We compare 8 with 1 and again switch the elements.  Then, we compare 8 to 9 and find that 9 is bigger so we now select 9 and continue our comparisons.  We compare 9 with 6 and find that 9 is bigger so we switch the elements.  We compare 9 with 10, but 10 is bigger so we now select 10.  We compare 10 with 4 and switch the elements since 10 is bigger.  We have now reached the end of the array and have completed the first pass of the algorithm. The current state of the array is as follows: –data(10) = Array(2, 5, 3, 7, 1, 8, 6, 9, 4, 10)

22 22 Bubble Sort in VBA  We can use the following procedure to perform the Bubble Sort algorithm in VBA. Sub BubbleSort() Dim sorted As Boolean, temp As Double j=10 Do sorted = True For i = 1 To j-1 If data(i) > data (i + 1) Then temp = data (i) data (i) = data (i + 1) data (i + 1) = temp sorted=False End If Next i j=j-1 Loop While sorted=False End Sub

23 23 Arrays with Function Procedures  Arrays can be used with function procedures as well. –You can pass the name of an array to a function procedure to manipulate some or all of its elements. –You can also pass elements of an array to a function procedure to manipulate.  You can initialize a new array variable using a function procedure as follows. Dim NewArray() As Double ArrayFunction(NewArray)  You could also create a function procedure to pass an array and sort it. Function BubbleSort(ArrayName)

24 24 Applications  Phonebook

25 25 Phonebook  We develop a phonebook application which uses dynamic arrays –This application allows a user to search through, add new entries to, and view all listings in a phonebook. –The phonebook stores a name and number for each entry.

26 26 Preparation  There are only two worksheets for this program –“Phonebook Welcome” –“Phone Data”  The “Phonebook Welcome” sheet is the basic welcome sheet with a problem description. –The button options appear on this sheet as well.  The “Phone Data” sheet has a table with the name and number of each entry in the phonebook. –There is also a button to return to the “Phonebook Welcome” sheet.

27 27 Figure 17.1

28 28 Figure 17.2

29 29 Procedures  We will only need two main sub procedures. –Search procedure which will search for an entry in the phonebook by name. –NewEntry procedure which will enter a new name and number to the phonebook.  There will also be two navigational procedures –One to take the user from the welcome sheet to view all listings. –One to return them to the welcome sheet, or the phonebook menu.  In the Search procedure we will call a CreateArray procedure to put all names and numbers from the “Phone Data” sheet into two arrays which we will use to search.

30 30 Variables  Counting variables  Two array variables (one for the names and one for the numbers)  Two range variables (for the two columns of data in the phonebook table)  Two variables to capture the name and number for searching or adding a new entry Public i As Integer, n As Integer, PhoneName() As String, _ PhoneNumber() As Double, NewName As String, NewNumber As Double,_ NameStart As Range, NumStart As Range

31 31 Navigational Procedures  These procedures will be assigned to the “View All Listings” and “Return to PhoneBook Menu” buttons respectively. Sub ViewBook() Worksheets("Phone Data").Visible = True Worksheets("Phonebook Welcome").Visible = False End Sub ---------------------------------------------------------------------------- Sub ViewMenu() Worksheets("Phonebook Welcome").Visible = True Worksheets("Phone Data").Visible = False End Sub

32 32 Search  The first action is to ask the user for the name they want to search for in the phonebook. –We assign the NewName variable to our InputBox function and provide a default value.  Next we will call the CreateArray procedure to create an array of all current names, PhoneName, and numbers, PhoneNumber, in the phonebook. –This makes our search easier since now we can just use a For, Next loop to check if any of the array elements are equal to our NewName value.

33 33 Search (cont’d)  If a match is found, the corresponding element (i.e., the same index number) from the PhoneNumber array is assigned to the NewNumber variable and the result of the search is shown to the user.  If no match is found, we consider that the NewNumber variable was never changed from its default value of 0. –Therefore, using this check we can tell the user that no match was found.  We have used the Format function to display the NewNumber value as a standard 10-digit phone number.  This function performs the same actions as formatting a cell in Excel.  The notation "(###) ###-####" specifies the custom format we want.

34 34 Search (cont’d) Sub Search() NewName = InputBox("Please enter name you wish to search for “ & _ & “using the following format: Last, First:", "Name Search", "Smith, John") Call CreateArray NewNumber = 0 For i = 1 To n If PhoneName(i) = NewName Then NewNumber = PhoneNumber(i) MsgBox "The phone number for " & NewName & " is " & _ Format(NewNumber, "(###) ###-####") & "." End If Next i If NewNumber = 0 Then MsgBox "There was no phone book entry by that name." End If End Sub

35 35 CreateArray  Notice in our variable declarations, our two arrays, PhoneName and PhoneNumber, were defined as dynamic arrays.  Now we need to find the size of these arrays and use the ReDim statement.  To find the size of the arrays we can use our range variables and the End property to count the number of values currently in our phonebook table. –To count the number of values in this range, we use the Rows property and Count sub property.  We can then use a For, Next loop to enter each value in the table as an element in one of our arrays.

36 36 CreateArray (cont’d) Sub CreateArray() With NameStart n = Range(.Offset(1, 0),.End(xlDown)).Rows.Count End With ReDim PhoneName(n) ReDim PhoneNumber(n) For i = 1 To n PhoneName(i) = NameStart.Offset(i, 0) PhoneNumber(i) = NumStart.Offset(i, 0) Next i End Sub

37 37 NewEntry  In this procedure we begin by prompting the user for both a name and a number to add to the phonebook. –We assign Input Boxes to the NewName and NewNumber variables.  We ensure that some non-empty string is entered as a name using an If, Then statement with the condition: NewName = “”. –If this condition is true, then the sub should be exited and the user should be prompted to re-enter a name.  We also ensure that the phone number entered is 10-digits in length. –We do this using Len function. –The Len function takes any string expression or variable name as input and counts the number of characters or digits.

38 38 NewEntry (cont’d)  We then again call the CreateArray procedure. –We do this in order to search all names in the current list so as to avoid duplicate entries. –If the NewName value is found in the PhoneName array, the user is told that this entry already exists. –If no match is found, we can proceed with adding the new entry to our table; we do this using our range variables.  We now select our modified table and sort all of the values using the Sort method.  We also use the ScreenUpdating property of the Application object to ensure that the user does not see this background work on the “Phone Data” sheet.

39 39 NewEntry (cont’d) Sub NewEntry() Application.ScreenUpdating = False Worksheets("Phone Data").Activate NewName = InputBox("Please enter the new entry name using the “ & _ & “following format: Last, First", "New Name", "Smith, John") If NewName = "" Then MsgBox "Please enter a name." Exit Sub End If NewNumber = InputBox("Please enter the 10-digit phone number for " & _ NewName & " using the following format: 1234567890", _ "New Number", 1234567890) If Len(NewNumber) <> 10 Then MsgBox "Please enter a 10-digit number." Exit Sub End If

40 40 NewEntry (cont’d) Call CreateArray For i = 1 To n If PhoneName(i) = NewName Then MsgBox "There is already an entry for this person in the “ & _ & “phone book." Exit Sub End If Next i NameStart.Offset(n, 0).value = NewName NumStart.Offset(n, 0).value = NewNumber Range(NameStart, NumStart.Offset(n, 0)).Select Selection.Sort Key1:=NameStart, Order1:=xlAscending Worksheets("Phonebook Welcome").Activate Application.ScreenUpdating = True MsgBox NewName & " has been added to the phone book." End Sub

41 41 Application Conclusion  The application is now complete.  Assign the procedures to the respective buttons and check the functionality of the program.

42 42 Summary  Arrays store series of data that we can manipulate or refer to later.  To define an array, use the Dim, Private, or Public variable declarations. –For a one-dimensional array, we just need a single number to specify the size. –To define multi-dimensional arrays, we must specify the size of each dimension, separated by a comma.  To insert values into an array, use the entire array variable and the array function.  The default initial index value of arrays in VBA is 0. To change the initial index value of all arrays in our module to 1, type Option Base 1 at the top of the module.  If we are not sure what size an array should or will be, depending on the users or other dynamic programming reasons, we can define a dynamic array.  To set the size of a dynamic array at some later point in the code, use the ReDim statement. –The ReDim Preserve statement retains any previously assigned element values.  Use Format function to apply a custom format to an expression or variable value.

43 43 Additional Links  (place links here)


Download ppt "Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) 456-7890 University Name."

Similar presentations


Ads by Google