Coding · Programming languages
Visual Basic .NET tutorial for beginners
Short answer
Visual Basic .NET (VB.NET) is an object-oriented, statically typed language for the .NET platform with English-like keywords such as Dim, If ... Then ... End If and For ... Next. It is not case-sensitive and uses the same .NET libraries as C#. Create a project with dotnet new console -lang VB and run it with dotnet run. VBA, the macro language inside Microsoft Office, is an older relative with similar syntax.
What Visual Basic .NET is and who uses it
VB.NET is the .NET successor of classic Visual Basic (VB6). It compiles to the same intermediate language as C#, so the two languages can share libraries and even be mixed in one solution. It is used mainly for Windows desktop applications (Windows Forms, WPF), internal business tools, ASP.NET web applications and the maintenance of existing VB code bases.
Microsoft continues to support Visual Basic on modern .NET, but it has said that it does not plan to evolve the language with major new features; new .NET features usually appear in C# first. For a new project without existing VB code, C# is the more common choice, but VB.NET remains a readable language for learning programming and for business software.
Install and run Hello, world
Install the .NET SDK (Windows, macOS or Linux). Visual Studio on Windows also includes Visual Basic templates and a visual form designer.
dotnet new console -lang VB -o HelloVB
cd HelloVB
dotnet run
# Hello, world!' Program.vb
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine("Hello, world!")
End Sub
End ModuleA Module holds shared procedures, and Sub Main is the entry point. Comments start with an apostrophe '. Each statement normally ends at the end of the line; there are no semicolons or braces.
Variables and basic types
Declare variables with Dim name As Type. With Option Infer On (the default) you can omit the type when you assign a value. Put Option Strict On at the top of each file (or set it in the project) so that risky implicit conversions become compile errors.
| Type | Example | Notes |
|---|---|---|
| Integer | Dim n As Integer = 42 | 32-bit; Long is 64-bit |
| Double | Dim x As Double = 3.14 | 64-bit floating point |
| Decimal | Dim price As Decimal = 19.99D | Exact decimal, good for money |
| String | Dim s As String = "hello" | Join strings with & |
| Char | Dim c As Char = "a"c | Single character, suffix c |
| Boolean | Dim ok As Boolean = True | True / False |
| Date | Dim d As Date = #2026-01-15# | Date and time value |
Option Strict On
Module Types
Sub Main()
Dim name As String = "Ana"
Dim age = 30 ' inferred as Integer
Console.WriteLine(name & " is " & age.ToString())
Console.WriteLine($"Next year {name} is {age + 1}")
Console.WriteLine(7 / 2) ' 3.5 (always Double)
Console.WriteLine(7 \ 2) ' 3 (integer division)
Console.WriteLine(7 Mod 2) ' 1
End Sub
End ModuleControl flow
Dim score = 85
If score >= 90 Then
Console.WriteLine("A")
ElseIf score >= 80 Then
Console.WriteLine("B")
Else
Console.WriteLine("C")
End If
Select Case score
Case 90 To 100
Console.WriteLine("excellent")
Case 80 To 89
Console.WriteLine("good")
Case Else
Console.WriteLine("keep going")
End Select
For i = 1 To 3
Console.WriteLine($"{i} squared is {i * i}")
Next
Dim n = 3
Do While n > 0
n -= 1
LoopThese statements go inside a Sub. For i = 1 To 3 includes both ends; add Step -1 to count down. For Each item In collection loops over any collection. Use Exit For or Exit Do to leave a loop early. For conditions, prefer AndAlso and OrElse: they stop evaluating as soon as the result is known, while And and Or always evaluate both sides.
Subs, functions and lambdas
A Sub does not return a value; a Function does. Parameters are passed ByVal (a copy) by default; ByRef lets the procedure change the caller's variable. Parameters can be Optional with a default value.
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
Sub Greet(Optional name As String = "world")
Console.WriteLine($"Hello, {name}!")
End Sub
Sub Increment(ByRef value As Integer)
value += 1
End Sub
' Inside Sub Main:
Dim x = 5
Increment(x) ' x is now 6
Greet() ' Hello, world!
Dim square = Function(n As Integer) n * n ' lambda
Console.WriteLine(square(Add(1, 2))) ' 9Arrays, List and Dictionary
Dim nums() As Integer = {3, 1, 2}
Dim five(4) As Integer ' 5 elements, indexes 0 to 4
Array.Sort(nums)
Console.WriteLine(String.Join(", ", nums)) ' 1, 2, 3
Dim names As New List(Of String) From {"Ana", "Ben"}
names.Add("Cleo")
Console.WriteLine(names.Count) ' 3
Dim ages As New Dictionary(Of String, Integer)
ages("Ana") = 30
ages("Ben") = 17
For Each pair In ages
Console.WriteLine($"{pair.Key}: {pair.Value}")
NextArrays and lists are indexed from 0 with parentheses: nums(0). Generic types use Of: List(Of String) is the VB form of C#'s List<string>. Note that Dim five(4) declares the upper bound, not the length, so the array has five elements.
Signature features: classes, properties and LINQ queries
VB.NET is fully object-oriented: classes have properties, methods, constructors (Sub New), inheritance (Inherits), interfaces (Implements) and events (Event, RaiseEvent, Handles). LINQ queries can be written in a readable query syntax.
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Sub New(name As String, age As Integer)
Me.Name = name
Me.Age = age
End Sub
End Class
' Inside Sub Main:
Dim people As New List(Of Person) From {
New Person("Ana", 30),
New Person("Ben", 17)
}
Dim adults = From p In people
Where p.Age >= 18
Select p.Name
For Each adultName In adults
Console.WriteLine(adultName) ' Ana
NextBecause VB is not case-sensitive, Name and name are the same identifier; inside the constructor, Me.Name refers to the property and name to the parameter. Other VB-specific conveniences include With ... End With blocks, XML literals and the My namespace for common tasks.
Error handling
VB.NET uses structured exception handling: Try, Catch, Finally and Throw. A Catch can include a When filter. The older On Error GoTo style from VB6 and VBA still compiles but should not be used in new .NET code.
Function ParseAge(s As String) As Integer
Dim n As Integer
If Not Integer.TryParse(s, n) Then
Throw New FormatException($"Not a number: {s}")
End If
If n < 0 Then Throw New ArgumentOutOfRangeException(NameOf(s))
Return n
End Function
' Inside Sub Main:
Try
Console.WriteLine(ParseAge("abc"))
Catch ex As FormatException
Console.WriteLine("Error: " & ex.Message) ' Error: Not a number: abc
Finally
Console.WriteLine("done")
End TryA small complete program: word frequencies
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module WordCount
Sub Main()
Dim text = "the cat and the hat and the bat"
Dim counts As New Dictionary(Of String, Integer)
For Each word In text.Split(" "c)
If counts.ContainsKey(word) Then
counts(word) += 1
Else
counts(word) = 1
End If
Next
Dim top = counts.OrderByDescending(Function(kv) kv.Value).Take(2)
For Each kv In top
Console.WriteLine($"{kv.Key} {kv.Value}")
Next
End Sub
End Module
' the 3
' and 2VBA: Visual Basic inside Microsoft Office
Visual Basic for Applications (VBA) is the macro language built into Microsoft Office applications such as Excel, Word and Access. It is based on classic Visual Basic, not .NET: it runs inside the Office application, uses the Office object model (workbooks, ranges, documents), and is edited in the VBA editor (Alt+F11 on Windows). The basic syntax of Dim, If, For and Sub is the same, which makes VB.NET knowledge useful for VBA.
' VBA in Excel: write the squares of 1 to 5 into column A
Sub FillSquares()
Dim i As Long
For i = 1 To 5
Cells(i, 1).Value = i * i
Next i
MsgBox "Done"
End SubWhere to go next
- Microsoft Learn: the Visual Basic documentation, including the getting-started guide and the language reference.
- Learn the .NET base class library (collections, files, LINQ); it is shared with C#.
- For desktop apps, try Windows Forms or WPF templates in Visual Studio.
- For Office automation, read the VBA reference on Microsoft Learn for the application you use.
FAQ
Is Visual Basic .NET dead?
No. It is supported on current .NET versions and in Visual Studio, but Microsoft does not plan major new language features, so most new .NET projects choose C#.
What is the difference between VB.NET and VBA?
VB.NET is a full .NET language for building standalone applications. VBA is a macro language based on classic Visual Basic that runs inside Office applications such as Excel; the syntax is similar, but the runtime and libraries are different.
Should I learn VB.NET or C#?
If you maintain VB code or want very readable syntax, VB.NET is fine. For new projects, job opportunities and the newest .NET features, C# is usually the better investment, and the libraries you learn transfer between the two.
Is Visual Basic case-sensitive?
No. Dim Total, total and TOTAL all refer to the same variable, and the editor usually normalizes the capitalization for you.