Skip to content
Visual Basic

Sub and Function Procedures

Define Sub (no return) and Function (returns value).

By EZ4Code Team
subfunctionprocedure

Code

' Sub: no return value
Sub Greet(ByVal name As String)
    Console.WriteLine($"Hello, {name}!")
End Sub

' Function: returns a value
Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
    Return a + b
End Function

' ByRef (pass by reference)
Sub Increment(ByRef x As Integer)
    x += 1
End Sub

' Optional parameters
Function Power(ByVal base As Double, Optional ByVal exp As Double = 2) As Double
    Return Math.Pow(base, exp)
End Function

' Usage
Greet("Alice")
Dim sum As Integer = Add(3, 4)
Dim n As Integer = 5
Increment(n)  ' n is now 6
Dim sq As Double = Power(5)    ' 25
Dim cb As Double = Power(5, 3) ' 125

Explanation

Sub performs actions; Function returns a value. ByVal is default (copy); ByRef allows mutation. Optional parameters have defaults. VB supports string interpolation with $ (VS 2015+). Always use ByVal unless you need ByRef — mutable arguments are a common bug source.

More Visual Basic Snippets