64

Vba ( Visual Basic for Application ) Arrays

  • Upload
    yuri56

  • View
    715

  • Download
    12

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Vba ( Visual Basic for Application ) Arrays
Page 2: Vba ( Visual Basic for Application ) Arrays

Developers and Designations

Macariao C. Lequin Resident Programmer

Chuck Loven Ballacer Designer

Amanda Arevalo Documenter

Bernadette Francisco & Gregory Dula Presenters

John Keno Systems Analyst

Page 3: Vba ( Visual Basic for Application ) Arrays

Variables refer to storage locations and associated symbolic names that contain some known or unknown quantities, information, or values. A variable's name represents information the variable contains.

Introduction

They are called variables because the represented information can change but the operations on the variable remain the same.

Variables are like boxes where information can be maintained and referenced. On the outside of the box is a name. When referring to the box, we use the name of the box, not the data stored in the box.

Page 4: Vba ( Visual Basic for Application ) Arrays

Introduction (con’t)

When we work with a single item, we only need to use one variable. However, if we are to work with a number of items, it would be too tasking to use many variables.

For example, what if you need to enter 5,000 names. Will you use 5,000 different variables . . . ?

You might run out of variables !!!

Page 5: Vba ( Visual Basic for Application ) Arrays

Introduction (con’t)

If we have a list of items which are of similar type to deal with, we use an array of variables instead of using a variable for each item.

Arrays make it possible for you to refer to a series of variables by the same name and to use a number (an index) to tell them apart.

This helps you create smaller and more simple code in many situations, because you can set up loops that deal efficiently with any number of cases by using the index number.

Page 6: Vba ( Visual Basic for Application ) Arrays

Introduction (con’t)

Arrays are useful when you must store a number of values of the same type, but you do not know how many, or you do not want to create individual variables to store them all.

For example, suppose you must store a numeric value for every day of the year. You could declare 365 separate numeric variables, but that would be a lot of work.

Instead, you can create an array to store all the data in one variable.

The array itself is a single variable with multiple elements and each element can contain one piece of data.

Page 7: Vba ( Visual Basic for Application ) Arrays

Current State of Technology

Arrays are useful in any programming language when you need to store a large number of values.

A student record for teachers is what we intend to create.

Some teachers still record their students’ data manually.

With our program, we will be able to ease the burden of teachers who record their students’ data manually .

Modern, computerized recording of students’ data is faster, more convenient and would minimize errors, if not totally eradicate them.

Page 8: Vba ( Visual Basic for Application ) Arrays

To understand the nature of arrays

To appreciate the use of arrays in programming

To learn how to manipulate the elements of arrays

To be able to create a student record program using arrays arrays in Visual Basic

Our Objectives

To know the importance of arrays in program development

To be able to construct a program using arrays

Page 9: Vba ( Visual Basic for Application ) Arrays

What are Arrays ?

An array is a group of variables with the same data type and name.

Arrays allow you to gather and manipulate different pieces of information of the same type.

We differentiate each item in the array by using subscripts, the index value of each item, for example name (1), name (2), name (3) ... etc.  

Arrays can be of any data type.

The data type for an array specifies the data type for each element of the array.

Page 10: Vba ( Visual Basic for Application ) Arrays

What is Arrays ? (con’t)

Data TypesData Types

Every array has a data type, but it is not the same as the data type of its elements.

For example, the an array can be of type Integer(), while each of its elements is of type Integer. The notation Integer() means an array of Integer elements.

Page 11: Vba ( Visual Basic for Application ) Arrays

What are Arrays ? (con’t)

An aray that uses one index and is said to be one-dimensional.

An array that uses more than one index or subscript is calledmultidimensional.

Another kind of array is one which holds other arrays as elements. This is known as an array of arrays or a jagged array.

A jagged array can be either one-dimensional or multidimensional, and so can its elements.

Array Array DimensionsDimensions

Page 12: Vba ( Visual Basic for Application ) Arrays

