VBA
Discuss AutoCAD ActiveX and VBA (Visual Basic for Applications) questions here.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Troubles with ByRef and ByVal in VBA

3 REPLIES 3
Reply
Message 1 of 4
Anonymous
420 Views, 3 Replies

Troubles with ByRef and ByVal in VBA

I cant figure why this didn't work:

Public Sub MainAppeal()
Dim Var As Integer
Var = 1
Apelat (Var)
MsgBox Var
End Sub

Public Sub Apelat(ByRef arg As Integer)
arg = arg + 1
End Sub

Variable Var should become 2, isn't it?
Is there a restriction in VBA or I don't know how to use.
3 REPLIES 3
Message 2 of 4
Anonymous
in reply to: Anonymous

Good morning Mihai,

> Is there a restriction in VBA or I don't know how to use.
The latter seems to be the case, sorry.

IMHO there are 2 possibilities:
First: have the Apelat sub to be a function. A function returns a value (or
object ...), a sub doesnt.

Public Sub MainAppeal()
Dim Var As Integer
Var = 1
Var = Apelat(Var)
MsgBox Var
End Sub

Public Function Apelat(ByRef arg As Integer)
Apelat = arg + 1
End Function

second: you may declare Var to be public and use the Apelat sub to change
Var directly.

Public Var As Integer

Public Sub MainAppeal()
Var = 1
Apelat
MsgBox Var
End Sub

Public Sub Apelat()
Var = Var + 1
End Sub

For Byval vs. ByRef see the Help file -do a search for "byval", theres a
topic named "efficient handling of arguments" or something like that (I have
the german version).
Message 3 of 4
Anonymous
in reply to: Anonymous

> Variable Var should become 2, isn't it?
> Is there a restriction in VBA or I don't know how to use.

Remove the parens in your call to Apelat and everything will work as
exepcted. This is a case of VB/A's flexibility getting in the way.
Consider this:

Apelat Var
Call Apelat(Var)

Both yield the same result. However, this does not:

Apelat (Var)

When you surround a parameter with parens and don't use the Call
keyword, VB/A passes a copy of that parameter. So even though you
specified the parameter is to be pass ByRef, you're essentially passing
ByVal as the copy is sent and modified, leaving the original untouched.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
Message 4 of 4
Anonymous
in reply to: Anonymous

Thanks Frank. It takes a little to understand that is about calling method but now you confirm that. Unfortunately, this is not mentioned in my online help, so I have to keep this in mind |:(.

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk Design & Make Report

”Boost