Skip to content
Volume V · The TensorCore.si Library

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.

Prologue

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 If read like English.
  • Office automation: VBA controls Excel, Word and Outlook.
  • .NET access: VB.NET uses the same libraries as C#.
Prologue

Set up and run your first program

Install the .NET SDK to build VB.NET apps. For VBA, open Excel and press Alt+F11.

terminal
dotnet new console -lang VB -o HelloVB
cd HelloVB
dotnet run
Program.vb
Module Program
    Sub Main()
        Dim name As String = "Ada"
        Console.WriteLine($"Hello, AI! Welcome to Visual Basic, {name}.")
    End Sub
End Module
TipPut Option Strict On at the top of files to catch type mistakes at compile time.
Chapter 1

Variables and types

Declare variables with Dim name As Type. VB is not case-sensitive. Comments start with an apostrophe.

Variables.vb
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 Module
Chapter 2

Control flow

If ... Then ... End If, Select Case and For ... Next loops read like plain English.

Control.vb
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 Module
Chapter 3

Subs and functions

A Sub does work and returns nothing; a Function returns a value. Parameters can be optional.

Procs.vb
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 Module
Chapter 4

Lists, dictionaries and LINQ

VB.NET uses .NET collections. LINQ queries filter and sort data with readable syntax.

Colls.vb
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 Module
Chapter 5

Automating Excel with VBA

VBA macros run inside Office. This macro reads a column of GPU prices, calculates monthly costs and writes them back.

Module1.bas
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 Sub
Part II · AI with Visual Basic

AI 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

ML.NETMachine learning for .NET.
ONNX RuntimeRun exported models.
System.Net.HttpCall LLM APIs from VB.NET.
MSXML2.XMLHTTPHTTP requests from VBA.

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.

AskAI.bas
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 Function
Part III · Build an AI agent

Build an AI agent in VB.NET

System.Text.Json.Nodes makes it easy to build and read the JSON for a tool-calling loop.

Your goal→Model plans→Tool call→Your code runs the tool→Result back to model→Final answer
Agent.vb
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 Module

The same pattern works in a Windows Forms app; use Async/Await so the UI stays responsive.

Run it locallyInstall Ollama, run 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.
Part IV · Your path

Visual Basic learning roadmap

Tick items off as you go. Your progress is saved in this browser.

Beginner

Intermediate

Advanced

Part IV · Your path

Projects to build

Expense trackerA Windows Forms app that saves to CSV.
Excel cleanerA VBA macro that tidies imported data.
AI spreadsheetClassify rows in Excel with a local LLM.
Reference

Visual Basic cheat sheet

TaskSyntax
VariableDim x As Integer = 5
IfIf x > 3 Then ... End If
LoopFor i = 1 To 10 ... Next
FunctionFunction F(x As Integer) As Integer
String format$"Value: {x}"
Comment' this is a comment
Reference

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.
Reference

Where to go next

On TensorCore.si: C# volume, F# volume.

Keyboard: [ previous language · ] next language · / search the library