Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    Visual Basic




Array Vs. Collection


Can anyone give some overview of the difference between array and Collectionin terms of performance.... thanks :>




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Collection/Array Of Classes VS Array Of UDT
everywhere I read everyone tells me that defining, for example, a particle system using a collection of classes (where each class is one particle with properties) is much slower than using an array of UDT (user defined type) where each element is a particle.

how come? isn't it almost the same in memory? whats making it more slow? is there anyway to improve the collection/classes way or should I NEVER use this way?

i would really like to know

Collection Vs. Array Vs. ???
I need to hold 1000's of objects in memory which I need to access by an ID Key. What's the best way?

I can either create a Class with the 8 properties and add it to a collection with the unique ID for easy reference. OR I can make a type with 8 items and continually ReDim Preserve an array and add to the last element. However, with an array, I can't access an element with an ID, right?

So what's my best option? I'm thinking Collections are my only option because of the needed Key ID. But don't arrays take up less memory? Although ReDim Preserve each time doesn't seem very effecient.

Or is there a third option I'm missing? Thanks for any input you can give!

Array Vs. Collection
Hello, just a general question: What is the difference between an array and a collection and when and how should each be used? Thanks!

To err is human, to really foul things up requires a computer. [img]images/icons/wink.gif[/img]

Help With Array Or Collection
Good morning all. I am in need of some help. I have been working on a macro in SolidWorks using API in SolidWorks and VBA. I have the program running and doing partially what it needs to do, but I am looking for some help on arrays or collections. The program opens an assembly and displays all parts contained, one by one. I need to record these part names for use later on in the program. I am fairly new to VB and VBA so I don't really understand what I need to do. Do I use an array or do I use a collection? Could you post an example of what I need to do? Any help would be greatly appreciated.

Here is my code so far:


VB Code:
Sub TraverseComponent(swComp As SldWorks.Component2, nLevel As Long)      Dim vChildComp                  As Variant     Dim swChildComp                 As SldWorks.Component2     Dim swCompConfig                As SldWorks.Configuration     Dim sPadStr                     As String     Dim i                           As Long     Dim Current                     As String       Dim swApp                       As SldWorks.SldWorks        Dim swSelObj                    As Object             For i = 0 To nLevel - 1         sPadStr = sPadStr + "  "     Next i          vChildComp = swComp.GetChildren        times = 0            For i = 0 To UBound(vChildComp)         Set swChildComp = vChildComp(i)         TraverseComponent swChildComp, nLevel + 1             Current = swChildComp.ReferencedConfiguration                    Set swSelObj = swChildComp.GetModelDoc                                Debug.Print sPadStr & swChildComp.Name2                Debug.Print swSelObj.CustomInfo2(Current, "Description")                Debug.Print swSelObj.CustomInfo2(Current, "PartNo")         Next i         End Sub


Thank you in advance!

Collection Or Array
Hi all,
Ive spent the last 2 weeks teaching myself VBA and ive struggled through most things by reading around on the web and trial and error with different things.
Im getting close to having something in my program actually working, but i need to decide whether im best to use an array or collection to store my data. Its a calculation program for an electrical network, where the data on transformers and lines etc is read from worksheets and stored. The user then enters other parameters on these lines and transformers such as load, voltage, etc. From there it is calculated and output to the screen. However i want the user to be able to delete these items so they wont be used in the calculation, or to be able to change the data they input such as load if it changes.

I will post the program i have, and hopefully it will make a little more sense if you run the user form.

Selecting add feeder or add substation will bring up the items to be added.
Selecting the add feeder button on the left will then input the data into the middle text box on the main menu.
The large amount of extra text boxes is where this data is to go eventually, but for now im using the middle one as a test box just to check im getting the right data out.

So you can see i will have a branch A and branch B, so will probably need to have either 2 colelctions or arrays. Within these there will be either a transformer entry or a feeder entry, and it will contain all necessary data such as impedance, load, transformers on load, power factor etc.

Hopefully this makes some sense and someone can help me out here. If you need to know any more, just ask.

ps. to run the add feeder command, you should set load to any value from say 0 to 1000 being realistic. power factor = 1.
and voltage = 33

Cheers, Rob

Help With Array Or Collection
I need to have an array or collection or something to that nature where I can have a key, for searching, and a value. I need to be able to store a list of WorkCenters as keys and for each WorkCenter, I need to have a value of what group it belongs to. Does this make sense and if so, got any suggestions?

Collection Vs. Array
From my simple understanding of VB, Arrays are slow. Are Collections any faster? Can you add and remove from the end of a collection like reDim Preserve on an array? Does For Each work on collections?

Would you ever use an array to store an object (non simple DT)?

NOMAD

Collection/Array
Hello,

Please help me to solve this easy problem (easy to you but not to me).
I have this block(I, II) and name(A, AB). Their combination is 4 and put in a collection. Each item in this collection (i.e. I_A) points to few records. There're many items in each record and one of these items points to a list of other items.

if I have three class modules (CArray, CRecord, CData).
CArray
I declare an array of collection:
Private m_array(1 to 4) as collection
What else do I need to do to load those 2 blocks and names into this collection?
I know there's a m_array.Add and m_array.remove but don't know how to implement them.

CRecord

