keep recursion result (a dynamic array) without using global variable

L

lvcha.gouqizi

Hi there,

I write a recursive subroutine which can be called by several macros
from different modules. I want to keep a dynamic array as a result of
this recursive code. I define an array as a global variant like:
Dim result() as Variant
Redim result(1 to 5, 1 to 20)

And whenever the recursion gets a correct answer, I add it to the
array. The recursion works well when called by its own module. But when
code from other module calls it, I am confused about how to deal with
the global array? Is there any way to keep recursion results without
using global variable?

Can I use a dynamic array parameter and an integer paramter to save its
increasing size like the following?

sub myrecursion(dynArr() as variant, dynArrLen as integer)

Thanks.
lvcha
 
T

Tom Ogilvy

you can only redim the last dimension in you want to preserve the results.

If you want to accumulate the results from many separate calls, then a
global variable/array seems like a good choice.

The alternative would be to pass the array as an argument, but then all the
calls would have to come from a the source of the array.
 
L

lvcha.gouqizi

well, thanks. I just take the parameter way to deal with it and it
works well.

Another confusion without too much relation to the above is when I
define a function with a string parameter, can I give an elememnt from
a variant to that parameter? It seems always showing me the "ByRef
argument type mismatch" msgbox.

How do I force the element from a variant be string type?

Here is what the function seems like
___________________________
sub myFunc(str as string)
....
end sub
----------------------------------------------

and here is what I use to call myFunc
____________________________
Dim path() variant
Redim path(1 to 3, 1 to 100)
....
Redim Preserve path(1 to 3, 1 to 20)
myFunc(path(1, 2))



thanks!
lvcha
 
T

Tom Ogilvy

The easiest would probably to change the declaration of myFunc to look for a
variant

Sub MyFunc(sStr as Variant)

[ str is aVBA function, don't use it for a variable name ]

Sub Main()
Dim sStr As String

sStr = "Abcd"
res = MyFunc(sStr)
Debug.Print res
End Sub

Public Function MyFunc(v As Variant)
Debug.Print TypeName(v)
MyFunc = v & "efgh"
End Function

works. Or I could leave it the way you have it and do the conversion in the
argument list

Sub Main()
Dim sStr As Variant

sStr = "Abcd"
res = MyFunc(CStr(sStr))
Debug.Print res
End Sub

Public Function MyFunc(v As String)
Debug.Print TypeName(v)
MyFunc = v & "efgh"
End Function

I tested both approaches and they work.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top