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



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

Crystal Reports. Overview. Contents. Advanced Reporting Techniques using Arrays

OpenOffice.org 3.2 BASIC Guide

Use the Visual Basic 6 APP object to polish your applications

Name = array(x,y,...,z) the indexing starts at zero, i.e. Name(0) = x. Programming Excel/VBA Part II (A.Fring)

PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015

Visual Basic 6 Error Handling

Many applications consist of one or more classes, each containing one or more methods. If you become part of a development team in industry, you may

Visual Basic Programming. An Introduction

Start Learning Joomla!

Use the ADO Control in your Visual Basic 6 projects

REDUCING YOUR MICROSOFT OUTLOOK MAILBOX SIZE

Moving from C++ to VBA

Exercise 1: Python Language Basics

How to Write a Marketing Plan: Identifying Your Market

Add an Audit Trail to your Access Database

Schema Classes. Polyhedra Ltd

Connecting to an Excel Workbook with ADO

Create Mailing Labels from an Electronic File

ZHAO-II instructions

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Mail Programming Topics

Microsoft Excel Tips & Tricks

Connect to an Oracle Database from Visual Basic 6 (Part 2)

Activation of your SeKA account

The Subnet Training Guide

Shopify and Brightpearl

VB.NET Programming Fundamentals

Introduction to Open Atrium s workflow

Double Entry Accounting Workbook. Erin Lawlor

Advice on Using Dada Mail

A Basic introduction to Microsoft Access

Essbase Calculations: A Visual Approach

1.2 Using the GPG Gen key Command

Data Integrator. Samples. Handbook. Pervasive Software, Inc B Riata Trace Parkway Austin, Texas USA

Introduction to Python

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

The C Programming Language course syllabus associate level

>print "hello" [a command in the Python programming language]

Tray Thompson: Welcome everyone. We now have our. webinar, our second webinar, which is Banking 101. I

Visual Basic - Modules and Procedures

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.

Action Steps for Setting Up a Successful Home Web Design Business

Hands-on Exercise 1: VBA Coding Basics

Introduction to Programming with Xojo

FEEG Applied Programming 5 - Tutorial Session

Contrast ratio what does it really mean? Introduction...1 High contrast vs. low contrast...2 Dynamic contrast ratio...4 Conclusion...

Crowdsourced Code Review in Programming Classes

EMC Publishing. Ontario Curriculum Computer and Information Science Grade 11

So with no further ado, welcome back to the podcast series, Robert. Glad to have you today.

Access Database Design

Square Roots and Other Radicals

Create an Access Database from within Visual Basic 6.

Applications Development

ADVANCED SCHOOL OF SYSTEMS AND DATA STUDIES (ASSDAS) PROGRAM: CTech in Computer Science

Fasthosts Internet Parallels Plesk 10 Manual

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

The HVAC Contractor's Guide to Facebook

BASIS International Ltd. - March DocOut - Interfacing Reports with the Barista Document Management System

USING WORDPERFECT'S MERGE TO CREATE MAILING LABELS FROM A QUATTRO PRO SPREADSHEET FILE Click on a Step to move to the next Step

ClientAce WPF Project Example

Instance Creation. Chapter

GUIDE TO PREPARING MASTERS THESIS/PUBLISHABLE PAPER PROPOSALS

JavaScript: Arrays Pearson Education, Inc. All rights reserved.

Computer Programming I

Drupal Drush Guide. Drupal.org

Introduction to Object-Oriented Programming

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Reboot, reset, erase, power off, restore - what's the difference?

Mastering Windows 8's backup/restore system Windows 8 has easily the most comprehensive backup-and-recovery system ever seen on a personal computer.

Access 2000 and Visual Basic 6

APPROACHES TO SOFTWARE TESTING PROGRAM VERIFICATION AND VALIDATION

Introducing VBA Message Boxes

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

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

IP Subnetting: Practical Subnet Design and Address Determination Example

Sophos Enterprise Console Auditing user guide. Product version: 5.2

Example of a Java program

Introduction to CloudScript

An Newsletter Using ASP Smart Mailer and Advanced HTML Editor

