Software Development

VB6 Tip: Understanding the importance of ByVal and ByRef keywords

Defining whether procedures are passed by reference or value is an essential part of almost every VB program.

Procedures are an essential part of almost every VB program. When you define a procedure, whether it's a Function or a Sub procedure, you need to decide whether the procedure arguments are passed by reference or by value.

What difference does it make?

VB's default is to pass arguments by reference. You can include the ByRef keyword in an argument list if desired but, because this is the default, it has no effect:

Sub Foo(ByRef Arg1 As Integer, ByRef Arg2 As String)

When an argument is passed by reference, the procedure is passed the address of the argument variable (in other words, a reference to the variable):

Dim Total as Integer
Call MySub(Total)

In this example, MySub receives a reference to Total. The practical consequence of this is that code in MySub can change Total. Here's an example. First, the procedure:

Sub MySub(Total As Integer)
    Total = 50
End Sub

Now the code that calls the procedure:

Dim Total As Integer
Total = 100
Call MySub(Total)

After this code executes, the variable Total equals 50 because the code in the procedure changed its value.

To pass an argument by value, use the ByVal keyword:

Sub MySub(ByVal Total As Integer)

When you use ByVal, the procedure is passed a copy of the argument variable and not a reference to the argument variable itself. Code in the procedure cannot change the variable's value.

Sub MySub(ByVal Total As Integer)
    Total = 50
End Sub

Now the code that calls the procedure:

Dim Total As Integer
Total = 100

Call MySub(Total)

After this code executes, Total is still equal to 100.

Note that array arguments and user-defined type arguments cannot be passed ByVal. Also, using ByVal or ByRef doesn't have any effect when the argument is a literal constant--only when it's a variable.

For most procedures, the default ByRef argument passing is fine. You can use ByVal when you want to ensure that code in the procedure cannot change the variable that was passed as an argument. You also must use ByVal when declaring Windows API and other DLL functions for use in your programs.

Peter Aitken has been programming with Visual Basic since Version 1.0. He has written numerous books and magazine articles on Visual Basic and other computer and programming topics.

1 comments
kebekebe
kebekebe

I need to read values from an ms access table to VB Combobox Please assist with the relevent coding.

Editor's Picks