Understanding ByRef in Visual Basic

In both Visual Basic and Visual Basic .NET, the keyword ByRef is used to pass arguments by reference. This means the called procedure receives a reference to the original variable—not a copy—allowing the procedure to change the variable directly.

What Does ByRef Mean?

When a parameter is passed ByRef:

Classic Visual Basic (VB6) Example


Private Sub ChangeNumber(ByRef x As Integer)
    x = x + 10
End Sub

Private Sub Command1_Click()
    Dim num As Integer
    num = 5
    Call ChangeNumber(num)
    MsgBox num   ' Shows 15
End Sub
    

Because x was passed by reference, modifying it inside the procedure also changes num.

VB.NET Example


Sub ChangeText(ByRef message As String)
    message = "Modified inside procedure"
End Sub

Sub Main()
    Dim txt As String = "Original text"
    ChangeText(txt)
    Console.WriteLine(txt)   ' Outputs: Modified inside procedure
End Sub
    

The original variable txt is changed because it was passed ByRef.

ByRef vs ByVal

Understanding the difference between ByVal and ByRef is essential for controlling how data flows in VB procedures.

Keyword Meaning Does the procedure modify the original variable?
ByVal Passes a copy of the variable No
ByRef Passes a reference to the original variable Yes

When Should You Use ByRef?


PeatSoft - VB.NET - Educational Reference - AI