What exactly does ByVal mean and when do you use it?
------------------
Tom Young, 14 Year Old
tom@e-bizinternet.com
ICQ: 15743470
AIM: TomY10
PERL, JavaScript and VB Programmer
Printable View
What exactly does ByVal mean and when do you use it?
------------------
Tom Young, 14 Year Old
tom@e-bizinternet.com
ICQ: 15743470
AIM: TomY10
PERL, JavaScript and VB Programmer
ByVal means to pass just the Value of a Variable, where as ByRef means to pass a Reference to the Variable itself, eg.
Function AddOne(ByVal iNum As Integer) As Integer
iNum = iNum + 1
AddOne = iNum
End Function
Dim I As Integer
I = 1
Debug.Print AddOne(I)
Debug.Print I
This would Print 2, then 1 as only the Value 1 is passed to the Function so the value of I never actually changes.
Function AddOne(ByRef iNum As Integer) As Integer
iNum = iNum + 1
AddOne = iNum
End Function
Dim I As Integer
I = 1
Debug.Print AddOne(I)
Debug.Print I
This would Print 2, then 2 again as a Refernce to the Actual Variable was passed, so changing iNum was like Changing I itself.
------------------
Aaron Young
Analyst Programmer
aarony@redwingsoftware.com
adyoung@win.bright.net
In addition, some API functions really mess up if you have to pass something ByVal and you pass it ByRef.
If you have an API function which includes a ByRef argument, and you want to pass it ByVal, then you don't need to change it in the declaration. You can use it in code, for example:
The SendMessage API has a ByRef argument, the last one: (ByRef) lParam As Any (If ByVal/ByRef isn't specified, default is ByRef). For some messages, you want to pass this ByVal. You can do it like this:
Call SendMessage(SomeHandle, WM_SETTEXT, 0, ByVal "New text")
In this sample, if you don't include the ByVal, then USER32.DLL decides it's a lot of fun to convert "New text" to some other totally random string.
This was just a sample, you can do it in other places as well.
------------------
Yonatan
Teenage Programmer
E-Mail: RZvika@netvision.net.il
ICQ: 19552879
[This message has been edited by Yonatan (edited 10-04-1999).]
What happens if you make you own function without any ByRef or ByVal? What is the default?
------------------
Tom Young, 14 Year Old
tyoung@stny.rr.com
ICQ: 15743470
AIM: TomY10
PERL, JavaScript and VB Programmer
ByVal is the default if you dont specify either
Actually ByRef is the default...
------------------
Yonatan
Teenage Programmer
E-Mail: RZvika@netvision.net.il
ICQ: 19552879