Solved

public array in class

Posted on 2013-06-30
6
281 Views
Last Modified: 2013-07-07
hey guys, i need a 3D array to store Category,Acronym,AcronymDefinition.

it's in my class

it says i can't make public arrays.

1) what's the best way to go about it? i could put it in the class and make accessor functions.
2) i decided not to use dictionary nor collection as they are only key and item (or am i wrong?)
0
Comment
Question by:developingprogrammer
  • 3
  • 3
6 Comments
 
LVL 24

Expert Comment

by:Bitsqueezer
Comment Utility
Hi,

the simplest method is to create an additional class consisting only of the Public declared variables you want to use (which also gives you the possibility to add any variable later).

Then you can fill either an array or a collection in your class using objects of this additional class. An array has the advantage that it is type safe (you can use IntelliSense) but difficult handling if you need to remove an item. A collection is easier in handling but you can't use IntelliSense. If you have a collection with the name "colValues" you could access the variables with "colValues(10).Category" for example, but also with a named index.

Cheers,

Christian
0
 

Author Comment

by:developingprogrammer
Comment Utility
hi Christian, thanks for your reply!!

hrmm i'm not too sure i understand what you mean by an additional class solving the problem. here's what i understand from your response.

create a data-class (this class just stores data) and then use the main class to store all the data in the data-class.

1) however --> problem is that i want to declare an array public and i cannot do that in a class. i want to declare the array public so that other classes or modules can use it as well. according to your way you're telling me to just declare it public in another class - but i can't even declare it public in any class at all.

2) solution --> i've declared the array private and created a set let property pair to access this array. is there a better way to do this?

3) Christian so are you saying that collections can has colValues(1,1,3), colValues(1,1,4), colValues(1,2,3), colValues(1,2,4) etc? that means collections can have 3 / more dimensions as well?

4) sorry what does "colValues(10).Category" do? the 10 i understand to be the record number 10 in the collection and the .Category is what i've defined as the key is it? i'm confused. if i have a 10, the 10 is already doing the job of the pointer and i don't need the Category as a pointer. sorry i don't understand this quite well, could you explain it to me again? i always though collections only have a key and a value --> thus the term key value pair right?

thanks Christian!! = ))
0
 
LVL 24

Accepted Solution

by:
Bitsqueezer earned 500 total points
Comment Utility
Hi,

maybe I misunderstood your question a little bit, didn't thought of your three dimensional array.

To make it clear: Yes, you're right, a collection can "only" have a key (or numeric index) and a value. The big difference between a collection and an array is that a collection only has the number of elements you added to it, an array always reserves the space for the size of dimensions you gave it.
This is the reason why I personally try to avoid arrays with more than 2 dimensions, as in most cases it is possible to do the same with a collection - but much more flexible. If you store simple variables into a collection then it is not so easy to handle as the values cannot be changed after adding it - you must remove it and add it again which always means you loose the order (so you cannot use the index to access it as it would change). But you can use a name for the value and that is your key to uniquely access it independent of the position in the collection.
But the good thing is that you can also add objects (and anything else, and also mixed) to a collection and in this case you don't need to remove and add again, you can change the values (the properties) of the object. Moreover you can add collections to collections so you can have an x-dimensional kind of "array" (but in opposite of an array you can mix the number of dimensions like for example in the structure of a file tree where you don't know how deep the file is nested in the tree). And you only need the space which is needed to store one element, not also the space calculated by multiplicating all dimensions of an array.

So indeed "colValues(1,2,3)" is of course not possible, but for example if you nest collections into each other you could access an element with "colValues(1)(2)(3)" (if the position remains the same all the time). As this is problematic if you add simple variables an object (built from a class module) can help instead.

Let's say you want to have a list of categories and in each category you want to have a list of AcronymDefinitions with the value Acronym.

You can of course define a three dimensional array, create a property to access it and everything is OK.

Here is my variant which (in my opinion) gives you a little bit more flexibility and less memory usage (and also a very good performance because you can use "For Each"):

First, you need the data class, that's simple, I called it "clsAcronym":

Option Compare Database
Option Explicit

Public Category As String
Public Acronym As String
Public AcronymDefinition As String

Open in new window


Next there must be a master class which handles the data, I called it "clsMaster":

Option Compare Database
Option Explicit

Public ColCategories As Collection


Private Sub Class_Initialize()
    Dim objAcronym As clsAcronym
    Dim ColAcronyms As Collection
    Dim i As Long, k As Long
    
    Set ColCategories = New Collection
    
    For k = 1 To 30
        Set ColAcronyms = New Collection
        For i = 1 To 100
            Set objAcronym = New clsAcronym
            With objAcronym
                .Category = "A" & k
                .AcronymDefinition = "ADef" & i
                .Acronym = "Acr" & i
                ColAcronyms.Add objAcronym, .AcronymDefinition
            End With
        Next
        ColCategories.Add ColAcronyms, objAcronym.Category
    Next
    