CData

Also how do I link them to my records and link each of my record to other item from other collection?

Collection Or Array??
What;s better to use a collection or an array wich I have to redim each time??

Please give answers wich explanation,

like less memory usage etc.

Collection Or Array
What exactly is the difference between a collection and an Array?


Are they not exactly the same thing with different names?

Thanks!

Well... Array Vs Collection
I want to store information in memory Which should I use? What is the difference?

Array In The Collection
Can anybody give me a hint how to get an array element if this array is a collection's item.

Example.
col_N.Item(1) = "12"
col_N.Item(2) = "22"
col_N.Item(3) = arr_num()

arr_num(0) = 7
arr_num(1) = 8

What if I need to get 8?

Thanks a lot,

Yuri

Collection Or Array?
Here is my predicament. I have a short list of file properties that I want to edit. The problem is, is that there are almost 150 that I can iterate through idividually but I don't want to. Is there a way that I can just cut to the chase perhaps using a select case do this.

These are some of the property strings that I am looking for

dim strCompany as string
dim strDesign as string
dim strDescription as string

I thought about setting the strings to what the property callouts will show, but I couldn't figure out how to get the strings to fill the text1.text box when the strings were found. I'd like to set the strings into a collection if that would be faster retreive.

set strCompany = "Company"
set strDesign = "Design"
set strDescription = "Description"

This is how I can iterate through the properties:

'setA, setB, and setC will need to be another collection properties.

For i = 1 to propsets.count
if propsets(i).displayname = setA or setB or setC then
dim prop as property
dim j as interger

for j = 1 to propsets(i).count
set prop = propsets(i).item(j)

if prop.name = strCollection then 'This is where I need it to jump to the strings that I have singled out for use.
prop.value = ""
end if

next
end if
next

Can somebody help put me out of my misery. This all I have to do to finish my project, then I can sleep.......

Thanks in advance,

Adding An Array To A Collection
is it possible to add an array of user defined type to a collection?

Speed (Array/Collection)
Hello

I was wondering what the speed difference are between using a Array and a collection. An array would be fast but what if you move in and out a lot of things. Would a collection be faster than??

Thx

ChoKamir

DB Connections Using Array/Collection?
Hello,
I'm working on a project in which I have to use a lot of functions and each function connects to the same database, using same function.

I think, it will be more clear if I paste functions here .... so,

I used the following function to connect to the database...

Code:
Public Function DB_Connection_Open() As Boolean
If oRS.State <> 0 Then oRS.Close
If oCon.State <> 1 Then ' isOpen?
dbPath = App.Path & "avis.mdb" ' Actual path
strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & dbPath
oCon.Open strConn
DB_Connection_Open = True
Exit Function
End If
DB_Connection_Open = False
End Function

following is the function to disconnect/close the connection from database...

Code:
Public Function DB_Connection_Close() As Boolean
If oCon.State <> 0 Then ' if not closed
oCon.Close
Set oCon = Nothing
DB_Connection_Close = True
If oRS.State <> 0 Then oRS.Close
Exit Function
End If
If oRS.State <> 0 Then oRS.Close
DB_Connection_Close = False
End Function

Following are the 2 functions where the real problem occures....
First function... pass the category name and ComboBox name in which the returned values will be stored.

Code:
Public Function getItemsInCategory(ByVal theCategory As String, inCombo As ComboBox)
inCombo.Clear
Call DB_Connection_Open
oRS.Open "SELECT Name FROM ITEMS WHERE Cat=" & getCategoryID(theCategory), oCon, adOpenForwardOnly, adLockReadOnly
If Not oRS.EOF Then
While Not oRS.EOF
inCombo.AddItem oRS.Fields(0).Value
oRS.MoveNext
Wend
inCombo.ListIndex = 0
Else
inCombo.AddItem "No Item Found in " & theCategory
inCombo.ListIndex = 0
End If
Call DB_Connection_Close
End Function

this function calls the below function (getCategoryID)....

Code:
Public Function getCategoryID(ByVal theCategory As String) As String
Call DB_Connection_Open
oRS.Open "SELECT RecID FROM ITEMS_CATEGORIES WHERE Category='" & theCategory & "'", oConN, adOpenForwardOnly, adLockReadOnly
If Not oRS.EOF Then
getCategoryID = oRS.Fields(0).Value
End If
oRS.Close
Call DB_Connection_Close
End Function

getCategory function uses the same function (DB_Connection_Open/Close), when this function is called, it will close the existing opened connection, and the error will occur, saying (Operation not allowed when the object is closed) .

Now, what I want to do is, create 2 functions e.g. DB_Connect(ConnectionName as String) and DB_Disconnect(ConnectionName as String) to connect/disconnect from the database. the ConnectionName will be Added to the "Collection" object and when DB_Disconnect is called, it will close that connection and remove the ConnectionName from Collection.

It is possible by theory but, can you please help me by giving an example which emulates the above?

It is very very important for me to complete this project.
I would be very thankful for your help.

Let me know if further explanation is required.

Warm regards.

Array Versus Collection.
In VB6 what is the best, an array or a collection. Is there any difference in retrieving the values from either, i.e. is an array faster than a collection or vice versa?


Kev.