Consulting. Personal Attention, Expert Assistance

Creating a Network Graph with Gephi

Program to solve first and second degree equations

SQL Server Database Coding Standards and Guidelines

The PSAT contains math, critical reading, and writing questions similar to those on the SAT.

MySQL 5.0 Stored Procedures

Introduction to Securing Data in Transit

OmniPlan for Mac Reviewer s Guide

6.1. Example: A Tip Calculator 6-1

COOLTRADE PERFROMANCE TIPS By Regina Guinn. Here are some things that subscribers should be aware of when running an automated trading platform.

Introduction. What is RAID? The Array and RAID Controller Concept. Click here to print this article. Re-Printed From SLCentral

M-Files Gantt View. User Guide. App Version: Author: Joel Heinrich

TRANSITION FROM TEACHING VB6 TO VB.NET

Python Loops and String Manipulation

Introduction to the data.table package in R

Managing User Accounts and User Groups

1. To start Installation: To install the reporting tool, copy the entire contents of the zip file to a directory of your choice. Run the exe.

RIT Installation Instructions

Writing cleaner and more powerful SAS code using macros. Patrick Breheny

Visual Logic Instructions and Assignments

Transcription:

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 when looping through the elements of an Array. Using the LBound and Ubound functions can be a big advantage, but even better is to use the For Each statement. Let's create and initialize a Static Array Before I show you how to loop through the elements of an array, let's first declare an array and then load it with values that represent the letters 'A' through 'G'. Assigning values to an element of an array simply requires that we reference the element with a subscript value contained within parentheses. Here's the code to do that Dim strletters(6) As String strletters(0) = "A" strletters(1) = "B" strletters(2) = "C" strletters(3) = "D" strletters(4) = "E" strletters(5) = "F" strletters(6) = "G" For those of you not familiar with the syntax, the declaration Dim strletters(6) As String tells Visual Basic that we wish to allocate a String Array called strletters whose Upper Bound is 6 (I analogize this, in my teaching and writing, to the top floor of a high rise building) What is unstated here is the Lower Bound value, which by default is 0 (I analogize this to the lower floor of a high rise building.) You could also write the declaration in this way Dim strletters(0 to 6) As String to make the code more readable, but in practice, most programmers don't specify the lower bound (which can be any value at all provided it is less than the upper bound.) To summarize, what we have here is a one-dimensional array called http://www.johnsmiley.com/cis18.notfree/smiley019/smiley019.htm (1 of 9)3/28/2004 11:58:40 AM

strletters containing seven elements, with elements numbered from 0 to 6. Accessing individual items within the Array Accessing individual items within an Array is pretty easy---we just refer to the element by using its subscript value within parentheses. For instance, to display the value of the fourth element of our array (subscript number 3) in a message box, we execute this code MsgBox strletters(3) which results in the value for that element, the letter 'D' being displayed in a Message Box. Accessing all of the items within a Static Array One of the great benefits of an array is the speed and ease with which you access every one of its elements. Using what I call the Brute Force method, you can display each element of our Array on the form using this code Dim x As Integer For x = 0 To 6 Form1.Print strletters(x) Next x http://www.johnsmiley.com/cis18.notfree/smiley019/smiley019.htm (2 of 9)3/28/2004 11:58:40 AM

I call this the Brute Force method because it requires that you know the subscript value for the first value in the Array (usually, BUT NOT ALWAYS 0) and the last value in the Array. The programmer will know these values for a Static Array (an array declared with a definitive Upper Bound) but won't necessarily know these values for a Dynamic Array (one whose Upper Bound is determined at run time). Let's create and initialize a Dynamic Array For instance, you might use a Dynamic Array to store the values found in a disk file that is opened and read at run time, in which the number of records varies from one running of the program to the next. For instance, let's create a disk file called 'LETTERS'.TXT' once again containing the first seven letters of the alphabet http://www.johnsmiley.com/cis18.notfree/smiley019/smiley019.htm (3 of 9)3/28/2004 11:58:40 AM

