Introducing RDCore: RD-VBA Language Platform v0.1.0-alpha

Close-up of a weathered dark coin featuring a raised duck emblem and partial lettering
V I V A T ❤️ C U C U M I S
[English version follows]

Rubberduck renaît

La plateforme RDCore franchit aujourd’hui une étape importante avec sa première version alpha publiée officiellement. Cette pré-version peut être téléchargée et installée dès maintenant, et fonctionne sous Windows, Linux et macOS. Pour le moment, seules les plateformes 64 bits sont prises en charge.

La plateforme accueille RD‑VBA, une implémentation de la spécification MS‑VBAL corrigée sur certains points, enrichie sur d’autres, qui permet notamment d’utiliser PEEK et POKE dans le mode BASIC, ajoute les constantes de précompilation #If Linux et #If Linux64, et compile vers l’IL de .NET 10.

Téléchargez la version alpha ici : https://github.com/rubberduck-vba/RDCore/releases/tag/v0.1.0-alpha

RD-VBA

Le cœur du langage réside dans le SDK (NuGet : v0.1.2‑alpha). Il définit une variante de VBA ainsi qu’une implémentation complète de sa bibliothèque standard capable de s’exécuter partout où .NET est disponible, sans dépendre du tristement célèbre environnement d’exécution Microsoft Visual Basic ni d’une application hôte quelconque. La plateforme fournit son propre environnement d’exécution.

Automatisation COM

VBA a toujours été capable d’automatiser des objets COM sans être hébergé dans le processus concerné. C’est exactement ce qui se produit lorsqu’une variable reçoit un New Excel.Application ou qu’un appel à CreateObject(“Excel.Application”) est effectué.

Comme RD‑VBA s’exécute en dehors des applications Microsoft Office, cette approche devient désormais la méthode normale d’interaction avec COM.

rdc build

En contrepartie, vous gagnez la possibilité de compiler du code RD‑VBA en exécutables autonomes. Les commandes rdc build et rdc run font exactement ce que leur nom laisse entendre.

Serveur de langage

Le cœur du langage n’est qu’un modèle. Ce qui lui donne vie, c’est l’architecture client/serveur LSP qui constitue la plateforme. En son centre se trouve le serveur de langage, qui coordonne les échanges entre l’hôte d’exécution, le client ou l’EDI et les extensions de la plateforme.

Le serveur fournit l’implémentation du protocole LSP 3.17 par l’intermédiaire d’OmniSharp 0.19. Les erreurs de syntaxe, de compilation et, lorsque possible, d’exécution sont signalées sous forme de diagnostics dès la phase de conception.

Les listes d’autocomplétion sont disponibles pour les mots-clés et les identificateurs, et prennent en charge la recherche par bosses PascalCase : saisir « mb » permet par exemple de retrouver MidB et MsgBox.

La plateforme elle-même n’inclut pas d’EDI*; cependant, rdc.exe agit également comme client LSP autonome et lance une console interactive RD‑VBA/BASIC lorsqu’il est exécuté sans argument.

*mais attendez, ce n’est pas tout!

RDCore.HexIDE

Sans faire directement partie de la distribution RDCore, ce module complémentaire pour HexIDE agit comme client LSP. Il télécharge la plateforme si nécessaire, avec votre consentement, puis assure la liaison entre l’EDI et le serveur de langage.

Pour installer RDCore.HexIDE, téléchargez le paquet signé depuis sa publication GitHub, extrayez-le dans un dossier qui lui est propre sous le dossier addins de HexIDE, puis redémarrez HexIDE.

HexIDE est né comme projet d’EDI VB6 accompagné d’un interpréteur expérimental. Avec RDCore comme moteur, il devient naturellement l’environnement de référence pour les espaces de travail RD‑VBA.

Importation de code source MS‑VBA

Les utilisateurs de Rubberduck dans le VBIDE connaissent probablement déjà les fonctionnalités d’exportation et de synchronisation de projets destinées au travail sous gestion de versions.

