Example - Passing Arguments by Reference
This section provides a tutorial example on how to pass arguments by reference to swap values passed through procedure arguments.
To see how passing arguments by reference works, I wrote the following example, function_swap_by_ref.html:
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
document.writeln("Test 1: Swapping two literals by reference")
document.writeln(" Before Sub: " & "Apple" & " | " & "Orange")
Call SwapByRef("Apple", "Orange")
document.writeln(" After Sub: " & "Apple" & " | " & "Orange")
vFirst = "Dog"
vSecond = "Cat"
document.writeln("Test 2: Swapping two variables by reference")
document.writeln(" Before Sub: " & vFirst & " | " & vSecond)
Call SwapByRef(vFirst, vSecond)
document.writeln(" After Sub: " & vFirst & " | " & vSecond)
Sub SwapByRef(ByRef vLeft, ByRef vRight)
vTemp = vLeft
vLeft = vRight
vRight = vTemp
document.writeln(" In Sub: " & vLeft & " | " & vRight)
Here is the output:
Test 1: Swapping two literals by reference
Before Sub: Apple | Orange
In Sub: Orange | Apple
After Sub: Apple | Orange
Test 2: Swapping two variables by reference
Before Sub: Dog | Cat
In Sub: Cat | Dog
After Sub: Cat | Dog
Here are my notes about this example:
- Test 1 shows that data literal can be used for a "ByRef" argument.
By you will not be able to receive the change done by the subroutine.
- Test 2 shows that using variable for a "ByRef" argument let us receive the change
done by the subroutine. After the subroutine call, values in vFirst and vSecond have been swapped.
- "ByRef" keyword is optional.
Table of Contents
About This Book
Introduction of VBScript - Visual Basic Scripting Edition
Variant Data Type, Subtypes, and Literals
Numeric Comparison Operations and Logical Operations
String Operations - Concatenation and Comparison
Variable Declaration and Assignment Statement
Expression and Order of Operation Precedence
Statement Syntax and Statement Types
Array Data Type and Related Statements
Array References and Array Assignment Statements
Conditional Statements - "If ... Then" and "Select Case"
Loop Statements - "For", "While", and "Do"
►"Function" and "Sub" Procedures
What Is a Procedure?
"Function" Statement and Function Call
Function Procedure Example
"Sub" Statement and Subroutine Call
Sub (Subroutine) Procedure Example
Passing Arguments to Procedures
►Example - Passing Arguments by Reference
Example - Passing Arguments by Value
Passing Arrays as Arguments
Variable Scope in Procedures
Example - Variable Scope in Procedures
Inspecting Variables Received in Procedures
Error Handling Flag and the "Err" Object
Regular Expression Pattern Match and Replacement
scrrun.dll - Scripting Runtime DLL Library
Creating Your Own Classes
IE Web Browser Supporting VBScript
IIS ASP Server Supporting VBScript
WSH (Windows Script Host)
PDF Printing Version