Visual Basic
Readable code for Windows and Office.
Visual Basic is a beginner-friendly language with English-like syntax. Visual Basic .NET (VB.NET) runs on .NET and builds Windows apps and services, while VBA (Visual Basic for Applications) automates Excel, Word and Access, which makes it one of the most widely used languages in offices around the world.
Why learn Visual Basic?
Millions of business spreadsheets and internal tools run on VBA and VB.NET, and AI can make them far more powerful.
- Easy to read: keywords like
If ... Then ... End Ifread like English. - Office automation: VBA controls Excel, Word and Outlook.
- .NET access: VB.NET uses the same libraries as C#.
Set up and run your first program
Install the .NET SDK to build VB.NET apps. For VBA, open Excel and press Alt+F11.
dotnet new console -lang VB -o HelloVB
cd HelloVB
dotnet runModule Program
Sub Main()
Dim name As String = "Ada"
Console.WriteLine($"Hello, AI! Welcome to Visual Basic, {name}.")
End Sub
End ModuleOption Strict On at the top of files to catch type mistakes at compile time.Variables and types
Declare variables with Dim name As Type. VB is not case-sensitive. Comments start with an apostrophe.
Option Strict On
Module Variables
Sub Main()
Dim layers As Integer = 32
Dim params As Double = 8030000000.0
Dim model As String = "llama3.1"
Dim fits As Boolean = True
Console.WriteLine($"{model}: {layers} layers, {params * 2 / 1.0E9:F1} GB, fits={fits}")
End Sub
End ModuleControl flow
If ... Then ... End If, Select Case and For ... Next loops read like plain English.
Module Control
Sub Main()
For epoch As Integer = 1 To 3
Console.WriteLine($"epoch {epoch}")
Next
Dim bits As Integer = 8
Select Case bits
Case 32 : Console.WriteLine("FP32")
Case 16 : Console.WriteLine("FP16")
Case 1 To 8 : Console.WriteLine("low precision")
Case Else : Console.WriteLine("other")
End Select
End Sub
End ModuleSubs and functions
A Sub does work and returns nothing; a Function returns a value. Parameters can be optional.
Module Procs
Function Params(layers As Integer, Optional width As Integer = 4096) As Long
Return 12L * layers * width * width
End Function
Sub Report(name As String, vram As Integer)
Console.WriteLine($"{name}: {vram} GB")
End Sub
Sub Main()
Console.WriteLine(Params(32))
Report("H100", 80)
End Sub
End ModuleLists, dictionaries and LINQ
VB.NET uses .NET collections. LINQ queries filter and sort data with readable syntax.
Imports System.Linq
Module Colls
Sub Main()
Dim vram As New Dictionary(Of String, Integer) From {
{"H100", 80}, {"H200", 141}, {"RTX 5090", 32}}
Dim big = From kv In vram Where kv.Value >= 80 Order By kv.Value Descending Select kv.Key
Console.WriteLine(String.Join(", ", big))
Console.WriteLine(vram.Values.Sum())
End Sub
End ModuleAutomating Excel with VBA
VBA macros run inside Office. This macro reads a column of GPU prices, calculates monthly costs and writes them back.
Sub MonthlyGpuCost()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("GPUs")
Dim lastRow As Long: lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Dim r As Long
For r = 2 To lastRow
' Column B = price per hour, column C = monthly cost
ws.Cells(r, "C").Value = ws.Cells(r, "B").Value * 24 * 30
Next r
MsgBox "Updated " & (lastRow - 1) & " rows"
End SubAI with Visual Basic
VB.NET can use the whole .NET AI stack, including ML.NET, ONNX Runtime and Microsoft.Extensions.AI, while VBA can call LLM APIs over HTTP to bring AI into Excel and Word, for example classifying rows, drafting text or cleaning data in a spreadsheet.
The essential libraries
An Excel formula that asks an LLM
A VBA user-defined function: type =ASKAI(A2) in a cell to send its text to a local model. Keep inputs short and avoid recalculating many cells at once.
Function ASKAI(prompt As String) As String
Dim http As Object: Set http = CreateObject("MSXML2.XMLHTTP")
Dim body As String
body = "{""model"":""llama3.1"",""messages"":[{""role"":""user"",""content"":""" & _
Replace(Replace(prompt, "\", "\\"), """", "\""") & """}]}"
http.Open "POST", "http://localhost:11434/v1/chat/completions", False
http.setRequestHeader "Content-Type", "application/json"
http.send body
Dim res As String: res = http.responseText
Dim i As Long: i = InStr(res, """content"":""") + 11
ASKAI = Mid(res, i, InStr(i, res, """") - i) ' simple extraction; use a JSON parser for real work
End FunctionBuild an AI agent in VB.NET
System.Text.Json.Nodes makes it easy to build and read the JSON for a tool-calling loop.
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json.Nodes
Module Agent
Function GetWeather(city As String) As String
Return $"It is 24°C and sunny in {city}."
End Function
Sub Main()
Dim http As New HttpClient()
Dim url = "http://localhost:11434/v1/chat/completions"
Dim tools = JsonNode.Parse("[{""type"":""function"",""function"":{""name"":""get_weather"",""description"":""Weather for a city"",""parameters"":{""type"":""object"",""properties"":{""city"":{""type"":""string""}},""required"":[""city""]}}}]")
Dim messages As New JsonArray(New JsonObject From {{"role", "user"}, {"content", "Should I take an umbrella in Lahore today?"}})
For round = 1 To 5
Dim body As New JsonObject From {{"model", "llama3.1"}, {"messages", messages.DeepClone()}, {"tools", tools.DeepClone()}}
Dim res = http.PostAsync(url, New StringContent(body.ToJsonString(), Encoding.UTF8, "application/json")).Result
Dim msg = JsonNode.Parse(res.Content.ReadAsStringAsync().Result)("choices")(0)("message")
messages.Add(msg.DeepClone())
Dim calls = TryCast(msg("tool_calls"), JsonArray)
If calls Is Nothing OrElse calls.Count = 0 Then
Console.WriteLine(msg("content").GetValue(Of String)())
Exit For
End If
For Each c In calls
Dim args = JsonNode.Parse(c("function")("arguments").GetValue(Of String)())
messages.Add(New JsonObject From {{"role", "tool"}, {"tool_call_id", c("id").GetValue(Of String)()},
{"content", GetWeather(args("city").GetValue(Of String)())}})
Next
Next
End Sub
End ModuleThe same pattern works in a Windows Forms app; use Async/Await so the UI stays responsive.
ollama pull llama3.1, and keep it running. The code talks to its OpenAI-compatible API at http://localhost:11434/v1, so the same program also works with vLLM, llama.cpp server or a cloud API by changing the URL, model name and adding an API key.Visual Basic learning roadmap
Tick items off as you go. Your progress is saved in this browser.
Beginner
Intermediate
Advanced
Projects to build
Visual Basic cheat sheet
| Task | Syntax |
|---|---|
| Variable | Dim x As Integer = 5 |
| If | If x > 3 Then ... End If |
| Loop | For i = 1 To 10 ... Next |
| Function | Function F(x As Integer) As Integer |
| String format | $"Value: {x}" |
| Comment | ' this is a comment |
Common mistakes
- Without
Option Strict On, VB silently converts types and hides bugs. - Arrays declared with
Dim a(5)have 6 elements (0 to 5). - VBA and VB.NET look similar but are different; VBA code does not run in .NET directly.
Where to go next
- VB.NET docs — official
- Office VBA reference — VBA docs
- ML.NET — machine learning
Keyboard: [ previous language · ] next language · / search the library