Sinon, exportez simplement les modules de votre projet dans un dossier dédié puis ouvrez ce dossier comme espace de travail dans HexIDE. RDCore génère un fichier .rdproj qui recense tous les éléments appartenant au projet, qu’il s’agisse de code source ou non.

Votre espace de travail peut ainsi contenir des fichiers README.md, des images, des ressources localisées ou tout autre actif chargé à l’exécution.

Le code MS‑VBA qui suppose la présence d’un hôte devra être adapté pour recourir à l’automatisation COM externe. Le code qui utilise déjà cette approche devrait fonctionner tel quel.

Importation d’un projet VB6

Les projets VB6 existent déjà sous forme de fichiers et sont décrits par un fichier .vbp. Lorsqu’un tel espace de travail est ouvert dans RDCore, le fichier .rdproj correspondant est généré automatiquement à partir du projet VB6 existant.

Là encore, la compatibilité devrait être largement transparente, avec quelques réserves.

Applications graphiques

RDCore héberge nativement MSForms 2.0 sur les postes Windows qui disposent de cette bibliothèque en version 64 bits. En revanche, il n’héberge pas les formulaires VB classiques, même si tous les symboles associés sont définis au moment de la compilation.

Le projet RDForms est actuellement en développement et sera publié pendant le cycle alpha. Cette infrastructure d’interface utilisateur reposera sur le rendu multiplateforme Avalonia et sur le moteur d’exécution RDCore.

L’objectif est de réunifier les formulaires VB classiques et MSForms dans une seule plateforme moderne capable d’importer les fichiers historiques .frm et .frx, tout en offrant une API événementielle familière pour le code existant et une API MVVM pour les nouveaux développements.

Un concepteur XAML pour HexIDE fait également partie du programme.

D’ici la publication de RDForms, les interfaces utilisateur interactives restent limitées aux systèmes Windows disposant de MSForms 2.0 en version 64 bits.

Applications console

Les applications ne nécessitant aucune interface graphique peuvent s’exécuter partout où .NET est disponible.

Sous Windows, MsgBox utilise une boîte de dialogue Win32 native. Sur les autres plateformes, la fonction est fournie par l’environnement hôte (rdc) et affiche une boîte de dialogue simulée en mode texte dans la console. InputBox suit le même principe.

Lorsqu’une application est exécutée avec rdc run –unattended, toute tentative d’interaction avec l’utilisateur provoque une erreur d’exécution mettant fin au processus.


À vous de jouer!

RDCore entame son cycle alpha avec une implémentation LSP déjà remarquablement avancée. Les fonctionnalités essentielles attendues d’un environnement moderne sont présentes aujourd’hui et continueront d’évoluer au cours des prochains mois.

C’est donc le moment idéal pour explorer RDCore et HexIDE.

Et si vous ne savez pas par où commencer, le dépôt RDCore.Demo.NavalBattle constitue la vitrine officielle de la plateforme. Cette adaptation RD‑VBA du code MS‑VBA original publié sur ce blogue propose une interface MSForms sous Windows et une interface console sur toutes les autres plateformes.

Consultez le site de documentation utilisateur pour découvrir tout ce qu’il faut savoir sur RDCore.


[English]

Rubberduck, reborn.

The RDCore platform has officially released a tagged alpha build: a pre-release that you can download and install, and that runs on Windows, Linux, and macOS. For now, it is only available on 64-bit systems.

The platform is the home of RD-VBA, an implementation of the MS-VBAL specification, corrected in places and enhanced in others, that lets you PEEK and POKE at memory space in BASIC mode, adds #If Linux and #If Linux64 precompiler constants, and compiles to .NET 10 IL.

Download the alpha release here: https://github.com/rubberduck-vba/RDCore/releases/tag/v0.1.0-alpha

RD-VBA

The language core lives in the SDK (NuGet: v0.1.2-alpha) and defines a version of VBA and an implementation of its standard library that runs everywhere .NET runs, without the infamous Microsoft Visual Basic runtime and outside of any host application: the platform provides its own host.