Array, Collection Or Dictionary?
I am developing a program in which certain users will have access to certain features depending upon there access level. I have a table that lists each users Access Level for each feature. Currently I load the user's Access levels into a 2 dimensional array after the User successfully logs in. Now when a user attempts to access a feature I search the array for the Feature Name then I check the Access Level (UnitRead, UnitEdit, UnitAdd, GlobalRead, GlobalEdit, GlobalAdd, etc).

My question is would I be better off creating a Collection or Dictionary to store this data or should I stick with the array? Is there a such thing as a two dimensional Collection or Dictionary?

Thanks!

Array In A Collection Class
Hello,

I have a Collection of Classes
How can I create an array in this Classes,
and how can I get acess to the array-elements?

Detailed Description:
One Class describes on Graphic-Element
A Collection for many Graphic-Elements
The Array in this Classes is for the x,y Koordinates of the Graphic-Elements: Each Element consists of various Koordinates: so I need a dynamic Array.

How can I create this array?
and how can I get access to the koordinates?

Can anyone help?
Bye
Ramoni

Control Collection/Array
I'm trying to take a snapshot of all the controls currently on a form and store the type/properties of each of those controls *AS IT IS RIGHT NOW* into a collection or array. THe problem im having is, when a control property changes, it changes in the collection. Is there a way to store a "copy" of the control into a collection or array with its current properties able to change when the control does?

If I have confused you, I'm sorry.

Array, Collection, Or ?????? **Resolved Enough**
I'm working on a process that is going to loop through a recordset a few times (different dataset each time).
I need to keep track of the ID of each of the records I loop through. Here's the catch, sometimes, the same ID may appear in one or more of these iterations. When I'm done with all looping, I want to be able to cycle through the list if IDs and pass it off to another procedure. BUT, each ID can only be processed once.
I thought about a Collection, but to hold a simple ID (long int) the overhead wouldn't be worth it - but I'd be able to check to see if the ID was already in the colleciton. So, I thought about an array, but then I would have to loop through it to see if the ID was already in there - problem with that is time, the processing is already long enough, I don't want to have to delay it any more than necessary.
Has any one got any ideas -- I don't care how outrageous it is.... any kind of an idea could be helpfull.

Collection Or Array For Speed?
I have a class called stock that holds last_price, symbol, high, and low (for now).

I have a collection of stock named stocks that is index by symbol.

The collection stocks contains app. 1300 instances of obj stock.

I have an event that triggers when the last price on any of the 1300 stocks changes. When this happens I need to update the last_price field to the new price.

With collections (my current implementation), since I cannot modify a member of a collection, I am simply deleting it and then adding it back with the new price.

The deleting and re-adding seems rather tedious.

The other possible solution would be to have an array of stock objects, which would allow me to modify the last_price field. But then I would have to use a hash table to find the index number, and maintain code for redims, etc.

Any thoughts on which is the more efficient method are appreciated. Along with ideas on even more efficient implentations than this.

Thanks!

Go Jets.

Steve Jones

An Array, Collection, Or Object??? Need Help!
I am writing an app that will load a matrix of accounts and document types from a detail file which may contain many accounts and many documents of the same type for each account. Basically all this will be loaded into a treeview with each account showing up only once as a parent, then each document type (only once) under that, and finally every document record read, stored uder the correct account and document type. So for example, I may have some raw data that may come in like this:

Account#, DocType, Date created
55555555, 2, 2/2/00
22222222, 1, 1/31/99
33333333, 1, 1/25/00
55555555, 2, 12/31/99
55555555, 2, 2/1/00
55555555, 1, 11/30/98

The ultimate goal would be to have the tree something like this:

22222222
---1
------1/31/99
33333333
---1
------1/25/00
55555555
---1
------11/30/98
---2
------12/31/99
------2/1/00
------2/2/00

So I am looking for the proper way to store this stuff so A)I can properly load the treeview without adding duplicates and B)so I can access the data at the document level (I simplifed this example, for the purposes of asking for help).

At first I thought I could use a multidimensional array. I would have a single dimension array with just accounts in it and search that array first to see what index a particular account is in. I would use the 2nd dimension to hold the document type. Problem is I don't know ahead of time if I will have 1 or 100 document types for a particular account and I don't want to make a big fixed size array and waste alot of memory.

What I really have here or would like I suppose is an array inside an array. In this approach I would have the account array holding the document type array (which could be a different size for each account).

So my actual question here is how would you implement this situation? I suppose the easiest would be to declare a large multi-dim array, but I wonder if I could use a collection or several collections, or even better, an object. I don't know much about objects yet but maybe there is some way to create one object for each account. I could still have my account array to determine if I 'have' that account already and if not create a new object with it's own array. Even with this approach however, how would I get down to that level, the array within the particular object when desired?

Thanks for taking the time to read all this and I hope you can help me find a solution!

Array/collection Needs To Be Dynamic
dear develpers...
I have to store master detail data in array or collection. The array or collection should be dynamic.
suppose i store master data (eg name) in one array/collection and i have to store its salary(detail data) in another array.

Is it possible.
The array/collection should be dyanamic.
thank u.

Should I Use Type-array Or Collection Here...
I decided to add a forward/back option on my CodeDatabase program. What I will do is save the key field and description field of the records viewed.