Importance of Arrays

Arrays play a very important role in almost all programming languages. It provides a very powerful feature which can be used to build a complex type of data structure like the implementation of stacks and queues.

Arrays allow us to simplify our processing. We can use arrays to help read and analyze repetitive data with a minimum of coding.

An array and a loop can make the program smaller.

Arrays enbale the implementation of mathematical vectors, matrices, and other rectangilar tables. Many databases, small and large, consist of or include one-dimensional arrays whose elements are records.  

Page 13: Vba ( Visual Basic for Application ) Arrays

TRIVIA

The first digital computers used machine-language programming to set up and access array structures for data tables, vector and matrix computations, and for many other purposes.

Atanasoff-Berry computer (ABC) was the first electronic digital computer.I t was built by Vincent Atanasoff and Clifford Berry from Iowa State University between 1937-1942.

Page 14: Vba ( Visual Basic for Application ) Arrays

TRIVIA (con’t)

Merge sort was the first array-sorting program written by John Von Neumann in 1945 during the building of the first stored program computer.

Small-Scale Experimental Machine (SSEM), popularly called “Baby”, was the world's first stored-program electronic digital computer that ran its first program on June 21 1948.

Page 15: Vba ( Visual Basic for Application ) Arrays

TRIVIA (con’t)

Array indexing was originally done by self-modifying code, and later using index registers and direct addressing.

Some mainframes designed in the 1960s, such as the Burroughs B5000 and its successors, had special instructions for array indexing that included index-bounds checking.

Page 16: Vba ( Visual Basic for Application ) Arrays

TRIVIA (con’t)

Assembly languages generally have no special support for arrays, other than what the machine itself provides.

Because of the importance of array structures for efficient computation, earliest high-level programming languages, including FORTRAN (1957), COBOL (1960), ALGOL60 (1960), and C (1972), provided support for multi-dimensional arrays.

In C++  (1983), class templates exist for multi-dimensional arrays whose dimension is fixed at runtime as well as for runtime-flexible arrays.

Page 17: Vba ( Visual Basic for Application ) Arrays

First element of an array has zero index.

All the data items in array are always stored in consecutive memory locations.

Arrays are always store under a common heading or a variable name

Important Points

An array either be an integer, character, or floating point data item but initialized only on declaration time not afterwards.

An array can always be read or write through loops

Page 18: Vba ( Visual Basic for Application ) Arrays

Types of Arrays

There are many different types of arrays in Visual Basic for Application. Each type of array has three fundamental attributes, determined at compile time by how the array is declared.

Element Data Type

Fixed or Dynamic Length

Numer of Dimensions

Fundamental Attributes

Page 19: Vba ( Visual Basic for Application ) Arrays

Type of Arrays - Element Data Type

Arrays have a data type that restricts what can go in the elements of the array.

The declared data type of an array is more restrictive that for a variable

Only arrays declared with exactly the same data type can be assigned to each other.

Page 20: Vba ( Visual Basic for Application ) Arrays

Type of Arrays – Number of Dimensions

Most arrays have only one dimension, but in VBA arrays can have up to 60 dimensions.

Additional dimensions are added to an array by declaring multiple sets of bounds separated by commas

Page 21: Vba ( Visual Basic for Application ) Arrays

Type of Arrays – Fixed or Dynamic

A fixed-size array is an array whose number of elements is fixed.

It is like a CD rack that has a fixed number of slots where you can slide CDs into. You can only place as many CDs as there are slots that will hold it.

Use this if you know the exact number of elements that you have.

Page 22: Vba ( Visual Basic for Application ) Arrays

Type of Arrays – Fixed or Dynamic (con’t)

A dynamic array is an array whose number of elements varies.

It allows elements to be added or removed from the array.

Use this if you do not know the number of elements the array will have.

Dynamic arrays can have more than one dimension.

Multidimensional dynamic arrays are created by specifying multiple dimension bounds.