COM Automation

VBA was always able to automate COM without needing to be hosted inside the COM process in question – it’s what you do whenever you set an object variable to a New Excel.Application, or when you CreateObject(“Excel.Application”). RD-VBA running outside a Microsoft Office host means you must do things that way now.

rdc build

What you gain in exchange is the ability to build standalone executables from RD-VBA source code, so CLI commands like rdc build and rdc run do exactly what they sound like they’re doing.

Language Server

The language core alone is just a model. What brings it to life is the LSP client/server architecture of the platform and its components, at the center of which we find the language server, which acts as a coordinator between the host and runtime, the client/IDE, and the platform extensions.

The server delivers LSP 3.17 through OmniSharp 0.19, progress reporting included. Syntax and compilation errors, and run-time errors whenever possible, are reported as design-time diagnostics. Completion lists are triggered for keywords and identifiers, and match PascalCase humps, so “mb” gets you “MidB” and “MsgBox”.

The platform itself doesn’t include an IDE*, but rdc.exe itself is a standalone LSP client that runs a fun RD-VBA/BASIC shell when executed without any command-line arguments.

*but wait, there’s more!

RDCore.HexIDE

Not directly part of the platform bundle, this LSP client is a HexIDE add-in that downloads the RDCore platform, with your consent, if it’s not already installed, and then becomes the bridge between the IDE and the language server.

To install the RDCore.HexIDE add-in, download the signed package from its GitHub release, extract it into its own folder under HexIDE’s addins folder, and restart HexIDE.

HexIDE started as a VB6 IDE project with a toy interpreter – with RDCore as a backend, it becomes the natural home of RD-VBA workspaces.

Importing MS-VBA source code

If you’re using Rubberduck in the VBIDE, you’re probably already familiar with the export project and synchronize folder features, which were intended for working with source control.

Otherwise, export your project’s modules to a dedicated local folder, and open that folder as a workspace in HexIDE: RDCore generates a .rdproj file that enumerates all the files that belong to the project, whether they’re source code or not – so your workspace can contain a README.md file and additional assets (images, resource strings, etc.) that source code loads at run-time.

MS-VBA source code that presumes a host must be adapted to automate COM from the sidelines. MS-VBA source code that already does this should work as-is.

Importing a VB6 project

VB6 projects already exist in the file system, and a .vbp file describes the project: opening such a workspace in RDCore will automatically generate the .rdproj file from the .vbp, and again should work as-is… with a few caveats.

GUI Applications

RDCore hosts native MSForms 2.0 on a Windows desktop that has the 64-bit library. It does not host VB Forms despite having all the symbols defined at compile time; hosting VB forms requires reengineering pieces that belong to Microsoft, and RDCore does not do that.

RDForms is under development and will ship during the alpha cycle; it is the UI framework that RDCore will ultimately be using: Avalonia cross-platform rendering with RDCore runtime support will be combining Classic VB Forms and MS-VBA’s MSForms into a unified, modern UI framework that seamlessly imports legacy .frx and .frm, and then exposes a familiar event-based API for legacy workloads, and an MVVM API for the new ones. A XAML designer for HexIDE is also part of the deal.

Until RDForms releases, interactive UI in RDCore remains limited to Windows machines that have Microsoft’s 64-bit MSForms 2.0 library installed.

Console Applications

An application that doesn’t need to display a UI can run anywhere .NET runs. On Windows, MsgBox is a native Win32 message box; otherwise, the function is implemented by the environment host (rdc) and draws a text-mode message box in the console; InputBox is in a similar condition.

When executed with rdc run with the –unattended switch on, code that requires such user interactions throws at run-time, failing the process.


Playtime!

RDCore launches its alpha cycle much further along its LSP implementation than most other LSP projects would: everything you expect is there and already works, and both the SDK and the platform will keep evolving in the next few months.