A collection will be much easier to work with because I would need to be able to remove and change positions of the members, so I guess my main question is about performance. I know collections weigh a little more than arrays, but is it enough to make a difference? I doubt this collection would ever grow bigger than 100 or so.


God Bless America

An Array, Collection, Or Object??? Need Help!
I am writing an app that will load a matrix of accounts and document types from a detail file which may contain many accounts and many documents of the same type for each account. Basically all this will be loaded into a treeview with each account showing up only once as a parent, then each document type (only once) under that, and finally every document record read, stored uder the correct account and document type. So for example, I may have some raw data that may come in like this:

Account#, DocType, Date created
55555555, 2, 2/2/00
22222222, 1, 1/31/99
33333333, 1, 1/25/00
55555555, 2, 12/31/99
55555555, 2, 2/1/00
55555555, 1, 11/30/98

The ultimate goal would be to have the tree something like this:

22222222
---1
------1/31/99
33333333
---1
------1/25/00
55555555
---1
------11/30/98
---2
------12/31/99
------2/1/00
------2/2/00

So I am looking for the proper way to store this stuff so A)I can properly load the treeview without adding duplicates and B)so I can access the data at the document level (I simplifed this example, for the purposes of asking for help).

At first I thought I could use a multidimensional array. I would have a single dimension array with just accounts in it and search that array first to see what index a particular account is in. I would use the 2nd dimension to hold the document type. Problem is I don't know ahead of time if I will have 1 or 100 document types for a particular account and I don't want to make a big fixed size array and waste alot of memory.

What I really have here or would like I suppose is an array inside an array. In this approach I would have the account array holding the document type array (which could be a different size for each account).

So my actual question here is how would you implement this situation? I suppose the easiest would be to declare a large multi-dim array, but I wonder if I could use a collection or several collections, or even better, an object. I don't know much about objects yet but maybe there is some way to create one object for each account. I could still have my account array to determine if I 'have' that account already and if not create a new object with it's own array. Even with this approach however, how would I get down to that level, the array within the particular object when desired?

Thanks for taking the time to read all this and I hope you can help me find a solution!

Find The Value Of An Array Item Which Is In A Collection
Hi,

I have a collection and each and every item is an array of values.

I would like to find the value of items in that array in that collection. I can extract the values if I use For Each ... However, I would like to access directly and find the value.

The current code I have is:


Code:
Sub TestCollection()
Dim oTests As New Collection
Dim var As Variant

oTests.Add Array("student 1", "Maths", "90")
oTests.Add Array("student 2", "history", "50")
oTests.Add Array("student 3", "science", "80")

For Each var In oTests
'var(0) 'Student
'var(1) 'subject
'var(2) 'marks
Debug.Print var(0)
Debug.Print var(1)
Debug.Print var(2)
Next var
End Sub


I would like to access and get the value "student 2" directly, not using for each.

Thank you

Initialise Structure, Collection, Array
I have a very large amount of data I want to load into a collection, array or similiar structure.

I created a Module with a collection and just tried to add all the items when the routine was called, but this resulted in a:

"Procedure too large" error message.

What is the best approach to handle this?
Ideally I'd like to do it at compile time, if that's an option with VB, which I'm not sure it is.

Thanks in advance.

Collection To Array Conversion - Resolved
Code:

'****************************************************************************
' Enumerate Value Names under a given key
' Inputs: Key Root, Key Name
' Return: a collection of strings
' Source: Slightly modified from www.vb2themax.com EnumRegistryKeys
'****************************************************************************
Public Function EnumRegistryKeys(ByVal hkey As hkey, ByVal KeyName As String) As _
Collection
Dim handle As Long
Dim length As Long
Dim index As Long
Dim subkeyName As String
Dim fFiletime As FILETIME
' initialize the result collection
Set EnumRegistryKeys = New Collection

' Open the key, exit if not found
If Len(KeyName) Then
If RegOpenKeyEx(hkey, KeyName, 0, KEY_READ, handle) Then Exit Function
' in all case the subsequent functions use hKey
hkey = handle
End If

Do
' this is the max length for a key name
length = 260
subkeyName = Space$(length)
' get the N-th key, exit the loop if not found
If RegEnumKeyEx(hkey, index, subkeyName, length, 0, "", vbNull, fFiletime) = ERROR_NO_MORE_ITEMS Then Exit Do
' add to the result collection
subkeyName = Left$(subkeyName, InStr(subkeyName, vbNullChar) - 1)
EnumRegistryKeys.Add subkeyName, subkeyName
' prepare to query for next key
index = index + 1
Loop

' Close the key, if it was actually opened
If handle Then RegCloseKey handle

End Function
'****************************************************************************
' Enumerate values under a given registry key
' Inputs: Key Root, Key Name
' Return: a collection, where each element of the collection
' is a 2-element array of Variants:
' element(0) is the value name, element(1) is the value's value
' Source: Slightly Modified from www.vb2themax.com EnumRegistryValues
'****************************************************************************
Function EnumRegistryValues(ByVal hkey As hkey, ByVal KeyName As String) As _
Collection
Dim handle As Long
Dim index As Long
Dim valueType As Long
Dim name As String
Dim nameLen As Long
Dim resLong As Long
Dim resString As String
Dim length As Long
Dim valueInfo(0 To 1) As Variant
Dim RetVal As Long
Dim i As Integer
Dim vTemp As Variant

