Pass by reference?

  • Thread starter Thread starter Laurel
  • Start date Start date
L

Laurel

Is there a way to put a parameter in a function and let the caller see the
changed value? In another language I would do it by declaring the parameter
this way as_StringParam by reference.

If not, how do I get at more than one result in a function or sub? I have
a function which returns a value I want, but I'd also like to get at the
values in an array that it creates when it does it's thing. I'd like to
make it a reference parameter, but can't see a way to do it in VB for
applications.
 
By Reference is the default behaviour. Try it, and see whether it does what
you want.

For instance:

Sub Sub1()
Dim A As Integer
Dim B As Integer

A = 5
Debug.Print "A = " & A
B = MyFunction(A)
Debug.Print "A = " & A & ", B = " & B
End Sub

Function MyFunction(Passed As Integer) As Integer
Passed = Passed * 2
MyFunction = 8
End Function

If you go to the Immediate window and run Sub1, you'll see:

Sub1
A = 5
A = 10, B = 8

If you want to be explicit, you can declare the parameters as ByRef or ByVal
in the declaration:

Function MyFunction(ByRef Passed As Integer) As Integer

or

Function MyFunction(ByVal Passed As Integer) As Integer

In fact, if you use the second declaration, what you'll see when running it
is

Sub1
A = 5
A = 5, B = 8
 
As you said, Works like a charm

Thank you RayC

Douglas J. Steele said:
By Reference is the default behaviour. Try it, and see whether it does what
you want.

For instance:

Sub Sub1()
Dim A As Integer
Dim B As Integer

A = 5
Debug.Print "A = " & A
B = MyFunction(A)
Debug.Print "A = " & A & ", B = " & B
End Sub

Function MyFunction(Passed As Integer) As Integer
Passed = Passed * 2
MyFunction = 8
End Function

If you go to the Immediate window and run Sub1, you'll see:

Sub1
A = 5
A = 10, B = 8

If you want to be explicit, you can declare the parameters as ByRef or ByVal
in the declaration:

Function MyFunction(ByRef Passed As Integer) As Integer

or

Function MyFunction(ByVal Passed As Integer) As Integer

In fact, if you use the second declaration, what you'll see when running it
is

Sub1
A = 5
A = 5, B = 8
 
Thanks. That just never crossed my mind. But I also appreciate the
explanation of explicit declarations.
 

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

Back
Top