This makes the next few months the perfect time to play with RDCore and HexIDE, and if you don’t know where to start, there’s always the RDCore.Demo.NavalBattle repository, which is the platform’s showcase demo: it runs an MSForms UI on Windows, and a console UI everywhere else, and it’s an RD-VBA port of the original MS-VBA code initially published on this blog.

See the user documentation site for everything you need to know.

Lightweight MVVM in VBA

A little while ago already, I went and explored dynamic UI with MSForms in VBA through a lens tinted with Windows Presentation Foundation (WPF) concepts, and ended up implementing a working prototype Model-View-ViewModel (MVVM) framework for VBA… across a hundred and some modules covering everything from property and command bindings to input and model validation. I’m still planning to build an actual COM library for it one day – for now I’m entirely focused on everything around Rubberduck3.

Although… the last month or so has actually been mostly about publishing the new website and setting up the Ko-fi shop: the new website is not without issues (search links are broken, for one), but the source code ownership has been transferred to the rubberduck-vba organization on GitHub and I’m satisfied enough with it to move on.

But then there’s operating the shop. When an order comes in, there’s a worksheet (duh!) with a Sales table where I enter the invoice line items sold using a Stock Keeping Unit (SKU) code that identifies each item sold; the Inventory table picks up the sale and calculates a new Available to Sell figure.

But tracking items sold isn’t the whole picture: an Invoice table tracks the actual totals including the shipping charges and actual shipping costs (currently 24% underwater, but I’ve since adjusted the shipping charges to better reflect reality), computing the Cost of Goods Sold, and ultimately a profit margin.

So for each invoice, I know I need:

  • Invoice number and date
  • Billing/shipping information (name, address, etc.)
  • The number of units sold per SKU, with the amount paid by the customer
  • The shipping charge paid by the customer

And then I manually prepare the invoice document. Such a waste of time, right? Of course I couldn’t leave it at that – all I needed was a UserForm to enter all that, and a command that would update the merchandise planning workbook and prepare the invoice document for me.

Thing is, I wanted that form to use property bindings and some extent of MVVM, but I wasn’t going to import the 100+ modules of the old MVVM prototype code. So instead, I made a “lite” version.

The accompanying code for this article is in the Rubberduck Examples repository.

Property Bindings

Bindings and the propagation of property value changes are the core mechanics that make MVVM work, and we don’t need dozens of classes for that.

We do need INotifyPropertyChanged and IHandlePropertyChanged interfaces:

Option Explicit
Public Sub OnPropertyChanged(ByVal Source As Object, ByVal Name As String)
End Sub
Public Sub RegisterHandler(ByVal Handler As IHandlePropertyChanged)
End Sub
Option Explicit
Public Sub OnPropertyChanged(ByVal Source As Object, ByVal Name As String)
End Sub

These interfaces are important, because the bindings need to handle property changed events; the View Model needs to invoke the registered callbacks. This is used in place of actual events, because interfaces in VBA don’t expose events, and we want an abstraction around property changes, so that everything that needs to notify about property changes can do so in a standardized way.

The IHandlePropertyChanged interface is to be implemented by property binding classes, such as this TextBoxValueBinding class:

Option Explicit
Implements IHandlePropertyChanged
Private WithEvents UI As MSForms.TextBox

Private Type TBinding
    Source As Object
    SourceProperty As String
End Type

Private This As TBinding

Public Sub Initialize(ByVal Control As MSForms.TextBox, ByVal Source As Object, ByVal SourceProperty As String)
    Set UI = Control
    Set This.Source = Source
    This.SourceProperty = SourceProperty
    If TypeOf Source Is INotifyPropertyChanged Then RegisterPropertyChanges Source
End Sub

Private Sub RegisterPropertyChanges(ByVal Source As INotifyPropertyChanged)
    Source.RegisterHandler Me
End Sub

Private Sub IHandlePropertyChanged_OnPropertyChanged(ByVal Source As Object, ByVal Name As String)
    If Source Is This.Source And Name = This.SourceProperty Then
        UI.Text = VBA.Interaction.CallByName(This.Source, This.SourceProperty, VbGet)
    End If
