article

Using Collections in VB

Email
Submitted on: 1/7/2015 11:49:00 AM
By: Matthew Roberts (from psc cd)  
Level: Intermediate
User Rating: By 36 Users
Compatibility: VB 3.0, VB 4.0 (16-bit), VB 4.0 (32-bit), VB 5.0, VB 6.0, VB Script, ASP (Active Server Pages)
Views: 357
 
     Explains the basics of using collections in Visual Basic. These are a very powerful and often unused feature of VB.

This article has accompanying files
 
				



Using Collections



Using Collections

So you have heard of Collections and may have even used them a few times. An unassuming word…collections. It doesn’t inspire much excitement in most circles, yet there are very few single words that represent such a powerful element of programming as they do. This article will outline some of the general and specific uses of collections in Visual Basic and Access. After reading it, you will hopefully have a higher respect for this often overlooked aspect of VB.

Just what are collections anyway? Well, they are just what their name implies. They are a logical grouping of objects in Visual Basic. The Visual Basic object model consists of objects and collections of objects. For example, you have a "Forms" collection which contains all of the forms in the application. Each form also has an Objects collection which contains all of the objects that are contained in the form. On the Access side, there is a TableDefs collection which contains all of the tables in your database, and each of these TableDefs contains a Fields collection. As you may have guessed, the Fields collections contains all of the fields that exists in each table.

What does this mean to the average coder? Where is the payoff for all of this organization? You are about to find out. Using the Forms example above, consider this problem:

For some strange reason, your client wants you to create a function that will show all of the forms in the entire application at once. You could so something like this:

Function ShowForms

FrmSplash.Show

FrmMainMenu.Show

FrmSelectUser.Show

FrmOpenDocument.Show

…etc….etc….

End Function

This can be tedious if the application has 35 or so forms. And to make matters worse, they keep adding and removing forms, so you have to keep coming back and changing this function to keep from causing a compile error "Object required" every time one changes. What a pain. You could solve this entire problem by either finding a new job, talking some sense into your client (like THAT would work!) or by using this code:

Function ShowForms

Dim frmForm as Form

For each frmForm in Forms

FrmForm.Show

Next frmForm

End Function

Now the client can add, remove, and change the name of as many forms as he likes without effecting the operation of the application. By looping through (or "iterating") the collection, you have made you code immune to the whims of your client. Lets look at how this works by examining each statement.

Dim frmForm as Form

This statement creates an object variable that will hold each form object as we iterate through the Forms collection. It is basically a temporary storage space for a form object.

For each frmForm in Forms

If you haven’t yet started using the For Each … Next statement, you need to get with the program. It works just like the old Basic/VB For…Next, but it does it with objects instead of variables. This is the heart of working with collections.

FrmForm.Show

This magic little statement takes the place of all of those other .show statements in the prior example. With each pass through the For Each…Next loop, the object variable frmForm is reassigned to contain the current form object. So when you say "frmForm.Show", VB interprets it as frmSplash.Show, frmMainMenu.Show, or whatever form is currently being proccessed.

Next frmForm

Wraps up the loop. This will return execution back to the For Each… statement above it. Code execution will pass through this loop once for each form in the Forms collection.

Now that you understand the basic logic of iterating through collections, you can see how this could be put to practical use. To cascade all open forms on the screen, you could modify the code to this:

Function CascadeForms

Dim intTop As Integer

Dim intLeft As Integer

Dim frmForm as Form

For each frmForm in Forms

If frmForm.Visible = True Then

IntTop = intTop + 100

IntLeft = IntLeft + 100

FrmForm.Top = IntTop

FrmForm.Left = IntLeft

End if

Next frmForm

End Function

This code will place forms over each other in cascade style, starting at coordinates 100,100 and moving down and to the right in increments of 100. It took almost as many letters to explain it as it does to write it!

The thing to note in this example is that ALL of the forms’ properties and functions are available as you loop though the collection. For example, you could have changed the caption of each one or the border style of only certain ones.

OK…enough about forms. Where else can these really cool collections be used? How about within a form? This code will print a list of all objects on a form to the debug window:

Function ShowObjects

Dim objObject as Object

For each objObject in Me

Debug.Print objObject.Name

Next objObject

End Function

This will work whether you have one or 1000 objects on a form…although I wouldn’t recommend putting that many controls on a single form…but hey, it would work with it!

The thing to note in the above code (besides the obvious compactness of it) is the use of the Me keyword. This is important. Me translates in VB to "Whichever form this code is running in". It is used to reference the Objects collection for the current form. This means that you could copy this code from one form and paste it directly into another and it would work with NO code changes. Here is a more practical example of the objects collection:

You have a form with 25 text boxes on it and you want to automatically center them when the user resizes the form. You could write some pretty painful code to do this, or you could do this:

Private Sub Form_Resize()

Dim objObject as Object

For each objObject in Me

ObjObject.Left = (Me.Width / 2) - (objObject.Width / 2)

Next objObject

End sub

This code will center any objects, no matter what their widths. With a little imagination, you can probably see how this same concept could be used to resized objects in a form as well. In fact, for the curious, I have already posted a sample project with the code to do just that in it. You can take a look at it by clicking here.

I hope you have found this article helpful. If you would like to have me post a follow up showing more advanced techniques for using collections, please leave some helpful comments and maybe a rating at PlanetSourceCode.

Have Fun!

M@

PS: For information on using the Microsoft Jet Database collections, Click Here to view my second collections tutorial.

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come out every day, so no prevention program can catch 100% of them. For your own safety, please:
  1. Re-scan downloaded files using your personal virus checker before using it.
  2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
  3. Scan the source code with Minnow's Project Scanner

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com


Other 25 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

5/7/2017 3:37:52 PMDavid

download link is broken 404 error
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.