Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing an array to a procedure

Status
Not open for further replies.

thomascd

Programmer
Mar 20, 2002
29
0
0
GB
Hello,
I can't succed to pass an array by reference to a procedure and modify the values directly. Can you tell me what is wrong in my code ?

Sub main()
Dim Array1(2, 1) As Long
Modify (Array1())
End Sub

Sub Modify(Array2 As Long)
For I = 0 To 2
Array2(I, 0) = I
Array2(I, 1) = I + 1
Next I
End Sub
 
Don't you need brackets after array2, ie array2(), in the parameter of the function?
 
Still not working with brackets, I get 'argument must be byref'
 
Try:

Sub Modify(ByRef Array2 As Long)

fingers crossed that should do it.
 
Normally, I would think of ParamArray. Fooled around a bit and found this would work for you, also. Forgive me for changing i to TheLoop.

Code:
Sub Modify(Array2 as variant)
Dim TheLoop As Integer
For TheLoop = 0 To 2
Array2(TheLoop, 0) = TheLoop
Array2(TheLoop, 1) = TheLoop + 1
Next TheLoop
End Sub

What Help says:
ParamArray:
Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. The ParamArray keyword can't be used with ByVal, ByRef, or Optional.
 
well, I am still getting the same error in the sub main.
 
Start with a fresh workbook, fresh module. Try the following code:

Code:
Sub main()
Dim Array1(2, 1) As Long
Modify (Array1())
End Sub

Sub Modify(Optional Array2 As Variant)
Dim TheLoop As Integer
For TheLoop = 0 To UBound(Array2)
Array2(TheLoop, 0) = TheLoop
Array2(TheLoop, 1) = TheLoop + 1
Next TheLoop
End Sub
 
The error message is misleading. The error is in the calling procedure wich doesn't accept brackets around the parameters. So to fix it, keep the brackets after array2, but remove them around Array1 in the calling procedure.

It should look like:
Code:
Sub main()
   Dim Array1(2, 1) As Long
   Modify Array1()
End Sub

Sub Modify(Array2() As Long)
   For I = 0 To 2
    Array2(I, 0) = I
    Array2(I, 1) = I + 1
   Next I
End Sub

Nath
 
Thanks for your persistence, but while I am not getting an error, the array is not modified when I return from the function.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top