End Sub

Private Sub UI_Change()
    VBA.Interaction.CallByName This.Source, This.SourceProperty, VbLet, UI.Value
End Sub

A binding has a source and a target object and property; the source is a ViewModel object, and the target is a MSForms control, in this case a TextBox. The binding must handle the control’s events to update the source whenever the value of the target changes. In this limited version we’re only going to handle the Change event, but if we wanted we could go further and handle KeyDown here to implement input validation. Some error handling wouldn’t hurt, either.

Because everything that involves notifying about property changes is standardized through interfaces, we can make a PropertyChangeNotification helper class to register the handlers:

Option Explicit
Private Handlers As VBA.Collection

Public Sub AddHandler(ByVal Handler As IHandlePropertyChanged)
    Handlers.Add Handler
End Sub

Public Sub Notify(ByVal Source As Object, ByVal Name As String)
    Dim Handler As IHandlePropertyChanged
    For Each Handler In Handlers
        Handler.OnPropertyChanged Source, Name
    Next
End Sub

Private Sub Class_Initialize()
    Set Handlers = New VBA.Collection
End Sub

This class is responsible for holding a reference to a collection of handlers, and a Notify method invokes the OnPropertyChange method on each registered handler.

ViewModel

The OrderHeaderModel class is the binding source, so it exposes a property representing the value of each field in the form. The Property Let procedures are all structured as follows:

  • If current encapsulated value is not equal to the new value…
    • Set the current value to the new value
    • Notify of a property change

ViewModel classses need to implement INotifyPropertyChange, and the implementation simply uses an instance of the helper class above to do its thing:

Option Explicit
Implements INotifyPropertyChanged

Private Notification As New PropertyChangeNotification

'...

Private Sub OnPropertyChanged(ByVal Name As String)
    INotifyPropertyChanged_OnPropertyChanged Me, Name
End Sub

Private Sub INotifyPropertyChanged_OnPropertyChanged(ByVal Source As Object, ByVal Name As String)
    Notification.Notify Source, Name
End Sub

Private Sub INotifyPropertyChanged_RegisterHandler(ByVal Handler As IHandlePropertyChanged)
    Notification.AddHandler Handler
End Sub

The private OnPropertyChanged method further simplifies the notification by providing the Source argument, which needs to be an instance of the ViewModel, so that’s always Me. So the properties all look more or less like this:

Public Property Get OrderNumber() As Long
    OrderNumber = This.OrderNumber
End Property

Public Property Let OrderNumber(ByVal Value As Long)
    If This.OrderDate <> Value Then
        This.OrderNumber = Value
        OnPropertyChanged "OrderNumber"
    End If
End Property

The ViewModel is inherently domain-specific, so for a form that collects information about an order we’re going to be looking at properties like OrderNumber, OrderDate, BillToName, ShipToAddress, etc.; in another application, a ViewModel could be a completely different thing – it all really depends on what the thing is meant to do. But no matter what the domain is, a ViewModel will be implementing INotifyPropertyChanged as shown above.

View

Implementing the View (the form’s code-behind module) boils down to setting up all the necessary bindings, and we do this using a PropertyBindings helper module:

Option Explicit

'@Description "Binds a MSForms.Control property to a source property"
Public Function BindProperty(ByVal Control As MSForms.Control, ByVal ControlProperty As String, ByVal SourceProperty As String, ByVal Source As Object, Optional ByVal InvertBoolean As Boolean = False) As OneWayPropertyBinding
    
    Dim Binding As OneWayPropertyBinding
    Set Binding = New OneWayPropertyBinding
    
    Binding.Initialize Control, ControlProperty, Source, SourceProperty, InvertBoolean
    
    Set BindProperty = Binding

End Function