' initialize the result
Set EnumRegistryValues = New Collection

' Open the key, exit if not found.
If Len(KeyName) Then
If RegOpenKeyEx(hkey, KeyName, 0, KEY_READ, handle) Then Exit Function
' in all cases, subsequent functions use hKey
hkey = handle
End If

Do
' this is the max length for a key name
nameLen = 260
name = Space$(nameLen)
' prepare the receiving buffer for the value
length = 4096
ReDim resBinary(0 To length - 1) As Byte

' read the value's name and data
' exit the loop if not found
RetVal = RegEnumValue(hkey, index, name, nameLen, ByVal 0&, valueType, _
resBinary(0), length)

' enlarge the buffer if you need more space
If RetVal = ERROR_MORE_DATA Then
ReDim resBinary(0 To length - 1) As Byte
RetVal = RegEnumValue(hkey, index, name, nameLen, ByVal 0&, _
valueType, resBinary(0), length)
End If
' exit the loop if any other error (typically, no more values)
If RetVal Then Exit Do

' retrieve the value's name
valueInfo(0) = Left$(name, nameLen)

' return a value corresponding to the value type
Select Case valueType

Case REG_DWORD
CopyMemory resLong, resBinary(0), 4
valueInfo(1) = resLong

Case REG_SZ
' copy everything but the trailing null char
If length <> 0 Then
resString = Space$(length - 1)
CopyMemory ByVal resString, resBinary(0), length - 1
valueInfo(1) = resString
Else
valueInfo(1) = ""
End If

Case REG_EXPAND_SZ
' copy everything but the trailing null char
' expand the environment variable to it's value
' Ignore a Blank String
If length <> 0 Then
resString = Space$(length - 1)
CopyMemory ByVal resString, resBinary(0), length - 1
length = ExpandEnvironmentStrings(resString, resString, Len(resString))
valueInfo(1) = TrimNull(resString)
Else
valueInfo(1) = ""
End If

Case REG_BINARY
' shrink the buffer if necessary
If length < UBound(resBinary) + 1 Then
ReDim Preserve resBinary(0 To length - 1) As Byte
End If
'Convert to display as string like this: 00 01 01 00 01
For i = 0 To UBound(resBinary)
resString = resString & " " & Format(Trim(Hex(resBinary(i))), "0#")
Next i
valueInfo(1) = LTrim(resString) 'Get rid of leading space

Case REG_MULTI_SZ
' copy everything but the 2 trailing null chars
resString = Space$(length - 2)
CopyMemory ByVal resString, resBinary(0), length - 2

'convert from null-delimited (vbNullChar) stream of strings
'to comma delimited stream of strings
'The listview likes it better that way
resString = Replace(resString, vbNullChar, ",", , , vbBinaryCompare)
valueInfo(1) = resString

Case Else
' Unsupported value type - do nothing
End Select

' add the array to the result collection
' the element's key is the value's name
EnumRegistryValues.Add valueInfo, valueInfo(0)

index = index + 1
Loop

' Close the key, if it was actually opened
If handle Then RegCloseKey handle

End Function



Would anyone mind converting both of these so they output an array instead of a collection?

Thank you so very much, i'll make sure to give you credit.

- BaDDBLooD

Converting A Collection Into A Control Array
Here is a simple example of converting from a collection of controls into a control array.
Personally I much prefer working with control arrays than using control enumeration, so thats why I wrote this.

This example does however use control enumeration to find all the controls in the first place.

Create a form, and place 6 command buttons on it.
If prompted, do not use a control array.


VB Code:
Private Function createControlArray(ByRef controlCollection As Object) As Object()    If Not controlCollection.Count = 0 Then        Dim retVal() As Object: ReDim retVal(controlCollection.Count)        Dim i As Long: For i = 0 To UBound(retVal) - 1: Set retVal(i) = controlCollection.Item(i): Next        createControlArray = retVal    End IfEnd Function Private Sub Form_Load()    Command1.Caption = "Command1": Command2.Caption = "Command2": Command3.Caption = "Command3":    Command4.Caption = "Command4": Command5.Caption = "Command5": Command6.Caption = "Command6":    Dim cmdButtons() As Object: cmdButtons = createControlArray(Form1.Controls)    MsgBox "Caption of third command button : " & cmdButtons(3).CaptionEnd Sub

Result As Collection Of Objects And Not As Array
Hi,
can anyone tell me how can I use a collection of objects as my final output and not array. I have a double dimensional array having file name and file path. Instead I need to have them in a collection of objects. Any idea?????

How To Determine Whether All Items In Array Exist In Collection
A Have an array of Strings, and a collection of Strings.
I'm having a little trouble figuring this out. What I want to do is see if all the strings in my array exist in the collection.

Checking Existance Of Printer In A Collection/array
Hello,

I am trying to figure out whether one of the printers from the print server had been mapped already using code below, but I am not having too much luck. Can you help?

NOTE: I don't want to use "For Each objPrinter in colPrinters" statement because I don't want to iterate through every record in the collection. I just want to find out if a particular printer exists in colPrinters. If it does I don't want to do anything, if it doesn't I want to map it.

 

