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




How Do I Detect Whether A Collection Item Exists?


Hi,

I was just wondering how to detect whether a particular item in a collection exists?

ie. How do I check whether EMS Tools already exists in the following CommandBars collection?

Application.CommandBars("EMS Tools")

Thanks

Chris




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
? Collection Item Exists
Hi All,

I am trying to write a general function to test if a collection item exists. I have managed to do this for a specific collection, but i would like the function to be able to accept a passed collection.

for example,

itemExists(collection)

would return true or false.

Can you pass a collection ro a function, i was planning to return true or false from the function, but if the collection item i am trying to pass does not exist i get the error 'subscript out of range' before it is passed to the function.

i must be missing something simple.

please help

i want to be able to use the function in the following way

if (ItemExists(colABC(1))) then

or

if (ItemExists(colABC(1).colXYZ(2))) then


Simon

Problem Checking If Collection.item Exists
Hi,

My program was working fine using VB6 on XP, but then that computer died. So I'm --attemping-- to run the program on Windows 2000 Advanced Server. Unfortunately, some of the code doesn't seem to work on this platform.

In particular, I have the following code (snippet) that checks to see if an item exists in a collection:

1. securities(i) contains a string i.e."abc". I check to see if that item exists in the objTSRecords collection as follows:
...
If ItemExists(objTSRecords, securities(i)) Then
...

2. This invokes the follwoing "ItemExists" function latter in the same module:

Function ItemExists(col As TSRecords, key As String) As Boolean
Dim dummy As Variant
On Error Resume Next
dummy = col.Item(key)
ItemExists = (Err <> 5)
End Function

3. When the execution gets to the line:

dummy = col.Item(key)

The code jumps to the class module ("TSRecords.cls") where the collection is defined:

Public Function Item(ByVal Index As Variant) As clsTSRecord

Set Item = collTSRecords.Item(Index) ' <-- error occurs right here

End Function