'@Description "Binds the Text/Value of a MSForms.TextBox to a source property"
Public Function BindTextBox(ByVal Control As MSForms.TextBox, ByVal SourceProperty As String, ByVal Source As Object) As TextBoxValueBinding
    
    Dim Binding As TextBoxValueBinding
    Set Binding = New TextBoxValueBinding
    
    Binding.Initialize Control, Source, SourceProperty
    
    Set BindTextBox = Binding
    
End Function

'@Description "Binds the Text of a MSForms.ComboBox to a String source property"
Public Function BindComboBox(ByVal Control As MSForms.ComboBox, ByVal SourceProperty As String, ByVal Source As Object) As ComboBoxValueBinding
    
    Dim Binding As ComboBoxValueBinding
    Set Binding = New ComboBoxValueBinding
    
    Binding.Initialize Control, Source, SourceProperty
    
    Set BindComboBox = Binding

End Function

'@Description "Binds the Value of a MSForms.CheckBox to a Boolean source property"
Public Function BindCheckBox(ByVal Control As MSForms.CheckBox, ByVal SourceProperty As String, ByVal Source As Object) As CheckBoxValueBinding
    
    Dim Binding As CheckBoxValueBinding
    Set Binding = New CheckBoxValueBinding
    
    Binding.Initialize Control, Source, SourceProperty
    
    Set BindCheckBox = Binding

End Function

As you can see each MSForms control gets its Binding class, and a OneWayPropertyBinding binds a source property to a target property without notifying for target changes (so without listening for control events) – this is useful for binding labels, ListBox/ComboBox contents, and anything else that doesn’t involve control events.

The form has a private ConfigureBindings method (invoked from the UserForm_Initialize handler) where we essentially map each one of the form controls to corresponding ViewModel properties:

Private Sub ConfigureBindings(ByVal Model As INotifyPropertyChanged)

    Const EnabledProperty As String = "Enabled"
    Const ListProperty As String = "List"
    
    This.Bindings.Add BindTextBox(Me.BillToNameBox, "BillToName", This.OrderModel)
    This.Bindings.Add BindTextBox(Me.BillToAddressLine1, "BillToLine1", This.OrderModel)
    This.Bindings.Add BindTextBox(Me.BillToAddressLine2, "BillToLine2", This.OrderModel)
    This.Bindings.Add BindTextBox(Me.BillToAddressLine3, "BillToLine3", This.OrderModel)
    This.Bindings.Add BindTextBox(Me.BillToEmailBox, "EmailAddress", This.OrderModel)
    This.Bindings.Add BindCheckBox(Me.BillToContributorBox, "IsContributor", This.OrderModel)
    
    This.Bindings.Add BindCheckBox(Me.ShipToSameBox, "ShipToBillingAddress", This.OrderModel)
    This.Bindings.Add BindTextBox(Me.ShipToNameBox, "ShipToName", This.OrderModel)
    This.Bindings.Add BindTextBox(Me.ShipToAddressLine1, "ShipToLine1", This.OrderModel)
    This.Bindings.Add BindTextBox(Me.ShipToAddressLine2, "ShipToLine2", This.OrderModel)
    This.Bindings.Add BindTextBox(Me.ShipToAddressLine3, "ShipToLine3", This.OrderModel)
    
    This.Bindings.Add BindProperty(Me.ShipToAddressLabel, EnabledProperty, "ShipToBillingAddress", This.OrderModel, InvertBoolean:=True)
    This.Bindings.Add BindProperty(Me.ShipToNameLabel, EnabledProperty, "ShipToBillingAddress", This.OrderModel, InvertBoolean:=True)
    This.Bindings.Add BindProperty(Me.ShipToNameBox, EnabledProperty, "ShipToBillingAddress", This.OrderModel, InvertBoolean:=True)
    This.Bindings.Add BindProperty(Me.ShipToAddressLine1, EnabledProperty, "ShipToBillingAddress", This.OrderModel, InvertBoolean:=True)
    This.Bindings.Add BindProperty(Me.ShipToAddressLine2, EnabledProperty, "ShipToBillingAddress", This.OrderModel, InvertBoolean:=True)
    This.Bindings.Add BindProperty(Me.ShipToAddressLine3, EnabledProperty, "ShipToBillingAddress", This.OrderModel, InvertBoolean:=True)
    
    This.Bindings.Add BindProperty(Me.ItemSkuSelectBox, ListProperty, "Value", InventorySheet.Table.ListColumns("SKU").DataBodyRange)
    This.Bindings.Add BindComboBox(Me.ItemSkuSelectBox, "SKU", This.OrderModel.NewLineItem)
    This.Bindings.Add BindTextBox(Me.ItemQuantityBox, "Quantity", This.OrderModel.NewLineItem)
    This.Bindings.Add BindTextBox(Me.ItemPriceBox, "Price", This.OrderModel.NewLineItem)
    
    This.Bindings.Add BindProperty(Me.LineItemsList, ListProperty, "LineItems", This.OrderModel)