On Error Resume Next
Set objNetwork = CreateObject("Wscript.Network")
Dim colInstalledPrinters
Dim objPrinter
Dim strMapPrinter1
Dim strMapPrinter2
Dim strMapPrinter3
Dim strPrintServer
strPrintServer = "\caprint01"
strMapPrinter1 = "TOSHIBA e-STUDIO 550 PCL6"
strMapPrinter2 = "TOSHIBA e-STUDIO 520 PCL6"
strMapPrinter3 = "Dell Laser Printer 3100cn PCL6"

strComputerName = "."

Set objWMIService = GetObject( _
     "winmgmts:" & "{impersonationLevel=impersonate}!\" _
     & strComputerName & "
ootcimv2")
 Set colInstalledPrinters =  objWMIService.ExecQuery _
     ("Select * from Win32_Printer")
 Dim i
 For i=0 To UBound(colInstalledPrinters) Step 1
  If colInstalledPrinters(i) = strMapPrinter1 Then
        Wscript.Echo "Printer Already Mapped"
  
  Else
    objNetwork.AddWindowsPrinterConnection strPrintServer & strMapPrinter1
    'objNetwork.SetDefaultPrinter strPrintServer & strMapPrinter1
        End If
    Next
    InArray=False
 
Set objNetwork = Nothing
Set objWMIService = Nothing
Set colInstalledPrinters = Nothing
WScript.Quit

 

Thank you.

Igor

Making A Graphics File From An Array Or Collection In VB
 Hi -

 Can someone tell me if there is functionality in VB6 to create a graphics file, such as a bitmap, from the contents of an array or collection. I'm fairly new to VB but I know there are functions in VisualAge Smalltalk that can do this. This is my first poting, hope it's not too off the wall.

Disabling Menu Items When Using Collection Array
I have a parent form with a menu, and I want some of the menu items disabled when a child form is opened. The book I am learning from only gives an example for unique named menu items, not arrays. Is there a way to disable one menu item when an array was used. Thank you in advance.

Catrina

How To Pass An Array Of Collection Object To A Function?
How to pass an array of collection object to a function? Also i want to know how u have to design the function which is going to accept this parameter. I have tried with ByRef argument but it is giving an error 'Object variable or with block variable not set' when i try to access the parameter.

I am giving the code:

'##ModelId=3897F4F2009C
public Function UpdateUnit(byref colValues() as Collection) as string
on error GoTo UpdateUnit_Err
Dim i%

for i = LBound(colValues) to UBound(colValues)
MsgBox colValues(i).Item(1)
next

Exit Function

UpdateUnit_Err:
RaiseError Err.Number, Err.Source, etError, Err.Description
End Function




I am calling this function like this:


private Sub TransferData_Unit()

strSql = objCUtil.StrConv(LoadResString(4001), ":Mandant", colParams("Mandant"))

rsPps.Open strSql, cnnClient, adOpenStatic, adLockOptimistic

If Not rsPps is nothing then
With rsPps
If .RecordCount &lt;&gt; 0 then
objProg.Info_Tip1 = LoadResString(1503)
objProg.Min = 0: objProg.Max = .RecordCount

ReDim colFieldVals(.RecordCount) as new Collection

Do While Not .EOF
'Incrementing progress dialog
objProg.Value = .AbsolutePosition

'adding relevent values to the collection object
colFieldVals(.AbsolutePosition).Add !me_von, "me_von"
colFieldVals(.AbsolutePosition).Add !bez_von, "bez_von"
'Updating rececords to incoplan
.MoveNext
Loop

'Now saving data to incoplan
objIncoPlan.UpdateUnit colFieldVals()
End If

End With

End If

End Sub




Thanks in advance


Initiative is to success what a lighted match is to a candle...

Collection .Add Not Working For First Element In Control Array (Hack?)
Sorry for the layman's thread title. It's Monday morning and I've been fighting this for quite some time already.
Here's the situation. I have a collection that holds a bunch of the same class, over and over. The class is simply used to maintain the properties of line items on an order. I have a user form asking for an operator to enter in various bits of data and those records are stored into the collection. 1 record/class per line item. Simple enough, right? Well, I thought so too. However, my collection.add isn't working for the first record when I iterate through the items to add them to the collection. Here's the psuedo code. (Various data validations, etc, intentionally not included.)


Module level declarations

vb Code:
Global g_clsKYDM            As clsKYDM Global g_colLineItems       As Collection


Pub sub main

vb Code:
Public Sub Main()     Set g_colLineItems = New Collection    Set g_clsKYDM = New clsKYDM        frmLines.ShowEnd Sub



Here's my add button click event. Button on the frmLines. This assume's multiple lines could be added at a time so I iterate through them in the for next loop. The text, combo's, etc are all control arrays and there are a maximum of 5 per.


vb Code:
Private Sub btnAddItems_Click()    Dim strErrMsg   As String    Dim lngCounter  As Long    Dim blnReset    As Boolean    Dim strResults  As String        On Error GoTo ERRORHANDLER        blnReset = True    lngCounter = 0        For lngCounter = 0 To txtWeight.Count - 1        g_clsKYDM.AddLineItem CLng(txtPieces(lngCounter).Text),                                 "Sample add", _                                CLng(txtWeight(lngCounter).Text),  blnReset, strErrMsg        blnReset = False    Next lngCounter    GoTo OVERERROR ERRORHANDLER: OVERERROR:    End Sub


Here's the "Add Item" Function, found in clsKYDM, which should, as named, add the item to the collection.


vb Code:
Public Function AddLineItem(ByVal v_lngQuantity As Long, ByVal  _                                ByVal v_strDescription As String, _                                ByVal v_sngTotalWeight As Single, Optional ByVal v_blnStartNew As Boolean, _                                Optional ByRef r_strErrorMessage As String) As Boolean            Dim itmLineItem         As New clsLineItem    On Error GoTo ERRORHANDLER        ' Populate a new line item class w/ data being pass and add it to the lineitem collection    With itmLineItem        .lngQuantity = v_lngQuantity        .strDescription = v_strDescription        .sngTotalWeight = v_sngTotalWeight    End With        With g_colLineItems            If v_blnStartNew = True Then            Set g_colLineItems = New Collection        End If                ' Add the class to the collection         ' THIS FAILS ONLY ON THE First iteration        .Add itmLineItem    End With        AddLineItem = True GoTo OVERERROR    ERRORHANDLER:    AddLineItem = False        If LenB(r_strErrorMessage) = 0 Then        r_strErrorMessage = Err.Number & g_strCOLON_SPACE & Err.Description    End If    OVERERROR: End Function



Line item class properties

vb Code:
Option ExplicitPrivate m_lngQuantity         As LongPrivate m_strDescription      As StringPrivate m_sngTotalWeight      As SinglePublic Property Get lngQuantity() As Long    lngQuantity = m_lngQuantityEnd Property Public Property Let lngQuantity(ByVal v_lngQuantity As Long)    m_lngQuantity = v_lngQuantityEnd Property Public Property Get strDescription() As String    strDescription = m_strDescriptionEnd Property Public Property Let strDescription(ByVal v_strDescription As String)    m_strDescription = v_strDescriptionEnd Property Public Property Get sngTotalWeight() As Single    sngTotalWeight = m_sngTotalWeightEnd Property Public Property Let sngTotalWeight(ByVal v_sngTotalWeight As Single)    m_sngTotalWeight = v_sngTotalWeightEnd Property

Control Array Object From Form Controls Collection?
How can I access a control array object as an item on a form, vs. explicitly by name?

e.g. I have a TextBox "Text1", with index=0 on a form (that's it)
but the following code fails with Error 344, "Must specify index for object array"


Code:
Dim xx As Object

For Each xx In Me.Controls
Load xx(1)
Next xx



FWIW
Load Text1(1) works fine.
? TypeName(Text1) = Object
? TypeName(xx) = TextBox

Apparently, in the For Each loop it's giving me actual instances of the textbox control, rather than the control array itself.

Thanks, DaveBo

Adding A Control Array To The Form.Controls Collection
Does anyone know how to add a control Array of text boxes or labels to the Form.Controls Collection. I need this so I can generate an entry form from a script held in a database.

Collection, String, Listbox? Want To Add Only Unique Items Constantly To An Array
Basically heres what my program does.
Every 10 seconds a file is generated (by another program) that contains a list of items.
I need to make a program that opens this file, and takes all the items and add each to an array - making sure that only unique items are added to this array.

For example - my program's array contains 'hello, test, vb, google'. It opens up the generated file which contains 'television, hotmail, radio, toaster, hello, calendar'. It needs to append this list, so the array now contains 'hello, test, vb, google','television, hotmail, radio, toaster, calendar' (note hote 'hello' was not added twice). It then removes the generated file so the next time its opened it has (somewhat) fresh new items.

But the array will be very big and my program needs to save its array to a file every few minutes.

What would be the best way to do this? using a listbox? (setitng it to visible = false, and using API (LB_FINDSTRINGEXACT) to add unique items) a collection (but its very large and memory intensive)? a string (but i dont know if there are quick ways of adding unique items to a string array, and i really dont think looping through thousands of items all the time will be efficeint)

Any help would be appreciated

Sort Data From An Existing Collection And Save It Into Another 2nd Collection
Hi,

have a huge problem. I have an existing collection and would like to use this collection to save some data from it into another collection.
The Problem is: in the 2nd collection I only have e.g. 5 times the same number. I'm using an if-loop for that, maybe the reason for it...

But before, I just try to explain a little of the structure (otherwise maybe my words doesn't make much sense to you).

My already working 1st collection has some properties which I fulfilled via an SQL-recordset.
I just want to use this information to 'sort' it in order to allow a correct graphical and hierarchical presentation (via an algorithm) on the screen -> like an organigram.

My 1st, working collection looks like:

Code:
dim x as my_object
Dim records As ADODB.Recordset
Dim sql1 As String
Dim strCnn As String
Dim my_collection As New Collection

Set records = New ADODB.Recordset

strCnn = "Provider=some;User ID=one_user;Password=one_password;Persist Security Info=True;Initial Catalog=server;Data Source=server"

sql1 = "SELECT ...................."
rs_app.CursorLocation = adUseClient
rs_app.Open sql1, strCnn, adOpenKeyset, adLockOptimistic, adCmdText


While Not records.EOF
Set x = New my_object
If IsNull(x) = False Then
x.my_key = records("my_key").Value 'ist eine Eigenschaft
x.my_overkey = records("overkey").Value

my_collection.Add x

records.MoveNext
Else
End If
Wend
-> So far so good, that works!!



HOWEVER, if I furthermore would like to sort that after a special criteria (e.g. just save all "my_key's" in another collecton, which have the "my_overkey" number "0815" then won't work.
If I have 5 numbers (which belong to 0815) then I get 5x the same my_key - number. I guess the reason for that error is the if-loop.
Does anybody know an solution/a better way for that? ?


my solution looks like:

Code:
dim collection2 as new collection ' defined via class-builder
set collection2 = new collecton

For i = 1 To my_collection.Count

'type_app habe ich dann als "0815" definiert

If my_collection.Item(i).my_overkey = type_app Then


y.my_key = my_collection.Item(i).my_key
y.my_overkey = my_collection.item(i).my_overkey

collection2.Add y

end if
next


Would be very grateful for any suggestion!!

Thanks
new_one

Error In Collection Whenever Delete One Item From Collection!!!
Hii everybody,

I am trying to remove one of the item from the collection, any item not like first or last or in sequence. LIke i have collection of 4 items and i removed 2 second item. After that i am trying to add new with new Key value whcih for this example is 5(In sequence). Then it generates error that "subscript out of range." I know wehn i am removing item, collection counter is decresing. But i did not get why it is giving error?

is it possible to remove item randomly from collection and then add new items with new key during run time?

Please enybody can give me small help or reference to example?

Thanks!!!

Hdave

Object Programming, Collection Of Collection
Ok i have been researching how to do object oriented programming for the past few days and so far it has been very very hard for me to find anything. so far i have been able to create a collection just by its self and display the information as needed. but i have another layer to my object...

it would look something like this...


Code:
Customer
|
+--+Customer Detail
|
+--+Customer Accounts


if i understand objects right...which i dont think i do its pretty much just a big array that is suposedto be faster and easyer to work with. but im trying to do if my example thing didnt get it accross is to make a collection "customer detial" then after that have another collection "customer accounts" for each different item if you will in customer detail...is this posible and if it is how would i go about this? thanks!

Properties Collection Of A Controls Collection. Help
I'm trying to retrieve the properties collection of a control collection, and my code is giving me the "object doesnt support this property or method" error. Anyone know why ?

    Dim objForm as Form
    Dim objControl As Control
    Dim objProperties As Property
    

    For Each objControl In objForm.Controls
        Debug.Print TypeName(objControl) & ": " & objControl.Name
        For Each objProperties In objControl.Properties  <-----ERRORS HERE
            Debug.Print "Properties for " & objControl.Name & ": " & objProperties.Name
        Next
    Next

Class, Array/Collection Within Class
Hi,

I am using a class to represent a object in my application. One item of such class(a property) could be having multiple itmes for some instances. I mean if I've Class A and P is a property of A, I could have multiple Ps for one instance of A. Like A.P1, A.P2, A.P3 etc. What is the best concept in Vb that I could use to represent such property? A collection? A array? Thanks for any suggestions

Class - Collection/Array Within Class
Hi,

I am using a class to represent a object in my application. One item of such class(a property) could be having multiple itmes for some instances. I mean if I've Class A and P is a property of A, I could have multiple Ps for one instance of A. Like A.P1, A.P2, A.P3 etc. What is the best concept in Vb that I could use to represent such property? A collection? A array? Thanks for any suggestions

Collection Inside Collection
Hello, I'd like to know if it is possible and how it can be done to
make collections with inside a class that contains another collection.

I tried it: when I es. add an item to the Inside collection, VB says
Method or data member not found.

Calling Collection1 the main and Collection2 the inside, I wrote:

Coll1.add (...args..., Coll2)

Coll1(1).Coll2(1).Property... ... Method or data member not found


I'm a self-learning (I'm not sure if this is the right way to say) so I'm not sure what is the problem.


Any chance to do this?

Thanks, Gibbofresco

Getting A Collection Item From One Collection To Another
Hi,

Okay, I've spent 2 days trying to figure this out. I'm obviously missing something because it seems it should be easy .

I have 2 Collections and want to get an item from one to the other. I have a function for adding an item and tried to write a function for getting an item and returning it to the add function. This didn't go over well. I've also tried to write a copy function but didn't have success with that either.

Anyone know how I should be trying to go about this.

Thanks in advance

kjf

Adding An Object From A Class Collection To Another Class Collection
I have a problem in that I am have created two class collections and I want to add to the first class collection an object comprising more than one object from the second class collection.

I think is it possible but I have no idea how to do it. I have created a wrapper for the add, delete and Item methods and the count property, but I do not know how to word the code to take the data into the object.

I want to only add the objects that relates to the first object! But I thought add the lot and then delete those that do not apply, but still can not work that out. Any help of suggestions will be gratefully received.

I have attached a zip file with the information, in it are a 5 PDF files with the classes, collections and the main module.

Anticipated thanks.

Copyright 2005-08 www.BigResource.com, All rights reserved