Passing Arguments to Procedure
You can pass arguments to the sub procedure or function procedure using two different methods:
(1) Passing arguments by value (ByVal)
(2) Passing arguments by reference (ByRef)
(1) Passing arguments by Value (ByVal)
This method of passing arguments to the sub procedure or function procedure works as follow:
(1) First it will examine number of arguments that are passed at the time of calling the sub procedure or function procedure.
(2) If passed arguments match with procedure definition then it creates that much new variables and copies value of original variables into newly created variables.
(3) So now onwards the sub procedure or function procedure works with the newly created variables instead of original variables. So any changes that are made to the variables inside procedure do not affect the original variables.
Thus the limitation of passing arguments by value is that you can not modify the contents of the original variables in the sub procedure or function procedure.
By default the arguments are passed by value. You can use ByVal keyword to explicitly pass argument by value.
(2) Passing arguments by reference (ByRef)
This method of passing the arguments to the sub procedure or function procedure works slightly different then the method of passing arguments by value.
(1) First it will examine number of arguments that are passed at the time of calling the sub procedure or function procedure.
(2) If passed arguments match with procedure definition then instead of creating new variables only references (address) of original variables are passed.
(3) So the sub procedure or function procedure works with the original variables.
Thus using this method you can modify the contents of the original variable in the sub procedure or function procedure.
By default the arguments are passed by value. If you want to pass arguments by reference then use keyword ByRef before declaration of each argument in the procedure definition.
Example of How to Pass Arguments by Reference
Design an application using sub Procedure to swap two numbers.
Step 1: Design a form as shown below:
Step 2: Now set properties of various controls as given below:
| Control Name | Property Name | Value |
Form1 |
Text |
Swap Two Numbers |
Label1 |
Text |
Number1: |
Label2 |
Text |
Number2: |
TextBox1 |
Name |
txtNumber1 |
TextBox2 |
Name |
txtNumber2 |
Button1 |
Name |
cmdSwap |
Text |
Swap Numbers |
|
Label3 |
Text |
Number1: |
Label4 |
Text |
Number2: |
Label5 |
Name |
lblNumber1 |
Text |
__ |
|
Label6 |
Name |
lblNumber2 |
Text |
__ |
Step 3: First define a sub procedure named Swap as given below:
Dim c As Integer
c = a
a = b
b = c
End Sub
Step 4: Now double click on Swap Numbers Button and write following code to call sub procedure.
Dim b As Integer
a = Val(txtNumber1.Text)
b = Val(txtNumber2.Text)
swap(a, b)
lblNumber1.Text = a
lblNumber2.Text = b