ByVal (keyword)

Syntax

...ByVal parameter...

Description

Forces a parameter to be passed by value rather than by reference.

Comments

The ByVal keyword can appear before any parameter passed to any function, statement, or method to force that parameter to be passed by value. Passing a parameter by value means that the caller cannot modify that variable's value.

Enclosing a variable within parentheses has the same effect as the ByVal keyword:

  Foo ByVal i      'Forces i to be passed by value.

  Foo(i)           'Forces i to be passed by value.

 

When calling external statements and functions (that is, routines defined using the Declare statement), the ByVal keyword forces the parameter to be passed by value regardless of the declaration of that parameter in the Declare statement. The following example shows the effect of the ByVal keyword used to passed an Integer to an external routine:

  Declare Sub Foo Lib "MyLib" (ByRef i As Integer)

  i% = 6

  Foo ByVal i%    'Pass a 2-byte Integer.
  Foo i%        'Pass a 4-byte pointer to an Integer.

Since the Foo routine expects to receive a pointer to an Integer, the first call to Foo will have unpredictable results.

Example

This example demonstrates the use of the ByVal keyword.

Sub Foo(a As Integer)

  a = a + 1
End Sub

Sub Main()

  Dim i As Integer
  i = 10
  Foo i
  MsgBox "The ByVal value is: " & i  'Displays 11 (Foo changed the value).
  Foo ByVal i
  MsgBox "The ByVal value is still: " & i    'Displays 11 (Foo did not change the value).
End Sub

See Also

() (keyword), ByRef (keyword).

More information

B