r/vba

I made a Discord bot that runs from a hidden Excel sheet. Because why not.
▲ 65 r/vba+2 crossposts

I made a Discord bot that runs from a hidden Excel sheet. Because why not.

So I've been working on a native WebSocket module for VBA called Wasabi, and at some point I asked myself: "can I connect this to Discord's gateway and make a bot?" The answer is yes, and it's glorious and completely unnecessary.

The concept

Discord's bot API is just a WebSocket connection to wss://gateway.discord.gg. Once connected, Discord sends you a JSON payload with an op code telling you to identify yourself. You send back your bot token and intents, and from that point on you receive events (messages, reactions, etc.) as JSON frames. You respond to them by hitting Discord's REST API with plain HTTP calls.

That's it. No SDK needed. Just WebSocket + JSON parsing.

Step 1: Get a bot token

Go to https://discord.com/developers/applications, create an application, add a bot, copy the token. Enable the "Message Content Intent" under the bot settings or it won't receive message content.

Step 2: Import Wasabi

Download Wasabi.bas from https://github.com/uesleibros/wasabi/releases and import it into your VBA project via File > Import File. No references to enable, no DLLs to register.

Step 3: Connect to the gateway and keep it alive

Discord requires you to send a heartbeat payload every N milliseconds (it tells you the interval on connect). Here's a minimal loop that handles that:

#If VBA7 Then
    Private Declare PtrSafe Function GetTickCount Lib "kernel32" () As Long
#Else
    Private Declare Function GetTickCount Lib "kernel32" () As Long
#End If

