Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何通过分离函数更改VBA集合值_Vba_Function_Collections - Fatal编程技术网

如何通过分离函数更改VBA集合值

如何通过分离函数更改VBA集合值,vba,function,collections,Vba,Function,Collections,我试图在一个单独的函数中更改字符串集合的一些值。据我所知,在将集合用作函数参数时,集合被视为默认集合。不幸的是,我在运行以下代码时出现以下错误: 需要运行时错误“424”对象 编辑: 我找到了一个使用字典的解决方案: Private Function MyFunc1() Dim b As Collection: Set b = New Collection b.Add "test1" b.Add "test2" Call myFunc2(b) End Functi

我试图在一个单独的函数中更改字符串集合的一些值。据我所知,在将集合用作函数参数时,集合被视为默认集合。不幸的是,我在运行以下代码时出现以下错误:

需要运行时错误“424”对象

编辑: 我找到了一个使用字典的解决方案:

Private Function MyFunc1()
    Dim b As Collection: Set b = New Collection
    b.Add "test1"
    b.Add "test2"
    Call myFunc2(b)
End Function

Private Function myFunc2(c As Collection)
    c.Remove 1
    c.Add "hello", , 1
End Function

我认为如果你愿意使用字典对象,你可以这样做

Function MyFunc1()

Dim b As New Scripting.Dictionary

   b.Add key:="1", Item:="test1"
   b.Add key:="2", Item:="test2"

   ' Example Call to update function
   Set b = updateDictWithStringValue(b, "1", "hello")

End Function

Public Function updateDictWithStringValue(d As Dictionary, key As String, value As String) As Dictionary

d.Remove key
d.Add value, key
Set updateCollectionWithStringValue = d

End Function

您需要包含对Microsoft脚本运行时的引用

MyFunc1
应该是一个子函数,而不是一个函数。如果我没有弄错的话,集合中的项是只读的。我认为@JosephC是正确的-您可以使用字典来实现这一点,尽管JosephC是正确的。您的错误与将集合传递给函数(或子函数)无关,当您在
MyFunc1
中写入
b(1)=“hello”
时,将收到相同的错误。看^^我会说,我几乎是个十足的傻瓜
Function MyFunc1()

Dim b As New Scripting.Dictionary

   b.Add key:="1", Item:="test1"
   b.Add key:="2", Item:="test2"

   ' Example Call to update function
   Set b = updateDictWithStringValue(b, "1", "hello")

End Function

Public Function updateDictWithStringValue(d As Dictionary, key As String, value As String) As Dictionary

d.Remove key
d.Add value, key
Set updateCollectionWithStringValue = d

End Function