Anda di halaman 1dari 8

University of Southampton

Faculty of Mathematical Studies

MA604 Visual Basic for Application

Arrays, VBA File I/O And Data Structure Algorithms

Author..... Israel Vieira Date........ November 2002 Version.... 2.0

Contents

Page

1.0 Arrays............................................................................................................................................ 1 1.1 Declaring Arrays ....................................................................................................................... 1 2.0 VBA File Input and Output ........................................................................................................... 2 2.1 Basic File Functions................................................................................................................... 2 2.2 Using Excel Built-in Dialogs........................................................................................................ 3 3.0 Data Structure Algorithms ........................................................................................................... 4 3.1 Simple List................................................................................................................................ 4 4.0 Practical Exercise ......................................................................................................................... 6

I.T.Vieira

MA604 Visual Basic for Applications

25/11/2002

1.0

Arrays

A set of memory locations or data items in which each member is identified by a common identifier (index) together with one or more subscripts (according to the number of dimensions of the array), so that the set can be treated as a linear series. Arrays have both upper and lower bounds, and the elements of the array are contiguous within those bounds. All the elements in an array have the same data type. You can use the Option Base statement at module level to declare the default lower bound for array subscripts (see Introduction to VBA page 9 for detail). The upper bound within an array variable must not exceed the range of a Long data type (-2,147,483,648 to 2,147,483,647). 1.1 Declaring Arrays

In VBA there are two types of arrays; fixed-size arrays that always remain the same size, and dynamic arrays whose size can change at run-time. You declare a VBA array using the Dim statement (You can also declare arrays with the Public or Private statements to explicitly indicate the scope of the array). The following are examples of fixed arrays declared in VBA:
Dim MyIntArray(10) As Integer Dim MySngArray(3 to 5) As Single Dim MyMArray(1 to 5,1 to 5) As Double declares an array of (2-byte) integer values with 10/11 elements declares an array of single values with 3 elements (indexes 3-5) Declares a square array of double with 5 rows and 5 columns

Theoretically you can declare arrays with as many as thirty-two dimensions, but it would be hard to find a reason for doing such a thing. Normally your arrays will not have more than three or four dimensions. You declare a VBA dynamic array by omitting its dimensions in the declaration statement, for example:
Dim MyDynArray() As Long

You must then redimension the array with a ReDim statement before you use it. For example:
ReDim MyDynArray(10)

This will allocate 10 entries for array MyDynArray. Each time you execute the ReDim statement; all the values currently stored in the array are lost. VBA resets the values to the Empty value (for Variant arrays), to zero (for numeric arrays), to a zero-length string (for string arrays), or to Nothing (for arrays of objects). However, sometimes you may want to change the size of the array without losing the data in the array. You can do this by using ReDim with the Preserve keyword. For example:
ReDim Preserve MyDynArray(11) Enlarges the array by one element without losing the existing data

Only the upper bound of the last dimension in a multidimensional array can be changed when you use the Preserve keyword; if you change any of the other dimensions, or the lower bound of the last dimension, a run-time error occurs. 1.1.1 LBound and UBound Functions

You can use the LBound and UBound functions to determine the size of an existing array as following:
MsgBox LBound(MyDynArray) MsgBox LBound(MyMArray, 2) & & UBound(MyDynArray) & & UBound(MyMArray, 1) Should return 0/1 - 11 Should return 1 - 5

The lower bound value will depend upon the Option Base statement. 1.1.2 Looping Through a Array

You can efficiently process a multidimensional array by using nested For Loops. For example:
Private Sub InitialiseArray() Dim idxI As Integer, idxJ As Integer, MatrixA(1 To 10, 1 To 10) As Double For idxI = 1 To 10 For idxJ = 1 To 10 MatrixA(idxI, idxJ) = (idxI * Rnd) + idxJ Debug.Print "(" & idxI & "," & idxJ & ") = " & MatrixA(idxI, idxJ) Next idxJ Next idxI End Sub Arrays, VBA File I/O, and Data Structure Algorithms [Version 2.0] 1

I.T.Vieira

MA604 Visual Basic for Applications

25/11/2002

2.0

VBA File Input and Output

Visual Basic for Applications provides functions for performing file input/output (I/O). This lets your custom solutions create, edit and store large amounts of data. You can also access several datasets at the same time and share data with other applications. There are three types of file access in VBA: Sequential .....for reading and writing text files in continuous blocks Random ........used with files containing a series of fixed length records Binary ...........used with files with no general format, this requires that you have exact knowledge on how the data is stored in the file in order to retrieve any information

The following table shows the statements typically used when writing data to and reading data from files. Access Type Sequential Random Binary Writing Data Print #, Write # Put Put Reading Data Line Input #, Input # Get Get

See the Introduction to VBA handout, page 26 for more detail on VBA file I/O. 2.1 Basic File Functions

