u/UesleiDev

▲ 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
▲ 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/brdev

Wasabi: Implementei uma stack WebSocket e TCP completa em VBA usando Assembly thunks e Schannel sem dependências, um único arquivo .bas

Quem já tentou integrar Excel/VBA com APIs de tempo real sabe que a coisa sempre termina igual: ou você faz polling com WinHTTP e a interface congela, ou usa uma biblioteca .NET/COM que a TI corporativa barra na hora. Não existe meio-termo.

Passei alguns meses estudando código de programadores antigos da comunidade (wqweto, EagleAglow e outros) tentando entender até onde dava pra ir só com VBA puro. O resultado foi o Wasabi: um único arquivo .bas que implementa uma stack completa de WebSocket do zero, sem dependência nenhuma.

Como funciona por baixo

A ideia central foi falar direto com o Windows em vez de depender de qualquer abstração:

  • Winsock na mão: chamo ws2_32.dll diretamente via ponteiros VBA para criar sockets TCP não-bloqueantes.
  • TLS via Schannel: em vez de usar biblioteca de terceiro, integrei o SSPI nativo do Windows para fazer o handshake de TLS 1.2 e 1.3 direto na memória. Zero dependências externas.
  • WebSocket sobre TCP: implementei o RFC 6455 por cima disso. O problema é que XOR masking de frames grandes em loop de VBA é absurdamente lento.
  • Assembly Thunks: pra resolver o gargalo, usei VirtualAlloc pra alocar memória executável, escrevi o algoritmo de mascaramento em Assembly (x86 e x64), converti pra opcodes e executei via CallWindowProcW. A performance foi pra outro nível.

O que o arquivo entrega

  • Cliente TCP, WebSocket (WSS) e MQTT 3.1.1 completos (QoS 0, 1 e 2)
  • Suporte a proxies corporativos com NTLM/Kerberos
  • Compilação condicional #If VBA7 o mesmo .bas roda no Office 32-bit (XP era) e no Office 64-bit atual sem alteração

Por que isso importa

O mundo corporativo ainda roda em planilhas, queira a gente ou não. Shadow IT é real. Esse projeto nasceu de uma comunidade de desenvolvimento de jogos no PowerPoint (sim, de verdade) onde a galera faz coisas absurdas com VBA e sempre sonhou com alguma forma de comunicação em tempo real entre instâncias.

O que nós tínhamos conseguido era fazendo uma conexão TCP, porém para a maioria das outras coisas não serviria, se conectar com WebSocket não dava por exemplo, mas foi uma base muito importante para a construção do projeto. O jogo em questão que tem o sistema TCP que ajudou muito é esse: https://youtu.be/E1_Jof8H6DI?si=j822dZfVf11I_nIo do canal PPTGames.

Com tudo isso, almejo tornar o Wasabi a biblioteca principal para desenvolvimento de redes no VBA, tanto com MQTT, WebSocket, TCP, TSL e entre outros. Muitos desenvolvedores quebram a cabeça e lêem fóruns antigos para tentar implementar, tudo que conseguem é um sistema travado pelas limitações do VBA e com sujeito a falhas de memória pelos handles mal feitos, essa solução é na minha opinião definitiva e tem um grande impacto em tudo que ja vimos envolvendo isso na comunidade VBA.

Se você curte baixo nível, a parte de alocação de memória e injeção de ASM vale uma olhada. Feedback técnico é bem-vindo (se curtir e decidir da uma estrelinha lá também agradeço 😉).

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

u/UesleiDev — 6 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
▲ 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