Now let's modify the small program we've written to read the letters of the alphabet from this disk file. Knowing that we have seven 'records' in the file, we could write this code Dim strletters(6) As String Dim x As Integer Open "C:\LETTERS.TXT" For Input As #1 For x = 0 To 6 Input #1, strletters(x) Next Close #1 For x = 0 To 6 Form1.Print strletters(x) Next x with the result that each one of the letters from the file would be loaded into an Array element, and then displayed on the form. The problem arises when the number of records in the file doesn't match what the program is expecting. If we add another letter to the file and run the program, this code doesn't load the letter 'H' to the Array, and therefore fails to display it on our form http://www.johnsmiley.com/cis18.notfree/smiley019/smiley019.htm (4 of 9)3/28/2004 11:58:40 AM

And if the file contains one less record than we are expecting then when we run the program, it bombs with this error http://www.johnsmiley.com/cis18.notfree/smiley019/smiley019.htm (5 of 9)3/28/2004 11:58:40 AM

For more on why this happens, you should check out Chapter 13 of my best selling book, "Learn to Program with Visual Basic." This is where a Dynamic Array comes in handy---it can handle the variable number of records in a disk file in a snap. Here's the code to load the letters in our file to a Dynamic Array. Dim strletters() As String Dim x As Integer Open "C:\LETTERS.TXT" For Input As #1 Do While Not EOF(1) ReDim Preserve strletters(x) Input #1, strletters(x) x = x + 1 Loop Close #1 Notice the differences between a Static Array Declaration and a Dynamic Array Declaration. The Dynamic Array, instead of being declared with a number within its parentheses, is declared with an empty set of parentheses Dim strletters() As String The empty set of parentheses tells Visual Basic that the number of elements in the Array will be determined later---using a ReDim statement. In fact, we execute multiple ReDim statements within the body of the loop that we use to read the records in our file---each time we read another record, we increment http://www.johnsmiley.com/cis18.notfree/smiley019/smiley019.htm (6 of 9)3/28/2004 11:58:40 AM

the value of the Upper Bound of our Array with this statement ReDim Preserve strletters(x) "Preserve" tells Visual Basic to retain the current values in the Array--- otherwise, the values would be wiped out. Accessing all of the items within a Dynamic Array Since we don't know, at the time we write the program how many elements a Dynamic Array will contain, we can't use the 'Brute Force' method we used earlier. One way to deal with the variable nature of a Dynamic Array is to use the LBound and Ubound Visual Basic functions. LBound returns the Lower Bound of an Array, and Ubound returns the Upper Bound of an Array. Therefore, to display all of the values in an array on our form, we can execute this code For x = LBound(strLetters) To UBound(strLetters) Form1.Print strletters(x) Next x The beauty of this code is that no matter how many letters are in our file (or our Array), this code is 'smart enough' to handle it. We can take this code on step further by using the Visual Basic For Each statement to 'loop' through the elements of the Array. For those of you not familiar with it, the For Each statement, in conjunction with an Object variable, can be used to 'loop' through the elements of a Visual Basic http://www.johnsmiley.com/cis18.notfree/smiley019/smiley019.htm (7 of 9)3/28/2004 11:58:40 AM

Collection---but it can also be used to loop through the elements of an Array, like this Dim y As Variant For Each y In strletters Form1.Print y Next In this code, the variable y is an Object Variable (and it MUST be declared as a Variant). Y is used, by the For Each statement as a placeholder to the value of the element in the Array. Here's a final look at the code Dim strletters() As String Dim x As Integer Open "C:\LETTERS.TXT" For Input As #1 Do While Not EOF(1) ReDim Preserve strletters(x) Input #1, strletters(x) x = x + 1 Loop Close #1 Dim y As Variant For Each y In strletters Form1.Print y Next and for good measure, let's modify the contents of our file http://www.johnsmiley.com/cis18.notfree/smiley019/smiley019.htm (8 of 9)3/28/2004 11:58:40 AM

and run the program one more time to be sure that it works Summary I hope you've enjoyed this refresher on Arrays, and that you will find the use of the For Each statement a valuable technique. http://www.johnsmiley.com/cis18.notfree/smiley019/smiley019.htm (9 of 9)3/28/2004 11:58:40 AM