End Sub

Private Sub Class_Terminate()
    Set ColCategories = Nothing
End Sub

Open in new window


It offers the collection "ColCategories" as public property (of course very simple version, a more comfortable way would be to use a property where you can initialize the collection again if it is lost and so on).

Then the Initialize sub fills a collection with 100 AcronymDefinition/Acronym value pairs using the data class. The collection will then be added into the collection ColCategories. So now you have the same as the three dimensional array: 30 categories with 100 value pairs. The difference is that you do not need to add empty objects, you can simply add them when you really need them (I only used the for loop to have some contents in the values, in real world you would offer an "add" method in the master class to add a value pair with a certain category).

Here's a simple test sub which can be used in a standard module to see the result and how to use the classes:

Option Compare Database
Option Explicit

Public objMaster As clsMaster

Public Sub TestClasses()
    Dim objAcronym As clsAcronym
    Dim ColCategories As Collection
    Set objMaster = New clsMaster
    
    For Each ColCategories In objMaster.ColCategories
        For Each objAcronym In ColCategories
            With objAcronym
                Debug.Print .Category, .AcronymDefinition, .Acronym
            End With
        Next
    Next
End Sub

Open in new window


You see, you can access the values easily using for each loops (which is of course also possible with arrays) but you can also use this to access a certain element:

Debug.Print objMaster.ColCategories("A1")("ADef50").Acronym

Open in new window


Or with indices (as long as you do not change the order of elements in the collections):

Debug.Print objMaster.ColCategories(1)(50).Acronym

Open in new window


I also added the variables for AcronymDefinition and Category to the clsAcronym because a disadvantage of the VBA collection is that you cannot read out the key value which you have used to store an element into a collection. With this method you can also access the key values if you do not know it.

I love collections and data classes because they allow to create active elements instead of dead variables where you can only store a simple value. With a data class you can always add for example an initialize sub to prefill the contained properties with a default value, you can create properties which only allows to fill in values in a defined range, you can defined read only variables or add methods to the class to do something with the data and so on.

As a data class can also contain a collection you can also create a structure of subobjects which contains the same object type again. This allows you to fill a collection with such objects and as they also contain a collection which is filled with the same objects which also have a collection which is filled...you get the idea. In the end you get a complete tree in one collection with any kind of data which can be filled and read out with recursive programming easily.

Cheers,

Christian
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:developingprogrammer
Comment Utility
whao Christian you've utter convinced me to use collections! reading through everything you said, it makes 100% sense!!

i also read this article by matthewspatrick on collections vs dictionaries
http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/A_3391-Using-the-Dictionary-Class-in-VBA.html

i will be implementing everything you said in to my programme once i'm done with the development of the other things. really super fantastic = )

if you've got any advice on collections vs dictionaries or any gotchas let me know, definitely will follow your stuff exactly!! just like how adding autonumber primary keys saved my life!! haha = ))
0
 

Author Closing Comment

by:developingprogrammer
Comment Utility
nesting collections in collections / dictionaries in dictionaries is the crux of everything to make a dictionary / collection 3 dimensional - and that's the clincher for me!! = )) thanks Christian!!
0
 
LVL 24

Expert Comment

by:Bitsqueezer
Comment Utility
Hi,

Dictionaries are the better collection, of course, because they allow some more things which can't be done with collections. The only thing I personally don't like is that you need to use an external library to use them (with low risk, as VBScript is part of all Windows installations nowadays).

I wrote my own dictionary class in VBA so I'm not only independent of VBScript, I can also extend this kind of dictionary like I want.

If you're interested, I've attached this here. Please keep in mind that this class uses a special trick to make it work like real collections: The "Attribute" rows which can only be edited if the class is exported as text file (see the "hidden rows" remarks in the code).

Cheers,

Christian
clsCCDictionary.zip
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In this article we discuss how to recover the missing Outlook 2011 for Mac data like Emails and Contacts manually.
Describes a method of obtaining an object variable to an already running instance of Microsoft Access so that it can be controlled via automation.
With Microsoft Access, learn how to start a database in different ways and produce different start-up actions allowing you to use a single database to perform multiple tasks. Specify a start-up form through options: Specify an Autoexec macro: Us…
The viewer will learn how to simulate a series of sales calls dependent on a single skill level and learn how to simulate a series of sales calls dependent on two skill levels. Simulating Independent Sales Calls: Enter .75 into cell C2 – “skill leve…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now