Page 23: Vba ( Visual Basic for Application ) Arrays

Types of Arrays (con’t)

Page 24: Vba ( Visual Basic for Application ) Arrays

Creating Arrays

We use the  Dim statement to declare an array just as the way we declare a single variable.

Dim arrayName(index) as dataType

Number of elements in the array

Identifies the element to process

Name of the array Type of data each element of the array contains

Page 25: Vba ( Visual Basic for Application ) Arrays

Creating Arrays (con’t)

This example creates an array named “Student” with five (5) elements. Each element is of type String.

Dim Student(5) as StringDim Student(5) as String

arrayName

index

dataType

Student(1) Student(2) Student(3) Student(4) Student(5)

Page 26: Vba ( Visual Basic for Application ) Arrays

Creating Arrays (con’t)

Another way of declaring an array is to specify the first index and the last index of the array

Dim arrayName(first index to last index) as dataType

Number of elements in the array as specified by the first index up to the last index

Name of the array Type of data each element of the array contains

Page 27: Vba ( Visual Basic for Application ) Arrays

Creating Arrays (con’t)

The previous example was changed to indicate the first index and the last index. This also creates an array named “Student” with five (5) elements, each is of type String.

Dim Student( 1 to 5) as StringDim Student( 1 to 5) as String

arrayName

First indexdataType

Student(1) Student(2) Student(3) Student(4) Student(5)

Last index

Page 28: Vba ( Visual Basic for Application ) Arrays

Creating Arrays (con’t)

You can also declare more than one array in a single line by separating each array with a comma ( , ). Below is an example :

Second array named “StudentID” with 3 elements, each of type string

First array named “Student” with 3 elements, each of type string

Third array named “StudentGrade” with 3 elements, each of type Single (single precision floating point)

Dim Student(3) As String, StudentID(3) As String, StudentGrade(3) As Single

Dim Student(3) As String, StudentID(3) As String, StudentGrade(3) As Single

Page 29: Vba ( Visual Basic for Application ) Arrays

Multidimensional arrays can be thought of as arrays-of-arrays.

They are often needed whenwe are dealing with more complex database, especially those that handle large amount of data.

Data are usually organized and arranged in table form, this is where multidimensional arrays come into play.

Creating Arrays (con’t)

Page 30: Vba ( Visual Basic for Application ) Arrays

 Two dimensional array can be represented by a table that contains rows and columns, where one index represents the rows and the other index represent the columns.

Creating Arrays (con’t)

1st dimension

2nd dimension

Page 31: Vba ( Visual Basic for Application ) Arrays

Creating Arrays (con’t)

The format to declare a 2-dimensional array is shown below : 

Dim arrayName (num1, num2) as dataType

the suffix of the first dimension of the last element 

Name of the array

Type of data each element of the array contains

the suffix of the second dimension of the last element 

Page 32: Vba ( Visual Basic for Application ) Arrays

The suffixes of the element in the array will start with (0, 0) unless you set the Option Base to 1.

In the case when the Option Base is set to 1, then the suffixes of the element in the array will start with (1, 1).

Creating Arrays (con’t)

Dim Score (3,3) as Integer

Dim Score (3,3) as Integer

the suffix of the first dimension of the last element 

Name of the array Type of data

each element of the array contains

the suffix of the second dimension of the last element 

Page 33: Vba ( Visual Basic for Application ) Arrays

Creating Arrays (con’t)

This example will create a two dimension array consisting of 16 elements.

These elements can be organized in a table form as shown in the table below:

Page 34: Vba ( Visual Basic for Application ) Arrays

Creating Arrays (con’t)

With reference to the previous example, if you set the option base to 1, then there will be only 9 elements, that is from Score(1,1) to Score(3,3).

If you want the first element to start with suffixes (1,1) you can also use the following format of declaration:

Dim Score( 1 to 3, 1 to 3) as IntegerDim Score( 1 to 3, 1 to 3) as Integer