Before start working with the VBA file I/O, you should know some useful VBA function, which will enable you to manipulate the windows file system from VBA. Following are some VBA functions and procedure to help you to work around with file in general: File Size ................ to find out the size of a file, in bytes, use the FileLen(pathname) function. If the specified file is open when the FileLen function is called, the value returned represents the size of the file immediately before it was opened.
Private Sub FileSize() MsgBox FileLen("c:\autoexec.bat") End Sub

File Date/Time ..... to find out the the date and time when a file was created or last modified, use the FileDateTime(pathname) function.
Private Sub FileDT() MsgBox FileDateTime("c:\autoexec.bat") End Sub

File Exists............. use the Dir(pathname) function to check whether a file actually exists.
Public Function FileExists(FileName As String) As Boolean If Dir(FileName) = "" Then FileExists = False Else FileExists = True End If End Function

Deleting a File...... use the Kill( pathname) statement to delete a existing file. Kill supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files. An error occurs if you try to use Kill to delete an open file.
Kill "*.TXT" Delete all *.TXT files in current directory

Copying a File ...... to copy or rename an existing file, use the FileCopy source, destination statement. If you try to use the FileCopy statement on a currently open file, an error occurs. Following is a example on how to use the FileCopy statement:
FileCopy "C:\Demo.txt","C:\temp\Demo.txt" FileCopy "C:\Demo.txt","C:\Demo1.txt" Copy Rename

Note: The pathname, source, and destination arguments may include the drive, directory or folder, and the file name with extension.

Arrays, VBA File I/O, and Data Structure Algorithms [Version 2.0]

I.T.Vieira

MA604 Visual Basic for Applications

25/11/2002

2.2

Using Excel Built - in Dialogs

You have access to most of the built-in dialogs in Excel and the other applications in Office. You can use such dialogs to dynamically interact with the user. You can retrieve a filename from the user that you want to use later to open or save a file by using the GetOpenFilename or GetSaveAsFilename methods. Both methods displays their respective dialogs, but they don't open or save the file when the user confirms the dialog. The methods instead return the complete filename to the file, which the user wants to open, or save. 2.2.1 GetOpenFilename displays the standard Open dialog box and gets a file name from the user without actually opening any files. The GetOpenFilename syntax is shown below:
Application.GetOpenFilename(Filter, FilterIndex, Title, ButtonText, MultiSelect)

Filter FilterIndex

Title ButtonText MultiSelect

Optional Variant. A string specifying file filtering criteria. Optional Variant. Specifies the index numbers of the default file filtering criteria, from 1 to the number of filters specified in Filter. If this argument is omitted or greater than the number of filters present, the first file filter is used Optional Variant. Specifies the title of the dialog box, the default title is "Open." Optional Variant. Macintosh only (ignored in Windows) Optional Variant. True to allow multiple file names to be selected. False to allow only one file name to be selected. The default value is False

This method returns the selected file name or the name entered by the user. The returned name may include a path specification. If MultiSelect is True, the return value is an array of the selected file names (even if only one filename is selected). Returns False if the user cancels the dialog box. Example:
Public Sub TestSingleFileOpen() Dim FileToOpen As String FileToOpen = Application.GetOpenFilename("Text Files (*.txt),*.txt,Add-In Files (*.xla),*.xla", 2, "Open example") If FileToOpen = "False" Then MsgBox "No file has been selected to open" Else MsgBox "Open " & FileToOpen End If End Sub

2.2.2

GetSaveAsFilename displays the standard Save As dialog box and gets a file name from the user without actually saving any files. The GetSaveAsFilename syntax is shown below:
Application.GetSaveAsFilename(Filename, Filter, FilterIndex, Title, ButtonText)

Filename Filter FilterIndex Title ButtonText

Optional. Specifies the suggested file name Optional. A string specifying file filtering criteria. If omitted in Windows, this argument defaults to "All Files (*.*),*.*" Optional. Windows only (ignored on the Macintosh). Specifies the index number of the default file filtering criteria Optional. Specifies the title of the dialog box. If this argument is omitted, the default title Save. is used Optional Variant. Macintosh only (ignored in Windows)

This method returns the selected file name or the name entered by the user. The returned name may include a path specification. Returns False if the user cancels the dialog box. Following is an example on how to use the Excel save dialog:
Public Sub SaveOneFile() Dim FileToSave As String FileToSave = Application.GetSaveAsFilename("Untitled1.txt", "Text files, *.txt", 1, "Select your folder and filename") If FileToSave <> "False" Then MsgBox "Saving File to: " & FileToSave End If End Sub Arrays, VBA File I/O, and Data Structure Algorithms [Version 2.0] 3

I.T.Vieira

MA604 Visual Basic for Applications

25/11/2002

3.0

Data Structure Algorithms

An algorithm is a discrete set of steps that describe how information is manipulated such that the solution to the problem is realised. Data Structures are a logical basis for organising information in the computer for representation of data types and operations, subject to the language constraints. Examples of basic data structure are Arrays, Lists, Stacks, Queues, and Trees. However, this course will not cover data structure, only a single list and sorting algorithms are implemented for demonstration purpose. 3.1 Simple List

