VBScript:如何利用函数返回的dictionary对象?
我正在尝试从函数返回字典。我相信该函数工作正常,但我不确定如何使用返回的字典 以下是我职能的相关部分:VBScript:如何利用函数返回的dictionary对象?,vbscript,Vbscript,我正在尝试从函数返回字典。我相信该函数工作正常,但我不确定如何使用返回的字典 以下是我职能的相关部分: 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.Fi
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
Set GetSomeStuff = stuff
如何调用此函数并使用返回的字典
编辑:我试过这个:
Dim someStuff
someStuff = GetSomeStuff
及
当我尝试访问某些内容时,会出现错误:
Microsoft VBScript runtime error: Object required: 'GetSomeStuff'
编辑2:在函数中尝试此操作:
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
Set GetSomeStuff = stuff
导致此错误的原因:
Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment.
您是否尝试过:
Dim returnedStuff
Set returnedStuff = GetSomeStuff()
然后“For Each”遍历字典?这里有一个使用字典的例子(尽管对于VB6来说,其要点是相同的!)。您是否尝试过使用
设置GetSomeStuff=stuff
在函数的最后一行?我不太确定你的问题是什么,所以我做了一些实验 似乎您没有注意到,要将引用指定给对象,必须使用
set
,即使对于返回值:
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
我缺少Set getsomething=stuff和Set d=getsomething的组合。谢谢@user66001我不认为尝试编辑别人的代码(或答案!)(除了诸如拼写错误修复、URL更新等任务之外)是一个好主意,尤其是对于这样的小问题,尤其是当你错了的时候。。。如果将
d
替换为函数名,则在每次出现时调用该函数。缺少()
可能会误导您使用像变量一样的函数调用。我不认为每次都要创建东西
结构有什么意义。对于这样一个简单的演示,它在这里并不重要,但在真正的程序中它可能很重要。@PhiLho-我的错误。对不起(我认为这在原则上很重要,所以删除了我的错误信息)。