Sub RunDiscordBot()
    Dim token As String
    token = "YOUR_BOT_TOKEN_HERE"

    Dim handle As Long
    If Not WebSocketConnect("wss://gateway.discord.gg/?v=10&encoding=json", handle) Then
        MsgBox "Failed to connect to Discord gateway."
        Exit Sub
    End If

    Dim msg As String
    Dim heartbeatInterval As Long
    Dim lastHeartbeat As Long
    Dim identified As Boolean

    identified = False
    lastHeartbeat = 0

    Do While WebSocketIsConnected(handle)
        msg = WebSocketReceive(handle)

        If Len(msg) > 0 Then
            Dim op As Long
            op = ExtractOp(msg) ' parse the "op" field from JSON

            ' Hello payload: Discord sends heartbeat interval
            If op = 10 Then
                heartbeatInterval = ExtractHeartbeatInterval(msg)
                lastHeartbeat = GetTickCount()

                ' Identify
                If Not identified Then
                    Dim identifyPayload As String
                    identifyPayload = "{""op"":2,""d"":{""token"":""" & token & """,""intents"":33280,""properties"":{""os"":""windows"",""browser"":""excel"",""device"":""excel""}}}"
                    WebSocketSend identifyPayload, handle
                    identified = True
                End If

            ' Dispatch: actual events like MESSAGE_CREATE
            ElseIf op = 0 Then
                Call HandleEvent(msg, token)
            End If
        End If

        ' Send heartbeat when due
        If GetTickCount() - lastHeartbeat >= heartbeatInterval Then
            WebSocketSend "{""op"":1,""d"":null}", handle
            lastHeartbeat = GetTickCount()
        End If

        DoEvents
    Loop

    WebSocketDisconnect handle
End Sub

Step 4: Handle a message event

When op = 0 and the event type is MESSAGE_CREATE, you get the channel ID and message content from the JSON. Then you can reply via Discord's REST API using XMLHTTP:

Sub HandleEvent(ByVal payload As String, ByVal token As String)
    If InStr(payload, "MESSAGE_CREATE") = 0 Then Exit Sub

    Dim channelId As String
    Dim content As String
    channelId = ExtractField(payload, "channel_id")
    content = ExtractField(payload, "content")

    If content = "!ping" Then
        Call SendDiscordMessage(channelId, "Pong! (sent from Excel)", token)
    End If
End Sub

Sub SendDiscordMessage(ByVal channelId As String, ByVal message As String, ByVal token As String)
    Dim http As Object
    Set http = CreateObject("MSXML2.XMLHTTP")
    Dim url As String
    url = "https://discord.com/api/v10/channels/" & channelId & "/messages"
    Dim body As String
    body = "{""content"":""" & message & """}"
    
    http.Open "POST", url, True
    http.setRequestHeader "Authorization", "Bot " & token
    http.setRequestHeader "Content-Type", "application/json"
    http.Send body
    
    Do While http.readyState <> 4
        DoEvents
    Loop
End Sub

Where to go from here

This is just the skeleton. From here you can:

  • Read/write cells based on Discord commands ("!get A1" returns the cell value, "!set A1 42" writes to it)
  • Trigger macros remotely by sending a command from Discord
  • Post alerts to a channel when a cell value crosses a threshold (combine with a Worksheet_Change event)
  • Run the bot from a hidden sheet so it sits quietly in the background while you use the spreadsheet normally

The browser and device fields in the identify payload are set to "excel" in the example above. Discord doesn't validate these, but it's a fun touch.

Full module docs and source: https://github.com/uesleibros/wasabi

u/UesleiDev — 3 days ago
▲ 14 r/vba+1 crossposts

This project started in a rather unexpected place. A group of friends of mine have the hobby of building entire games inside PowerPoint using VBA. They kept hitting the same wall: there was no clean, reliable way to get real‑time communication working inside VBA. I wanted to help them, and that’s how Wasabi came to life. It is a single .bas module that acts as a full WebSocket and secure WebSocket client, written entirely in native VBA using Winsock and the Windows Schannel security provider.

Because it’s just a plain VBA module, you can use it in any Office host that runs VBA: Excel, PowerPoint, Word, Access, Outlook, and more. You import the file and you’re ready to go. No references to add, no DLLs to register, no external dependencies at all. It works on 32‑bit and 64‑bit Office, from Windows XP to Windows 11.

Under the hood it handles secure sockets over TLS via Schannel, so you can connect to wss:// endpoints without relying on a browser or third‑party library. An integrated MQTT 3.1.1 client lets you talk to brokers like Mosquitto directly from any VBA‑enabled program, which opens the door to IoT projects and industrial automation. There is support for corporate proxy authentication using NTLM and Kerberos, so it fits right into enterprise environments where the network expects Integrated Windows Authentication. The connection layer includes automatic reconnection, an optional heartbeat, and per‑message deflate compression as defined in RFC 7692. Masking keys for outgoing frames are generated using CryptGenRandom, which keeps the randomness cryptographically sound.

This becomes genuinely useful in practice when you need real‑time data inside Office. You can stream quotes from Binance or Coinbase straight into an Excel spreadsheet with millisecond latency. You can build dashboards that update live without polling HTTP endpoints. You can write a Discord or Slack bot that runs from Access or Excel. You can connect legacy VBA tools to modern event buses over WebSockets or MQTT, bridging old and new without complex middleware. And yes, you can even add real‑time multiplayer to a PowerPoint game if the mood strikes.

Getting started takes a few minutes. Grab the Wasabi.bas file from the releases page, open the VBA editor in your host of choice, and choose File → Import File.

The project is open source under the MIT license. The full documentation covering the API reference, error handling, and internal architecture lives in the GitHub repository folder docs. That same group of friends is already testing multiplayer PowerPoint games through Wasabi, and seeing it work across different Office apps at the same time still feels a little magical.

If you have ever wanted to add real‑time capabilities to a VBA project and found the built‑in options lacking, this module might save you a lot of low‑level pain. I would be glad to hear your thoughts, ideas, or use cases.

Repository: https://github.com/uesleibros/wasabi

Releases (download just the .bas): https://github.com/uesleibros/wasabi/releases

u/UesleiDev — 6 days ago
▲ 36 r/vba

Stop using For Each Cell In Range on big datasets. It's too slow and will just hang Excel and kill the UI. If you're looping more than a few hundred rows this way, you're doing it wrong. It's basic.

Just dump the whole range into an array in RAM. Crunch the data in memory. Then 'spray' it back to the sheet in one shot. It's much faster.

Sub FastCleanData()
    Dim data As Variant
    Dim i As Long
    
    ' Pull everything into RAM
    data = [A1:B10000].Value 
    
    For i = 1 To UBound(data)
        ' Process logic in RAM
        data(i, 1) = Trim(UCase(data(i, 1)))
    Next i
    
    ' Push back to sheet
    [A1:B10000].Value = data
End Sub

The reason it's slow is the VBA-to-Sheet communication. That's the bottleneck. One single read followed by one single write is almost instant. 10,000 separate reads and writes will make Excel hang every time.

Keyboard-only move: Don't reach for the mouse to run this. Alt+F8 > type name > Enter

reddit.com
u/Good-Willingness2234 — 9 days ago
▲ 62 r/vba

9 quick tips to improve your VBA macro performance.

1 Turn off everything but the essentials in VBA;

The below code sample shows you how to enable/disable:

  • Manual calculations
  • Screen updates
  • Animations

​

Option Explicit

Dim lCalcSave As Long
Dim bScreenUpdate As Boolean

Sub SwitchOff(bSwitchOff As Boolean)
    Dim ws As Worksheet

    With Application
        If bSwitchOff Then
            ' OFF
            lCalcSave = .Calculation
            bScreenUpdate = .ScreenUpdating
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableAnimations = False

            For Each ws In ActiveWorkbook.Worksheets
                ws.DisplayPageBreaks = False
            Next ws
        Else
            ' ON
            If .Calculation <> lCalcSave And lCalcSave <> 0 Then
                .Calculation = lCalcSave
            End If
            .ScreenUpdating = bScreenUpdate
            .EnableAnimations = True
        End If
    End With
End Sub

Sub Main()
    SwitchOff True
    MyFunction
    SwitchOff False
End Sub

2. Disabling Office animations through system settings;

Animations can be disabled across Windows by accessing the Ease of Access Center.

Animations can be disabled in Excel specifically, under the Advanced or Ease of Access tab, within the File > Options menu.

Please see the following link for more information: https://support.office.com/en-us/article/turn-off-office-animations-9ee5c4d2-d144-4fd2-b670-22cef9fa025a

3 Disabling Office animations through registry settings

Office animations can be disabled across multiple computers by setting the appropriate registry key via a group policy setting. 

HIVE: HKEY_CURRENT_USER
Key Path: Software\Microsoft\Office\16.0\Common\Graphics
Key Name: DisableAnimations
Value type: REG_DWORD
Value data: 0x00000001 (1)

4 Removing unnecessary selects

The select method is common to see in VBA code, however it is often added to the macro where it isn’t needed. Select can trigger cell events such as animations and conditional formatting which slow the macro down, so removing unnecessary selects can significantly speed up your macro.

The following example shows the code before and after making the change to remove unnecessary selects.

Before

Sheets("Order Details").Select
Columns("AC:AH").Select
Selection.ClearContents

After

Sheets("Order Details").Columns("AC:AH").ClearContents

 4 Removing unnecessary selects

The select method is common to see in VBA code, however it is often
added to the macro where it isn’t needed. Select can trigger cell events
such as animations and conditional formatting which slow the macro
down, so removing unnecessary selects can significantly speed up your
macro.
The following example shows the code before and after making the change to remove unnecessary selects.

 Before
Sheets("Order Details").Select
Columns("AC:AH").Select
Selection.ClearContents

After
Sheets("Order Details").Columns("AC:AH").ClearContents

5 Using the With statement to read object properties

When working with objects, use the With statement to reduce the number of times object properties are read. The following example shows the code before and after making the change to use the With statement.

 

Before

Range("A1").Value = "Hello"
Range("A1").Font.Name = "Calibri"
Range("A1").Font.Bold = True
Range("A1").HorizontalAlignment = xlCenter

After

With Range("A1")
  .Value2 = "Hello" 
  .HorizontalAlignment = xlCenter
    With .Font
      .Name = "Calibri"
      .Bold = True
    End With
End With

6 Using ranges and arrays

Reading and writing to cells in Excel from VBA is expensive. There is an overhead that is incurred every time data moves between VBA and Excel.

This means that you should try to reduce the number of times you pass data between VBA and Excel. This is where ranges are useful. Instead of reading and writing to each cell individually in a loop, read the entire range into an array at the start, loop through the array, and then write the entire array back at the end. The following example code shows how a range can be used to read and write the values once, instead of reading each cell individually.

Dim vArray As Variant
Dim iRow As Long
Dim iCol As Long
Dim dValue As Double

vArray = Range("A1:C10000").Value2

For iRow = LBound(vArray, 1) To UBound(vArray, 1)
    For iCol = LBound(vArray, 2) To UBound(vArray, 2)
        If IsNumeric(vArray(iRow, iCol)) Then
            dValue = CDbl(vArray(iRow, iCol))
            If dValue > 0 Then
                dValue = dValue * dValue
            End If
            vArray(iRow, iCol) = dValue
        End If
    Next iCol
Next iRow

Range("A1:C10000").Value2 = vArray

7 Use .Value2 instead of .Text or .Value

There are different ways that you can retrieve values from a cell, and which property you use can make a different in the performance of your code.

.Text is commonly used to retrieve the value of a cell – it returns the formatted value of a cell. Getting the formatting of a cell is more complex than just retrieving a value, and makes .Text quite slow.

.Value is an improvement over .Text, as this mostly gets the value from the cell, without formatting. However for cells formatted as a date or currency, .Value will return a VBA date or VBA currency (which may truncate decimal places).

.Value2 gives the underlying value of the cell. As it involves no formatting, .Value2 is faster than .Value. .Value2 is faster than .Value when processing numbers (there is no significant difference with text), and is much faster using a variant array.

8 Bypass the clipboard (copy and paste)

When you use the Macro Recorder to record operations that use copy and paste, the code will use the copy and paste methods by default. However, within VBA code, it is much faster to bypass the clipboard and use internal operations instead. By default, copying will copy everything, including formulas, values and formatting. You can make copying faster by only copying values or formulas, without the formatting. The following example shows the code before and after making the change to bypass the clipboard.

Before

Range("A1").Select
Selection.Copy
Range("A2").Select
ActiveSheet.Paste

After

' Approach 1: copy everything (formulas, values and formatting
Range("A1").Copy Destination:=Range("A2")

' Approach 2: copy values only
Range("A2").Value2 = Range("A1").Value2

'Approach 3: copy formulas only
Range("A2").Formula = Range("A1")

9. Use Option Explicit to catch undeclared variables

Option Explicit is one of the available Module directives in VBA that instructs VBA how to treat the code within the code module. Setting Option Explicit requires all variables to be declared and will give compile errors if an undeclared variable is used. This helps catch incorrectly typed variable names and improves performance with all variable types being defined at compile time, instead of being inferred at runtime.

This can be set by typing: Option Explicit at the top of each module in your project or by checking the "Require Variable Declaration" option under Tools -> Options in the VBA editor. 

reddit.com
u/Good-Willingness2234 — 6 days ago
▲ 28 r/vba

Wasabi just hit Awesome VBA + Update v2.3.8

I am very pleased to announce a significant milestone for the Wasabi project. After several in depth technical discussions with sancarn, the creator of the renowned stdVBA library, Wasabi has been officially included in the Awesome VBA list. This is a meaningful recognition for a project that originated from a specific need within a niche PowerPoint gaming community and has now matured into a robust tool for general purpose networking.

For those who are not familiar with the project, Wasabi is a self contained .bas module designed to provide a complete networking stack for VBA. It requires zero external dependencies, zero references, and no registration of COM DLLs. It implements WebSockets (WSS), raw TCP, and full Proxy support directly within the VBA environment.

The core of Wasabi architecture relies on machine code thunks for both x86 and x64 architectures. These thunks handle critical operations such as memory zeroing, byte searching, and WebSocket masking outside the standard VBA stack. This creates a vital safety layer. In typical VBA networking, the application often crashes if the editor enters break mode or encounters an unhandled error while a Windows message pump is active. Wasabi assembly thunks act as a firewall, intercepting these events and preventing the host application from closing abruptly.

The repository was recently updated to version 2.3.8-beta. This update focused on hardening the protocol implementations and expanding compatibility with modern standards.

  1. Native MQTT 5.0 Implementation The MQTT parser has been significantly overhauled to move beyond the legacy 3.1.1 standard. Wasabi now natively supports the MQTT 5.0 protocol. This includes the correct processing of variable byte integers for the remaining length field and the mandatory property length fields in CONNECT, SUBSCRIBE, and PUBLISH packets. We have successfully validated this implementation against modern brokers like HiveMQ and EMQX, as well as testing tools like MQTTX. MQTTX Reported by u/Savings_Mission_534 (https://www.reddit.com/r/vba/comments/1t9q3nc/comment/ol4zycm)
  2. RFC 6455 Hardening and Protocol Compliance We have reinforced the WebSocket frame parser to be strictly compliant with RFC 6455. The parser now performs strict validation of reserved bits (RSV2 and RSV3). According to the specification, if these bits are set without a negotiated extension, the connection must be terminated with a protocol error code 1002. Additionally, the handling of TLS fragments during reassembly was improved to ensure that data remains contiguous and valid even during high volume or fragmented transmissions.
  3. Memory Management and Buffer Optimization The internal routine for buffer allocation, EnsureBufferCapacity, was rewritten to handle larger data streams more efficiently. The previous limits were found to be too restrictive for certain industrial applications. The module now supports data payloads of up to 256MB by utilizing a more aggressive growth strategy and safer memory pointers, which is a significant leap for the VBA environment.
  4. Closing Handshake Logic The Finite State Machine (FSM) for connection teardown was refined. Wasabi now correctly handles the STATE_CLOSING status, ensuring that it sends the closing frame and waits for the server echo before fully releasing the socket resources. This prevents half open connections and potential memory leaks during rapid connect and disconnect cycles.

Looking ahead, the goal is to further increase the stability and reach of the module. There is an ongoing plan to eventually integrate these networking capabilities into a dedicated class for the stdVBA library, making it even easier for developers to build modern, connected applications.

Contributions through Pull Requests, detailed bug reports, or architectural suggestions via GitHub Issues are highly encouraged. Whether you are interested in Win32 API hacks, IoT integration, or real time data synchronization within Office, Wasabi provides a solid foundation to explore these limits.

Github: https://github.com/uesleibros/wasabi

Release: https://github.com/uesleibros/wasabi/releases/tag/v2.3.8-beta

I want to thank the members of this sub who provided technical feedback on previous versions. Your insights were crucial in identifying edge cases and refining the memory management logic. We continue to push the boundaries of what is possible within the VBA environment.

reddit.com
u/UesleiDev — 2 days ago
▲ 1 r/vba

Automation with VBA

Hello everyone,

I would like to know how analysts are using VBA in Excel in their daily work.

I currently work as a data analyst, and part of my role is to create different types of analysis reports. For example, I analyze sales evolution in Grand Surfaces and other local sales by article and by category and other kpis etc.. to identify which products perform well and which do not.

Most of the time, I use tools like Claude AI and Google Gemini to help structure my analysis by explaining my data and the expected output by one simple click and loge generate well performed analysis and reports (even if it's huge page) in one simple click

For data preparation, I usually:

Clean product names

Standardize category names

Use functions like VLOOKUP, SUMIF DATEEVAL for fixing date NB.SI.ENS, etc. to calculate totals and revenue

However, I am looking for innovative ways to use VBA to automate data cleaning. Any ideas?

My goal is to create simple macros so that even a beginner could run them and clean the dataset automatically.

Unfortunately, I cannot use Microsoft Power BI in my environment, but I can use Microsoft Power Query

I will also begin developing a more interactive dashboard using VBA. This dashboard will explain all (KPIs) and provide guidance on the appropriate placement for pie charts, histograms, and line charts.

reddit.com
u/Fluffy-Difficulty882 — 5 days ago
▲ 4 r/vba+1 crossposts

I have been looking to make an MS Project add-in tool for myself, and came across one by Structured Solutions Inc. This add in has what seems to be a dockable window custom made by them and I was wondering what they did to make something like that. My current plan is to use VSTO, but I can't find any documentation showing that this is even possible.

reddit.com
u/Playful_Orchid_7816 — 7 days ago
▲ 14 r/vba

A day ago I posted here about Wasabi v2.3.2. First and foremost, I want to express my deepest gratitude. The repository just hit 20 stars on GitHub! The community reception has been absolutely incredible, and your support gave me the exact fuel I needed to push some massive updates over the last few days.

The leap from the version I posted earlier this week to the current v2.3.4-beta is not just an update. It is a complete architectural paradigm shift. I want to dive deep into what is new, because there is a lot to unpack.

1. The High Performance Assembly Engine (Wasabi ASM)

We all know VBA is excellent for automation, but it is notoriously slow at processing massive byte arrays sequentially. To solve this bottleneck once and for all, Wasabi now features a microscopic Assembly Engine. The module safely allocates executable memory and injects native x86 and x64 machine code directly into the CPU. Wasabi now executes heavy networking math with C level throughput.

  • ws_mask: I completely rewrote the WebSocket XOR masking logic in Assembly. By eliminating the high overhead VBA loops, payloads ranging from kilobytes to several megabytes are now masked in microseconds. This also completely resolved a critical frame validation issue (Error 4002) with the Discord Gateway.
  • mem_find: An ultra optimized "Needle in a Haystack" search engine powered by the repe cmpsb hardware instruction. Wasabi can now scan massive TCP streams for delimiters (like \r\n) almost instantaneously, without blocking the Office UI thread during large data transfers.
  • mem_zero: Implements hardware level memory zeroing using the rep stosb instruction. Upon connection teardown, all sensitive buffers and proxy credentials are physically wiped from RAM instantly to prevent data leakage.
  • Native Kernel Entropy: I stripped out legacy cryptographic APIs and implemented RtlGenRandom. Wasabi now fetches cryptographically secure random bytes for WebSocket masking directly from the Windows Kernel with significantly lower latency.

2. Bulletproof TLS and Graceful Teardowns

I spent the last couple of days stress testing Wasabi on highly demanding, long lived connections. I noticed a critical edge case: if a server gracefully decided to drop your connection (a normal session cycle), the Windows Schannel engine would return a SEC_I_CONTEXT_EXPIRED alert. Wasabi was misidentifying this normal teardown as a fatal decryption failure (ERR 15). Worse, it would attempt to write queued data to a dead socket, causing a zombie socket crash (ERR 10).

Version 2.3.4-beta completely eliminates this issue. The module now intercepts the graceful teardown, closes the internal state cleanly, and silently hands over the flow to the AutoReconnect engine. Long lived connections can now run for days and recover from server drops seamlessly.

3. The Future: The Framework Era (Middlewares & Extensions)

This is what excites me the most. Wasabi is evolving from a monolithic script into a modular ecosystem. I have officially laid the groundwork for an injection system using Late Binding, inspired by modern frameworks like Express.js.

The goal is to turn the core Wasabi module into a "Dumb Pipe" that only handles raw Sockets and Schannel. Everything else will become pluggable Lego pieces. The community will soon be able to inject custom high level protocols (like Socket.IO or MQTT 5.0), security interceptors (autonomous OAuth/JWT headers or E2E AES encryption), and decouple the Zlib compression into an optional standalone extension. You can read the full architectural blueprint in the repository roadmap.

4. Ultra Low Latency Code Example

By combining the new Assembly engine, the decoupled Zlib compression, and disabling the TCP Nagle algorithm, the processing overhead in VBA is now practically zero. Here is how you can build a rock solid, ultra low latency connection to Discord:

Dim h As Long

' Enable Zlib compression to drastically reduce massive payload sizes
Wasabi.WebSocketSetDeflate True, True, h

' Disable Nagle algorithm for instant packet delivery
Wasabi.WebSocketSetNoDelay True, h

' Configure a resilient AutoReconnect (5 attempts, 1000ms base delay)
Wasabi.WebSocketSetAutoReconnect True, 5, 1000, h

' Connect to Discord requesting zlib stream transport
If Wasabi.WebSocketConnect("wss://gateway.discord.gg/?v=10&encoding=json&compress=zlib-stream", h) Then
    
    Debug.Print "Connected! Physical Latency: " & Wasabi.WebSocketGetLatency(h) & "ms"
    
    Do While Wasabi.WebSocketIsConnected(h)
        Dim msg As String
        msg = Wasabi.WebSocketReceive(h)
        
        If Len(msg) > 0 Then
            Debug.Print "Received Event: " & Left(msg, 100) & "..."
        End If
        
        DoEvents
    Loop
    
End If

With these updates, Wasabi handles all the heavy protocol level math in the background, allowing your VBA project to dedicate 100% of its execution time to your actual application logic.

Check out the latest release:

GitHub Repository: https://github.com/uesleibros/wasabi

Release v2.3.4-beta: https://github.com/uesleibros/wasabi/releases/tag/v2.3.4-beta

Extensions Roadmap: https://github.com/uesleibros/wasabi/tree/main/extensions

Thank you all once again for the stars, the feedback, and the community validation. It is an honor to build this alongside you. I would love to hear your thoughts, answer questions, or see the crazy integrations you are building with this!

reddit.com
u/UesleiDev — 7 days ago
▲ 13 r/vba

Two days ago I posted about Wasabi, a zero-dependency WebSocket/WSS module for VBA. Since then the project has moved quickly. Version v2.3.2-beta is now available, and I want to share what has been added.

The biggest addition is a full native TCP client that works over plain TCP and over TLS 1.2/1.3. It shares the same connection pool, proxy support, MTU discovery, and Schannel infrastructure as the WebSocket client. The API is deliberately straightforward:

Dim h As Long

' Plain TCP
If TcpConnect("tcpbin.com", 4242, h) Then
    TcpSendText "Hello" & vbCrLf, h
    Debug.Print TcpReceiveText(h)
    TcpDisconnect h
End If

' TLS-wrapped TCP
If TcpConnectTLS("example.com", 443, h) Then
    TcpSendText "GET / HTTP/1.0" & vbCrLf & "Host: example.com" & vbCrLf & vbCrLf, h
    Debug.Print TcpReceiveText(h)
    TcpDisconnect h
End If

All TCP functions (TcpSend, TcpSendText, TcpReceive, TcpReceiveText, TcpReceiveUntil, TcpBroadcast, etc.) work seamlessly with corporate proxies, NTLM/Kerberos authentication, and the same TLS stack that powers wss connections. The same timeout, certificate, and buffer configuration functions are available on TCP handles as well.

The repository now contains an examples folder with ready-to-run code:

  • WebSocket connection to Binance for live ticker data
  • MQTT publish and subscribe using Mosquitto
  • Raw HTTPS request over TLS
  • Proxy connection with NTLM authentication

Each example is documented and tested on 32-bit and 64-bit Office.

A benchmarks folder has been added. It contains VBA routines that measure throughput, round-trip time, and connection setup. These are useful for tuning and for comparing environments.

A tests folder now holds unit tests for frame parsing, compression, MQTT packet handling, and other internal logic. The test suite is growing with each release.

The documentation in the docs folder has been reorganized. The API reference is clearer, error codes are explained, and an architecture overview has been included.

A quick example using WebSocket and MQTT:

Dim h As Long

If WebSocketConnect("wss://test.mosquitto.org:8081/mqtt", h, False, True, "mqtt") Then
    MqttConnect "wasabi-client", h
    MqttSubscribe "sensors/temperature", 0, h
    
    Do While WebSocketIsConnected(h)
        Dim msg As String
        msg = MqttReceive(h)
        If msg <> "" And Left(msg, 1) <> "[" Then
            Dim parts() As String
            parts = Split(msg, "|", 2)
            Debug.Print parts(0), parts(1)
        End If
        DoEvents
    Loop
    
    MqttDisconnect h
    WebSocketDisconnect h
End If

A bug reported by fafalone (a crash on 32-bit Office) was fixed within hours of the original post and the patch is already in main.

The module remains a single .bas file with no references, no DLLs, and no registration. It works from Windows XP to Windows 11, in any VBA host.

Github: https://github.com/uesleibros/wasabi

Release v2.3.2-beta: https://github.com/uesleibros/wasabi/releases/tag/v2.3.2-beta

I would be glad to hear about your use cases, questions, or ideas.

It's worth highlighting that I really liked the community's reception; I believe this project will become increasingly solid and have a great user base over time.

reddit.com
u/UesleiDev — 8 days ago