End Sub

This rather straightforward configuration completely replaces event handlers. That’s right: the bindings take care of the control events for us, so checking the ShipToSameBox checkbox automatically disables the ShipToNameLabel, ShipToAddressLabel, ShipToAddressLine1, ShipToAddressLine2, and ShipToAddressLine3 controls on the form, and un-checking it automatically enables them, and we don’t need to explicitly handle any control events to achieve this. Small note: here the View is accessing a table in InventorySheet directly, and it shouldn’t be doing that, because what SKUs are available belongs in the Model, not the View: I should instead implement a service that accesses the worksheet for me and supplies the available SKU codes.

With the form controls effectively abstracted away by the ViewModel, we never need to directly interact with MSForms to affect the View, because the property bindings do this automatically for us. This means commands can affect just the ViewModel, and doing that will automatically keep the View in sync.

Commands

This lite version of MVVM doesn’t (yet?) have command bindings, but UI commands are still abstracted behind an ICommand interface. In my case I needed a command to add a new order line item, so I implemented it like this:

Option Explicit
Implements ICommand

Private Function ICommand_CanExecute(ByVal Parameter As Object) As Boolean
    ICommand_CanExecute = TypeOf Parameter Is OrderHeaderModel
End Function

Private Sub ICommand_Execute(ByVal Parameter As Object)
    If Not TypeOf Parameter Is OrderHeaderModel Then Err.Raise 5
    
    Dim Model As OrderHeaderModel
    Set Model = Parameter
    
    Dim Item As OrderLineItemModel
    Set Item = New OrderLineItemModel
    
    Item.SKU = Model.NewLineItem.SKU
    Item.Quantity = Model.NewLineItem.Quantity
    Item.Price = Model.NewLineItem.Price
    
    Model.AddLineItem Item
    
End Sub

This code is completely oblivious of any form or form controls: it only knows about the OrderHeaderModel and OrderLineItemModel classes, and what it needs to do with them. Why bother implementing this in a separate class, rather than in the form’s code-behind?

Without command bindings, we do need to handle command buttons’ Click event:

Private Sub AddLineItemButton_Click()
    CmdAddLineItem.Execute OrderModel
End Sub

I don’t like having logic in event handlers, so this one-liner is perfect. Without a command class the View would need to have more code, code that isn’t directly related to the View itself, and then the commands’ dependencies would become the View‘s dependencies, and that would be wrong: if I made a “Save to Database” button, I’d want the ADODB stuff anywhere but in the form’s code-behind; command classes can have their own dependencies, so pulling commands into their own classes keeps the View cohesive and focused on its purpose.

I’m finding that MVVM works best with relatively complex forms such as this one, where some fields’ enabled state might depend on some checkbox control’s value, for example. There’s something oddly satisfying typing something in a textbox and seeing another (disabled!) textbox get updated with the same content, knowing zero event handling is going on in the form.

Viability

If the full-featured MVVM framework isn’t viable in VBA, a more lightweight version of the UI paradigm certainly is: this particular VBA project doesn’t have dozens of class modules, and yet still manages to leverage what makes Model-View-ViewModel such a compelling architecture.