CodeItBetter Programming Another VB Programming Blog

What exactly does ByVal and ByRef mean and when do you use it?

Posted on January 4, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'Coding Basics - What exactly does ByVal and ByRef mean and when do you use it?
'ByVal means to pass just the Value of a Variable, where as 
'ByRef means to pass a Reference to the Variable itself.

'For Example,

Function AddOne(ByVal iNum As Integer) As Integer
    iNum = iNum + 1
    AddOne = iNum
End Function
 
Sub Main()
    Dim I As Integer
    I = 1
    Debug.Print AddOne(I)
    Debug.Print I
End Sub
 
'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
 
Sub Main()
    Dim I As Integer
    I = 1
    Debug.Print AddOne(I)
    Debug.Print I
End Sub
 
'This would Print 2, then 2 again as a Refernce to the Actual 
'Variable was passed, so changing iNum was like Changing I itself.

'If ByVal/ByRef isn't specified, default is ByRef
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.