the suffix of the first dimension of the last element 

Name of the array Type of data

each element of the array contains

the suffix of the second dimension of the last element 

Page 35: Vba ( Visual Basic for Application ) Arrays

Dynamic Arrays

The length of an array can be fixed at declaration by explicitly setting bounds, or can be dynamic if no bounds are specified.

If an array has explicit (fixed) bounds it can be used right away, but dynamic arrays must be resized at least once before they can be used.

Dynamic arrays are resized using the Redim statement.

If the Preserve keyword is supplied, any existing elements already in the array being resized will remain intact.

If it is omitted all elements will be erased.

Page 36: Vba ( Visual Basic for Application ) Arrays

Dynamic Arrays (con’t)

To resize the array, you provide a value for the upper bound, and optionally, for the lower bound.

The upper and lower bound of an array refer to the beginning and ending indexes for the array.

You must specify the upper bound for the array when you resize it.

The lower bound is optional, but it is a good idea to include it, so that you know what the lower bound of the array is.

Page 37: Vba ( Visual Basic for Application ) Arrays

Dynamic Arrays (con’t)

The Redim keyword syntax array is shown below : 

ReDim [Preserve] ArrayName(Subscript) As DataType

ReDim - keyword that denotes we are redimensioning an array.

Preserve - optional keyword that is used to retain all existing elements' values. Without it all elements will return to their default values.

ArrayName - the name of the array.

Subscript  - the dimensions of the array.

DataType - any valid data type. The data type cannot be changed from its initial declaration when using the ReDim keyword, unless it was initially declared as a Variant

Page 38: Vba ( Visual Basic for Application ) Arrays

Dynamic Arrays (con’t)

Resizing an array with the Preserve keyword can be slow, so you want to do it as infrequently as possible.

A good way to minimize use of the Preserve keyword in your code is to estimate the amount of data you require to store and size the array accordingly.

If an error occurs because you have not made the array large enough, you can resize it within the error handler as many times as necessary.

When you're through working with the array, if it is larger than you require, you can resize it to make it just large enough to contain the data it currently has.

Page 39: Vba ( Visual Basic for Application ) Arrays

Dynamic Arrays (con’t)

Dim Grades( ) As Integer

ReDim Grades(0 to 99)

ReDim Preserve Grades(0 to 599)

Dim Grades( ) As Integer

ReDim Grades(0 to 99)

ReDim Preserve Grades(0 to 599)

Declares the array Grades as Dynamic

Resizes the array Grades to contain 100 elements

Resizes the array Grades to contain 600 elements at the same time retaining the original values of the elements Grades(0) to Grades(99).

Page 40: Vba ( Visual Basic for Application ) Arrays

Erasing Arrays

You should always erase your array when you are done using it, especially if you are using dynamic arrays.

To erase an array, we use the Erase statement as in :

Erase ArrayName

Page 41: Vba ( Visual Basic for Application ) Arrays

Erasing Arrays (con’t)

Dim strFriends(0 to 2) As String

strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Erin"

Erase strFriends)

Dim strFriends(0 to 2) As String

strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Erin"

Erase strFriends)

Declares the array strFriends with 3 elements as String type.

Assigns values to the 3 elements of the array

Erases the array

Page 42: Vba ( Visual Basic for Application ) Arrays

Retrieving Contents of Arrays

After building an array, we can now retrieve its contents. Below is an example of an array of friends’ names that was created :

Dim strFriends(0 to 6) As String

strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Sam" strFriends(3) = "Jenna" strFriends(4) = "Erin" strFriends(5) = "Carolyn" strFriends(6) = "Kate"

Dim strFriends(0 to 6) As String

strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Sam" strFriends(3) = "Jenna" strFriends(4) = "Erin" strFriends(5) = "Carolyn" strFriends(6) = "Kate"

Page 43: Vba ( Visual Basic for Application ) Arrays

