tags:

views:

2708

answers:

4

I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary.

Here is the relevant part of my function:

Function GetSomeStuff()
  '
  ' Get a recordset...
  '

  Dim stuff
  Set stuff = CreateObject("Scripting.Dictionary")
  rs.MoveFirst
  Do Until rs.EOF
    stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value
    rs.MoveNext
  Loop

  GetSomeStuff = stuff
End Function

How do I call this function and use the returned dictionary?

EDIT: I've tried this:

Dim someStuff
someStuff = GetSomeStuff

and

Dim someStuff
Set someStuff = GetSomeStuff

When I try to access someStuff, I get an error:

Microsoft VBScript runtime error: Object required: 'GetSomeStuff'

EDIT 2: Trying this in the function:

Set GetSomeStuff = stuff

Results in this error:

Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment.
A: 

Have you tried:

Dim returnedStuff
Set returnedStuff = GetSomeStuff()

Then "For Each" iterating over the dictionary? There's an example of using the Dictionary (albeit for VB6, the gist of it is the same though!) here.

Rob
+1  A: 

Have you tried doing
set GetSomeStuff = stuff
in the last line of the function?

tloach
+6  A: 

I wasn't too sure of what was your problem, so I experimented a bit.

It appears that you just missed that to assign a reference to an object, you have to use set, even for a return value:

Function GetSomeStuff
  Dim stuff
  Set stuff = CreateObject("Scripting.Dictionary")
    stuff.Add "A", "Anaconda"
    stuff.Add "B", "Boa"
    stuff.Add "C", "Cobra"

  Set GetSomeStuff = stuff
End Function

Set d = GetSomeStuff
Wscript.Echo d.Item("A")
Wscript.Echo d.Exists("B")
items = d.Items
For i = 0 To UBound(items)
  Wscript.Echo items(i)
Next
PhiLho
I was missing the combination of Set GetSOmeStuff = stuff and Set d = GetSomeStuff. Thanks!
aphoria
A: 

Great help!!! I had the same problem ;-) THANKS

Stephan