If you program needs a list that never changes, you can build it easily using an array. However, most of the time, programs use lists that grow and shrink over time. You could allocate an array big enough to handle the list to its largest, but that may not always work well. You may not know ahead of time how large the list will become. There may also be a small chance that the list will become huge. In that case, allocating a gigantic array would be a waste of memory most the time. Following we implement a simple list step by step. This example does not provide a user interface, however you can make the necessary changes and add one. To start the list, add a standard module, and declare the global variables, which will keep track of the data and other properties of the list:
Option Explicit Option Base 1 Private List() As Double Private ListItems As Long Private ListInitialised As Boolean 'Arrays lower bound starts from 1 'List of double 'The number of items in the list 'List initialisation status

The next step are straightforward, you need to implement the operation to control the list. By now you should be able to read and understand the following VBA code: Clears the list
Private Sub ClearList() ListItems = 0 ListInitialised = False Erase List End Sub

'Removes the array from memory

Add a new value to the list and initialise it if not yet initialised
Private Sub AddToList(addValue As Double) ListItems = ListItems + 1 If ListInitialised Then ReDim Preserve List(1 To ListItems) Else Initialise the list ReDim List(ListItems) ListInitialised = True Randomize Initialise the VBA number generator End If List(ListItems) = addValue End Sub

Returns a particular item from the list, if not out of the list bounds
Private Function GetItem(ByVal Position As Long) As Double If ListInitialised Then If Position < 1 Or Position > ListItems Then ' Out of bounds. Return Null. MsgBox "Out of the bounds" GetItem = 0 Else ' Return the item. GetItem = List(Position) End If Else MsgBox "List not initialised!" End If End Function

Arrays, VBA File I/O, and Data Structure Algorithms [Version 2.0]

I.T.Vieira

MA604 Visual Basic for Applications

25/11/2002

Remove the last item from the list


Private Sub RemoveLast() If ListInitialised Then ListItems = ListItems - 1 ReDim Preserve List(ListItems) End If End Sub

Prints out the list to a given file name.


Private Sub PrintList(inFileName As String) Dim lIdx As Long, oFile As Long oFile = FreeFile Open inFileName For Output As #oFile For lIdx = 1 To ListItems Write #oFile, lIdx; Write #oFile, List(lIdx) Next lIdx Close #oFile End Sub

Sort the list using the Selectionsort, a very simple sorting algorithm of O(N2) time.
Private Sub SortList() 'Selection sort algorithm Dim idxI As Integer Dim idxJ As Integer Dim BestValue As Double Dim PrevBest As Long For idxI = 1 To ListItems - 1 BestValue = List(idxI) PrevBest = idxI For idxJ = idxI + 1 To ListItems If List(idxJ) < BestValue Then BestValue = List(idxJ) PrevBest = idxJ End If Next idxJ List(PrevBest) = List(idxI) List(idxI) = BestValue Next idxI End Sub

Note: Sorting is a common task in computer applications, almost any data is more meaningful if you can sort it and display it in various ways. You should implement more efficient sorting algorithms such as Quicksort, Bubblesort, Mergesort, Countingsort, and so on. Different sorting algorithms behave differently for different data so no algorithm is best under all circumstances. You can use the Big O notation for analysing algorithm complexity. Now you can test your list by creating a valid sequence of events as following:
Public Sub TestList() Dim nitems As Long ClearList 'Clears the list For nitems = 1 To 100 'Adds 100 items to the list AddToList (1000 * Rnd) + 1 'Generates random number between 1 and 1000 Next nitems PrintList "C:\OriginalList.txt" 'Prints out the list For nitems = 1 To 5 'Removes the last five items MsgBox "Removing item " & ListItems & " = " & GetItem(ListItems) RemoveLast Next nitems SortList 'Sorts the list PrintList "C:\SortedList.txt" 'Prints out the list ClearList 'Clears the list End Sub

Note: To run the example above, put the cursor inside the TestList procedure (VBA IDE) and press F5 or use the menu Run Run Macro. Check the generated text files to see the algorithms result.
Arrays, VBA File I/O, and Data Structure Algorithms [Version 2.0] 5

I.T.Vieira

MA604 Visual Basic for Applications

25/11/2002

4.0

Practical Exercise

The following picture describes a scenario where a supermarket has three distribution centres to supply its 15 stores across the UK. The respective co-ordinates (location) for each centre and store are given.

4.1 4.2 4.3 4.4 4.5

Create an Excel worksheet similar to the one shown above (Centres, Stores, Summary and Chart). Write a procedure to find the nearest centre for each store, according to its location, summarise the number of stores to be served by each centre and the average travelled distance. Add a new button and the necessary code associated to the Even Click such that it generates a valid random location for each store when clicked. Write a procedure to save the current scenario to a text file (centres, stores). Write a procedure to load a saved scenario from a text file (centres, stores). Note: You should use the Excel built-in dialog for exercises: 4.4 and 4.5

Arrays, VBA File I/O, and Data Structure Algorithms [Version 2.0]

Anda mungkin juga menyukai