I want to pass an array to a function and the "books" say it can't be done. Is there a workaround? Can I pass a pointer instead?
Thanks
Printable View
I want to pass an array to a function and the "books" say it can't be done. Is there a workaround? Can I pass a pointer instead?
Thanks
I wasn't aware that it "couldn't be done"!
Just declare the input parameter type as variant
Code:Option Explicit
Private Sub Command1_Click()
Dim anArray(5) As Integer
Dim possible As Boolean
anArray(0) = 0
anArray(1) = 1
anArray(2) = 2
anArray(3) = 3
anArray(4) = 4
possible = CanDoIt(anArray)
MsgBox possible
End Sub
Private Function CanDoIt(arr As Variant) As Boolean
'hopefully your funtion will do somthing more useful
Debug.Print arr(0)
Debug.Print arr(1)
Debug.Print arr(2)
Debug.Print arr(3)
Debug.Print arr(4)
CanDoIt = True
End Function
Even without the variant datatype there is no problem.
I stole Mark's code for this purpose:
Option Explicit
Private Sub Command1_Click()
Dim anArray(5) As Integer
Dim possible As Boolean
anArray(0) = 0
anArray(1) = 1
anArray(2) = 2
anArray(3) = 3
anArray(4) = 4
possible = CanDoIt(anArray)
MsgBox possible
End Sub
Private Function CanDoIt(arr() As Integer) As Boolean
'hopefully your funtion will do somthing more useful
Debug.Print arr(0)
Debug.Print arr(1)
Debug.Print arr(2)
Debug.Print arr(3)
Debug.Print arr(4)
CanDoIt = True
End Function
Frans C is right of course
however, if you want to pass an array out of a function you need to declare it as variant
eg:
Private Function CanDoIt(arr() As Integer) As Variant
.......
end if
So if I set possible as
dim possible() as integer
then
possible = CanDoIt(anArray)
would set the array correctly for possible assuming that we set
Private Function CanDoIt(arr() As Integer) As Variant
?
So then possible and anArray would be the same?
netSurfer, I don't think so!
I haven't tried it but you would probably get a type mismatch
you can....
dim possible as variant
possible = CanDoIt(anArray)
If IsArray(possible ) Then
msgbox "Yep! possible is an array!"
End If
Private Function CanDoIt(arr() As Integer) As Variant
dim xxx() as integer
'do something meaningful
'including demensioning xxx
CanDoIt = xxx
end if
Cool! I'll have to try that out - it would come in handy. Thanks.
With VB 6 you can return an array, like:
Function MyFunc() As Integer()