I get (even though I've got "On Error Resume Next" defined):

"run-time error '5':
Invalid procedure call argument"

Although I've been trying to solve this for hours I keep getting this error. This code worked fine under XP just yesterday! Maybe there are some patches I need to get to fix this, or maybe the VB 6 on XP is more forgiving of my programming errors....?

Anyone got any ideas?

Thank you very much,

Robert

ComboBox List/add Item, If Item Exists, Dont Add It Again!
Dudes and Dudeesses I need help!

I have a problem with a combobox within a form. I'm scanning down the spreadsheet for values and asking a combobox to .additem, however, the same value may appear twice whilst scanning down. Is there an if statement that will look and check the combobox to see if it is already added, if so dont add it again, if not, add it?

as below,

Code:
combobox.AddItem "Hotmail"
combobox.AddItem "Yahoo"
combobox.AddItem "Hotmail"
Hotmail will be added twice, how can I stop that?

If worst comes to the worst, I can sort it out with a long winded method, but I'm hoping theres a quicker way.

Thanks for all your help

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

Key Exists In Collection
I found some code for checking if a key was already in a collection. The code is:


[code]
Public Function KeyExists(ByVal NewKey As String) As Boolean
On Error GoTo errKeyExists
KeyExists = IPs(NewKey).Index
If KeyExists > 0 Then
KeyExists = True
Else
KeyExists = False
End If
Exit Function

errKeyExists:
KeyExists = False
End Function
[CODE]


I don't understand the On Error. There are times when it returns a false and I try to add it to the collection I get an error that the key is already there. Without the On Error I get a "Invalid Procedure Call or Argument" error and the
KeyExists = IPs(NewKey).Index is highlighted.

Is there a better way to find if a key exists?

Key Exists In A Collection
Doing a search of the forum I found some code for checking if a key was already in a collection. The code is:

Code:

Public Function KeyExists(ByVal NewKey As String) As Boolean
On Error GoTo errKeyExists
KeyExists = IPs(NewKey).Index
If KeyExists > 0 Then
KeyExists = True
Else
KeyExists = False
End If
Exit Function

errKeyExists:
KeyExists = False
End Function


First I don't understand the On Error because when it returns a false and I try to add it to the collection I get an error that the key is already there.
Second is there a better way of checking if a key exists (if you have a first you need a second)?

Checking If An Object Exists In A Collection
Hi team

Does anyone know if there is a quick way to check if an object exists in a collection other than checking each one individually?

FW

How To Find Out If A Collection Element Exists
how would I go about figuring out if there's an item in my collection with a certain key?

My program creates collection items with keys "a##" where a is any letter and ## is a number.
now, how would check to see if key "s34" has data?

How To Find Out Whether A Class With A Certain Key Exists In A Collection?
Hi!

I recently ran into this simple problem - I would like to find out whether a class with a certain key exists in a collection (the collection is a class which acts as a repository of CommentStyle onjects in my application).
The way I tried to do this was:

strDummy = MyCollection(MyKey).Property1

If an error occurs, I would return False from the function DoesClassExist(MyKey as variant)

However, the application raises an unhandled error and crashes. I put the error-handling code in the collection class's Item Get property (On Error goto .._Err, Err.Raise err.number), put error handling code into the DoesClassExist function, but still no luck. I can of course iterate through the entire collection to find out whether a key exists, but it sounds to me the performance will quickly degrade with 1000 objects in the collection or more. Can anyone help here?

Thanks a lot in advance,
Stas

How Can You Find Out If An Object Exists In A Collection?
I have a class module called 'clsPayment' and a collection of them in another class module called 'PaymentsCollection'

I want to search through a database and see if there are any payments stored there that do not exist in my collection (so that I can delete them from the database)

The code I am using is
Code:
'Look for payments in database that are not in collection
With grstPayments
   .Filter = "payAccount = " & mlngAccountID
   if .RecordCount>0 then .MoveFirst
   Do until .EOF
         if not isObject (mcol.item(cstr(!ID))) then ...
         if mcol.item(cstr(!ID)) is nothing then ...
      .MoveNext
   Loop
End With

The two lines shown in red are where I am having problems. Neither of those syntaxes worked because they generated an error 5 'Invalid procedure call or argument'
Obviously VB6 doesn't like mcol.item with an invalid index, but that is exactly the thing that I am trying to find.
I could enumerate through all the items in the collection for each record in the database but that seems a bitt inefficient.
Can anybody suggest a better way?

Detect If Key Exists
I need to detect if the following key exits in the registry of the machine runnin gmy app.

key: HKEY_LOCAL_MACHINESOFTWAREMicrosoft.NETFrameworkpolicyv2.0

Look For a Setting Called: 50727

If it does, i just need a boolean set to true, otherwise it will stay false, this is for an app that will detect, and if needed install the .net framework, its a setup launched i am writing because I have given up on finiding a useable bootstrapper, since the M$ bootstrapper will only work if i use an MSI installer, which i refuse to do (for numerous reasons of which I will not go into)

So basically i found this function, GetSetting but i am not sure about how to use this because the paramters it asks for is an app name, and setting, but i have a specific key it need to goto.

Any ideas?

How To Detect One Form Exists?
Hello, Everyone:
I have one form. If it is launched, I won't launch a new form. Otherwise, I will go ahead and launch a new one. So, it is very important to know whether the form is already exists or not. Would someone be kind to let me know how I can handle it?
Thank you very much!
Charlie

How To Detect If Data Exists...
Er......i have a form with textfields and a data control.

How do I check if the current details being displayed on the textfields actually exist in the database?

Detect If Shortcut Already Exists ?
Does anyone know of a way to programatically detect if there is a specific desktop shortcut ALREADY installed on a PC ?

Thanks for any help...

How Do You Detect If A Certain File Exists?
I have this file that is being copied, "C:vb6.exe"

How can i detect if this is installed or not?

How To Detect If An Instance Already Exists?
Hello,

I'm using the VB snapIn Designer and I would like to know if there is a known way to detect if an instance of the snapIn is already loaded, and then cancel the load..?

If that helps, the SnapIn is an OCX, so it might be possible to track if the ActiveX is loaded. I can't stop MMC since MMC is used for a lot of applications.

Thank you.


---
Nicolas LeBlanc
Software Engineer
Ordiplan Inc.

Detect If Registry Entry Exists
How do I detect if a registry entry exists?
I have been looking all day for some code that will do this, found many examples, and not a single one worked.

Thanks

Detect If A VB Line Exists In The Program?
Hello,

How can I tell whether or not a vb line exists on my form? once the program is compiled (To see if the user drew a line)

Thank you!!

Stilekid007

How To Detect If An Excel Sheet Exists
Hi,

If I run xlBook.Worksheets(strSheetName).Activate on a sheet that does not exist within the workbook I get a 'subscript out-of-range' error.

Is there a way to first detect if it exists so I can prompt the user?

Detect If A SubForm Exists In A Form
I would like to check if a subform obj exists in a form.... I ve tried sth like:

if subform_obj is Nothing Then ......

but it wasn't able to detect it.....

Could anyone give me some advice please, thanks.

Detect If A Record Exists Using Conn.execute
Hi everybody,
Assuming one uses only ADODB.Connection (No Rs or loops to drive into the columns), is it possible to send a SQL query and discover if one/more records satisfying the query exists in a DB. Sufficient if we can find the no. of records satisfying the SQL.
Any other effective method to accomplish this task would also be appreciated.
Thanks in advance.

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

How Can I See If An Item Exists In The Listbox
How can I check if the listbox has the specified item?

Finding Out If An Item Exists...
I need to know if an item in a collection exists...

How do I do this?

say mCol is a collection and there are 2 items in it. ne with an ID of "WOOF" and the other "BADGER". What I want to do is find out if "WEASEL" exists...


VB Code:
If mCol.Item("Weasel") = <WHAT DO I PUT HERE> Then   'Code for when it already existsElse   'Code to add new itemEnd If


I have tried Is Nothing and others, but I can't seem to work it out.
The only way I can see it being done is by trapping the error caused by trying to find an item that doesn't exsist and place the code there, but surely this is bad programming

Booooooooooo...Need a Scooby Snack!!!

Checking If A Certain Item Exists In A Listbox
hey people...

i have a listbox, but i dont want to add an item in the listbox if theres an item in the list box that already exisits with the same value...

so i thought i could search the listbox to see if a certain item already is in the listbox...can anyone tell me how to do this??

thanks,

dan

Checking If An ITEM Already Exists In A Listview
Sorry wrong forum -> should be VS 2005 instead of classic vb

hi,

I'm currenly trying to load two textfiles in a listview.
afterwards i'm updating one of the columns where i have the following problem

i donnot know if a certain index of the item already exist

so for instance i want to update a subitem but i donnot know if the item itself exists.

the method
listview.item(2).exists

does not seem to exist

is there another way ?

Checking If An Item In A Listbox Exists
How would I check if something is already in a ListBox?

Checking To See If An Item Exists In An Array
I've got an array of up to 30,000 items. I then have a new item that I need to check against the array to see if it is already in there. If the item isn't already in the array, it is added.
Is there anything faster than looping through the entire 30,000 items, comparing one-by-one to see if the item is already in the array?
I've sped things up a bit by jumping out of the check loop once the item is found to be in the array, but that doesn't help when the item being checked is near the end of the array.

A friend suggested breaking the array in smaller sections so that smaller only portions of it would need to be checked. I'm going to give that a try.
Any other suggestions?

How To Get The Key Of A Collection Item.
I have a collection of data that I access in different ways.
Assuming that the collection is called Items, and each item is called Item, and finally the key is called Key
1. Direct acces to an item using:

Code:
Item = Items(Key)
2. Loop through all Item in Items:

Code:
for each Item in Items
Next Item

Now I know that I could define my own collection of data elements holding the Key value as part of its data, however I was trying to see if I could somehow get the Key value out of an Item in the collection.

Any ideas?

How To Get The Key Of A Collection Item?
I'm using the code below to find an item in my collection. How can I get its key argument?


Code:
Dim pTmpLayer As ILayer
Dim i As Integer
For i = 1 To m_pLayers.Count
Set pTmpLayer = m_pLayers.Item(i)
If pTmpLayer Is pSearchedLayer Then
m_pLayers.Remove i

'I need to know the key of the item I've removed from the collection...
'Any Idea?

Exit For
End If
Next

Unable To Reference A Dictionary Item When The Key Exists ??
Hi all,

I have a dictionary called 'RecordBag' correctly defined and correctly populated a few lines earlier in my code. But when I reference an item in the dictionary directly like so...


Code:
fvars.Recordbag("Customer") = "Test String"


I get the error message...

'Compile error: Wrong number of arguments or invalid property assignment.'

OK says I - lets try this...


Code:
fvars.Recordbag("Customer").Item = "Test String"


I now get the error message ...

Run-Time error '424': Object Required.

Literally the line before my attempted equate I can do a print out of the dictionary and I get the following in format KEY 'space' ITEM

UID UID::RF::0::0
Ref Ref::RF::0::0
Customer Customer::CB::9999::0::0
OrderNo OrderNo::TB::9999::0
PackNo PackNo::TB::9999::0
MoistureContent MoistureContent::TB::9999::0
Commodity Commodity::CB::9999::0::0
Species Species::CB::9999::0::0
TimberProfile TimberProfile::CB::9999::0::0
Length Length::TB::9999::0
Quantity Quantity:D::9999::0
TargetCharge TargetCharge::TB::9999::0
BarCode BarCode::RF::0::0
PlantNumber PlantNumber::RF::0::0
TreatmentDate TreatmentDate::RF::0::0
CycleRef CycleRef::RF::0::0

... and intellisense shows that 'fvars.Recordbag("Customer")' does in fact equal 'Customer::CB::9999::0::0'

Has anyone got an idea of what may be going wrong here? It has me stumped. I have done a reboot of VB just but still no joy.

Thanks in advance

Checking If A Item Allready Exists In A Treeview
how to check if something allready exist in a treeview... i want it to check the key of the item

Checking For An Item In A Collection.
I used Thinkers Collection tutorial and made my own collection class.

Now, I'm adding "shifts" from work into the collection from a database. In the database, they have a unique shift number. But in the program they are displayed by date (for one employee at a time). It is possible to have two shifts on the same date, so when I'm adding the shifts to the collection, I cannot use the date as a key, because it's possible to have more then one with the same date. I do not want to use the unique shift number as the key, because I have no way to match the multiple dates that could exist, to the unique entries in the database.

So I figured I'd display any extra shifts in a day with a number after them:
May 4, 2006
May 4, 2006 (1)
etc...

I thought that when I assign the keys to the shifts, I could search the collection to see if that key already exists, and then create a new one if needed. Then when the user clicks on the details for the shift, the unique key will get the proper shift number, and retrieve the right details.

However, I cannot seem to find a way to see if the key already exists.

This is the code I already have....but it just overflows as the int gets too big. I figured if I set the key to something that didn't exist, then nothing would be returned, and I could catch that....but either that's not the case, or I'm checking wrong. Here is my code:

Code:
Dim shiftcount As Integer, keytoadd As String
'Check to see if this date already exists in the collection
keytoadd = ConvertYYYYMMDDtoLongDate(DbRecSet("date_in").value)
Set tempemployeeshift = employee_shifts.item(keytoadd)
shiftcount = 1
Do Until tempemployeeshift Is Nothing
Set tempemployeeshift = employee_shifts.item(ConvertYYYYMMDDtoLongDate(DbRecSet("date_in").value) & "(" & shiftcount & ")")
keytoadd = ConvertYYYYMMDDtoLongDate(DbRecSet("date_in").value) & "(" & shiftcount & ")"
shiftcount = shiftcount + 1
Loop

Here is the code of the item function of the tutorial:

Code:
Public Function Item(ByVal vKey As Variant) As EmployeeShift
' Variant allows for string key or long index
On Error GoTo ErrorHandler:
If Len(vKey) > 0 And Len(vKey) < 51 Then
Set Item = mcolEmployeeShifts.Item(vKey)
Else
Set Item = Nothing 'signal failure
Err.Raise vbObjectError + 10000, _
"EmployeeShiftCollection.EmployeeShifts", "Key value invalid"
End If
Exit Function
ErrorHandler:
If Err.Number = 5 Or Err.Number = 9 Then
Set Item = Nothing 'Item not found
Else
Err.Raise Err.Number, "EmployeeShiftsCollection.EmployeeShift", Err.Description
End If
End Function

Check For Item In Collection
Hi. I have a collection and all the items in it have keys specified. How can i check if there is an item using a key? Theres a possibility the app might try to add the same key twice. In this case i want to remove the old one first then add the new one.

Item Not Found In This Collection
I get this error message, "Item not found in this collection"
and this line of code is marked
(code)
Set FagIStudieØkten = Databasen.OpenRecordset("SELECT StudieØktPlanFag.***, StudieØktPlanFag.StudieØktPlanNr From StudieØktPlanFag WHERE (((StudieØktPlanFag.StudieØktPlanNr) = " & FinnStudieØktPlan("studieøktplanNr") & "));")
(/code)


And that is logical, because there are no items in that table, but why is VB giving me an error message just because there are no
items, I did not request any items. The sole purpose of the sql-sentence was to check if there was any?!

Item Cannot Be Found In The Collection..
Hello all. I've got a problem with a class module sub where I am trying to supply a value to a parameterized query in the text for a command. It seems like the command does not have the parameter added to the collection like it should be doing. I know it's got to be something simple that I just can't see. Any ideas????

Thanks...code sample below..
Public Sub GetWorkAreaDescription()
Dim rsDesc As Recordset
MsgBox "cmd is " & mcmdDesc.CommandText
mcmdDesc.Parameters(0) = msWorkArea
'This is the line with the problem. Item cannot be
found in the collection...
Set rsDesc = mcmdDesc.Execute
msDescription = rsDesc!Description
End Sub

Test Whether A Collection Contains An Item
I'd like to be able to test if a certain collection contains an item described by a string key, and if the item isn't there, to Add it.
How can I do this without causing an error?

Should We Clear Item In Collection
I have a question here.

Should we do this before terminate event fired?

VB Code:
Do While myCol.Count > 0Call myCol.Remove(1)LoopSet myCol = Nothing


or this is enough?
Set myCol = Nothing

And why so?






Added [RESOLVED] to thread title - Hack

Item Not Found In This Collection
I get error 3265 - Item not found in this collection when the following bit of code runs. The weird thing is, the field does exist. This is on an access databse. Any ideas what else could be causing this?

Thanks.



VB Code:
Data1.RecordSource = "user_settings"    Data1.Refresh     If IsNull(Data1.Recordset("userid")) Or Data1.Recordset("userid") = "" Then       MsgBox "No userid has been supplied."    Else       sUserid = Data1.Recordset("userid")    End If

Item Collection Properties
HI, anybody knows how to make something like this???

collection.item(1).property1=10

I did the collection part, and it works, but I don't know the proerties part.

Thanks!!!

Searching For An Item In A Collection
Hi,

This is along the same lines as my search through a MultiDimensional Array that I've been trying to make work.

I've decided to try the collection route instead, so here is my thought

I have a series of existing items in two collections


VB Code:
Dim EmpColl As New Collection ' For total payroll hours for all 3                                                     'weeksDim FNColl As New Collection ' For the ID number which is the                                               'unique key in the system  


I need to be able to update the EmpColl as new weeks of the payroll are added, but I'm not exactly sure what I need to do to search the Collection for the specified item.

I'm trying this


VB Code:
'FileNum is the unique key.  The Employee's payroll ID.Dim FileNum As SingleDim Found As BooleanDim Hours As Single 'Employees hours for one payroll week For Each Item in FNColl     If FNColl.Item(Item) = FileNum Then           Found = True           EmpColl.Item(FNColl.Item) = EmpColl.Item(FNColl.Item) _           + Hours     End IfNext If Found = False Then     FNColl.Add FileNum, FileNum     EmpColl.Add Hours, FileNumEnd If


Is the logic in this right? I'm not sure whether specifying the Item as the key in this For Each statement is the right thing to do.

Thanks one and all for your help,

Tojam

Removing Item From Collection
Dim b As Bookmark
If collbookmarks.Count <> 0 Then
MsgBox "Nothing to remove"
Else
Set Favs = New bkmarks
Favs.Remove Index ' whatever the index number you want removed

Passing Item Of A Collection By Val
Hi all,

How can i pass item of a collectiion by val.

For e.g.
Dim cola As Collection
Dim colb As Collection
Set cola = New Collection
Set colb = New Collection

Dim rstA As ADODB.Recordset
Set rstA = New ADODB.Recordset

rstA.Fields.Append "Nm", adChar, 10
rstA.Open
rstA.AddNew
rstA.Fields(0) = "ABC"
rstA.Update

cola.Add rstA
Set colb = cola
colb.Item(1).Fields(0) = "DEF"

Debug.Print cola.Item(1).Fields(0) 'it prints DEF


How can i change the item in colb while not affecting cola?

Thank You!

Change To Item Key In A Collection
I need to Change to Item key in a collection for all items remaining after I remove an item from it.

Is there a way to do Item.key = XXX ?

 

Changing The Value Of A Particular Item In A Collection?
Hi there folks! Now, suppose that I've a collection object like this :

Dim m_MyCol as New Collection



Private Sub Form_Load()
m_MyCol.Add "Item1"
End Sub[/ccode]


Private Sub Command1_Click()
'try to change the value of the item
'that we added in Form_Load()
m_MyCol.Item(1) = "ItemXeon!"
End Sub



But the thing is that the compiler gave me an error! I know it's this line that causes the error :

m_MyCol.Item(1) = "ItemXeon!"




In any case, how do I change the value of a particular item in a Collection?
Is it even possible? Thanks a lot! :--D

The lyric of the shattering roar of Xeon(Berserker Mode) :
BWOAR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Passing Item Of A Collection By Val
Hi all,

How can i pass item of a collectiion by val.

For e.g.
Dim cola As Collection
Dim colb As Collection
Set cola = New Collection
Set colb = New Collection

Dim rstA As ADODB.Recordset
Set rstA = New ADODB.Recordset

rstA.Fields.Append "Nm", adChar, 10
rstA.Open
rstA.AddNew
rstA.Fields(0) = "ABC"
rstA.Update

cola.Add rstA
Set colb = cola
colb.Item(1).Fields(0) = "DEF"

Debug.Print cola.Item(1).Fields(0) 'it prints DEF


How can i change the item in colb while not affecting cola?

Thank You!

Getting The Index Of A Collection Item.
Is it possible to get the Index of a collection item if you know the key it was added under?

example:

dim Mycol as new collection
Mycol.Add "keyboard","bob"
Mycol.Add "monitor","peter"
Mycol.Add "desk","joe"

I want to know that "monitor" is the second item in the list by using the key "peter" can this be done?

Jean-Guy

How To Extract The Key Of An Item In A Collection
Could someone tell me how to extract the key of an item in a collection?

Dim mcol as new Collection
mcol.Add "item1", "key1"

Then I passed this collection to an ActiveX DLL.
The ActiveX DLL doesn't know the keys used for each item the collection.
I know I can use an index like : debug.print col(index). But is there a way to extract the keys used for each item in the collection instead of using an index?

Thank you

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