Retrieving Contents of Arrays (con’t)

We want to display these names in successive message boxes, so we construct a loop, using the For . . .Next statement

Dim strFriends(0 to 6) As String, lngPosition as Long

strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Sam" strFriends(3) = "Jenna" strFriends(4) = "Erin" strFriends(5) = "Carolyn" strFriends(6) = "Kate"

For lngPosition = LBound(strFriends) To UBound(strFriends)

MsgBox strFriends(lngPosition)

Next lngPositionlngPositionlngPosition

Dim strFriends(0 to 6) As String, lngPosition as Long

strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Sam" strFriends(3) = "Jenna" strFriends(4) = "Erin" strFriends(5) = "Carolyn" strFriends(6) = "Kate"

For lngPosition = LBound(strFriends) To UBound(strFriends)

MsgBox strFriends(lngPosition)

Next lngPositionlngPositionlngPosition

Page 44: Vba ( Visual Basic for Application ) Arrays

Retrieving Contents of Arrays (con’t)

There are two new functions used in yhis example, Lbound and Ubound. These are used to determine the lower and upper bounds of an array.

Since strFriends has a lower bound of 0 and an upper bound of 6, these functions allow you to to iterate through an array with a dynamic size, without having to keep track of the array's size yourself.

With each iteration of the loop, lngPosition will count up from 0 to 6.

By accessing the array as strFriends(lngPosition) we are greatly reducing the amount of code you have to write.

Page 45: Vba ( Visual Basic for Application ) Arrays

Split and Join

The Split function allows us to convert a character string into an array.

variable = "IF/VLOOKUP/SUM/COUNT/ISNUMBER/MID"variable = "IF/VLOOKUP/SUM/COUNT/ISNUMBER/MID"

Use the Split function and define the separator :

en = Split(variable, "/")

en = Split(variable, "/")

Page 46: Vba ( Visual Basic for Application ) Arrays

Split and Join (con’t)

The array en will return the following values :MsgBox en(0) '=> returns : IFMsgBox en(1) '=> returns : VLOOKUPMsgBox en(2) '=> returns : SUMMsgBox en(3) '=> returns : COUNTMsgBox en(4) '=> returns : ISNUMBERMsgBox en(5) '=> returns : MID

MsgBox en(0) '=> returns : IFMsgBox en(1) '=> returns : VLOOKUPMsgBox en(2) '=> returns : SUMMsgBox en(3) '=> returns : COUNTMsgBox en(4) '=> returns : ISNUMBERMsgBox en(5) '=> returns : MID

The following 3 arrays will also return the same values :

en = Array("IF", "VLOOKUP", "SUM", "COUNT", "ISNUMBER", "MID")en = Split("IF,VLOOKUP,SUM,COUNT,ISNUMBER,MID", ",")en = Split("IF VLOOKUP SUM COUNT ISNUMBER MID", " ")

en = Array("IF", "VLOOKUP", "SUM", "COUNT", "ISNUMBER", "MID")en = Split("IF,VLOOKUP,SUM,COUNT,ISNUMBER,MID", ",")en = Split("IF VLOOKUP SUM COUNT ISNUMBER MID", " ")

Page 47: Vba ( Visual Basic for Application ) Arrays

Split and Join (con’t)

MsgBox Split("IF,VLOOKUP,SUM,COUNT,ISNUMBER,MID", ",")(2) '=> returns : SUMMsgBox Split("IF,VLOOKUP,SUM,COUNT,ISNUMBER,MID", ",")(2) '=> returns : SUM

The following example returns the 3rd value in the string :

Page 48: Vba ( Visual Basic for Application ) Arrays

Split and Join (con’t)

The opposite of the Split function is Join.

This function assembles the values of an array into a string.MsgBox Join(Array(1, 2, 3, 4, 5), "") '=> returns :

12345MsgBox Join(Array(1, 2, 3, 4, 5), "") '=> returns :

12345

Page 49: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA

Private Sub CommandButton1_Click( )

Dim StudentName(1 to 5) As StringFor i = 1 To 5StudentName(i) = InputBox("Enter student

Name")Cells(i, 1) = StudentName(i)Next

End Sub

Private Sub CommandButton1_Click( )

Dim StudentName(1 to 5) As StringFor i = 1 To 5StudentName(i) = InputBox("Enter student

Name")Cells(i, 1) = StudentName(i)Next

End Sub

Page 50: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA (con’t)

In this example, we define an array StudentName of five strings using the Dim keyword.

An InputBox is included to accept input from the user.

A For ...Next loop is placed to accept the input five times and display the five names from cell A1 to cell E1.

When we run the program, an input box will appear five times, allowing the user to enter five names. The sample input box is shown on the next slide.

Page 51: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA (con’t)

The five names will be displayed in the spreadsheet as shown on the next slide.         

Page 52: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA (con’t)

Page 53: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA (con’t)

Private Sub CommandButton1_Click( )

Dim StudentName(3) As String, StudentID(3) As String, StudentMark(3) As Single

For i = 1 To 3StudentName(i) = InputBox("Enter

student Name")StudentID(i) = InputBox("Enter student

ID")StudentMark(i) = InputBox("Enter student

Mark")Cells(i, 1) = StudentName(i)Cells(i, 2) = StudentID(i)Cells(i, 3) = StudentMark(i)

Next

End Sub

Private Sub CommandButton1_Click( )

Dim StudentName(3) As String, StudentID(3) As String, StudentMark(3) As Single

For i = 1 To 3StudentName(i) = InputBox("Enter

student Name")StudentID(i) = InputBox("Enter student

ID")StudentMark(i) = InputBox("Enter student

Mark")Cells(i, 1) = StudentName(i)Cells(i, 2) = StudentID(i)Cells(i, 3) = StudentMark(i)

Next

End Sub

Page 54: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA (con’t)

This example declares three arrays in a single line.

An InputBox and a For …Next loop are again included to accept input from the user

A For ...Next loop is placed to accept the input three times and display the three names, ID number, and mark from cell A1 to cell C3.

When we run the program, three input boxes will appear consecutively to allow the user to enter the student name, student ID and student mark.

The process will repeat three times until three student names, student IDs and student marks have been entered.

Page 55: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA (con’t)

The sample input boxes and the output are shown below and on the succeeding slides.

Page 56: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA (con’t)

Page 57: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA (con’t)

Page 58: Vba ( Visual Basic for Application ) Arrays

Sample Arrays in Excel VBA (con’t)

Page 59: Vba ( Visual Basic for Application ) Arrays

The Environment

OK Button – used to go to the Username and Password screen

EXIT Button – used to exit the program

Page 60: Vba ( Visual Basic for Application ) Arrays

The Environment (con’t)

Text Box 1 – used to enter User Name

Text Box 2 – used to enter user’s password

OK Button – used to accept user’s name and password and go to the Main Menu

EXIT Button – used to exit the program

Page 61: Vba ( Visual Basic for Application ) Arrays

The Environment (con’t)

Label – indicates the type of array

Record Button – enter the Student Record screen

EXIT Button – used to exit the program

Page 62: Vba ( Visual Basic for Application ) Arrays

The Environment (con’t)

Dialog Box – used to enter the student’s name, id, quiz1, quiz 2, and final grade

OK Button – used to display the next dialog boxEXIT Button – exit the program

ERASE Button – used to delete or erase the record in EXCEL one by one

Page 63: Vba ( Visual Basic for Application ) Arrays

Conclusion

We therefore conclude that the Student Record System :

Will introduce to the user a more systematic way of handling students’ records

Will help teachers in doing their recording of students’ information and ease their burden

Will support teachers in their job by paving the way for a more convenient and efficient (less paper work) method of recording all students’ data.

Page 64: Vba ( Visual Basic for Application ) Arrays