RAS Playground 日本語 GitHub

Language and projects

Language specification


1. Design philosophy and basic policy


2. Type system and variable declarations

2.1 Basic data types and their VBA counterparts

The TypeScript number type does not exist (writing number produces an error saying to use int or double). The numeric types follow C# names.

RAS type VBA type Size Notes
byte Byte 8-bit unsigned
short Integer 16-bit
int Long 32-bit Default type of integer literals
long LongLong 64-bit 64-bit Office only. In targets that include 32-bit, use outside a #If Win64 guard is an error (§11.3)
float Single 32-bit floating point
double Double 64-bit floating point Default type of decimal literals
currency Currency 64-bit fixed point
decimal Variant (CDec) 96-bit VBA has no variable declaration for the Decimal type, so it is stored in a Variant
RAS type VBA type Notes
ptr LongPtr (VBA7) / Long (VBA6) Pointers and handles. See §11
currency Currency
date Date
byte Byte
string String
boolean Boolean
any Variant Unknown type, mixed types
cellValue Variant A cell value. An any that may be an error value (such as #N/A). §2.6.6
object Object Late binding
A | B (union type) Object / Variant Object if all members are object types, otherwise Variant. §2.6
Excel.Range etc. Range etc. (early binding) From the host type library. §15.3
RAS class Generated class name
struct / { a: A; b: B } / [A, B] Type (user-defined type) Value type. §2.5
T[] Dynamic array T() See the array rules in §13

2.2 Numeric literals

Written as Type VBA output
123 int (long if it does not fit in int) 123&
123L long 123^
1.5, 1e3, 2d double 1.5#
1.5f float 1.5!
1.5m decimal CDec("1.5")
0xFF int &HFF&
0cA, 0cAA, 0cXFD int (column number; A = 1) 1&, 27&, 16384&

2.3 Numeric operations and type conversion

Follows the C# rules.

2.4 Generics

Type parameters can be used in functions, extension methods, and classes. VBA has no generics, so a separate function or class is emitted for each combination of type arguments actually used in the project (monomorphization). No common Variant-based implementation is emitted.

export function maxOf<T extends Comparable>(this: T[]): T {
    let m = this[0];
    for (const v of this) if (v > m) m = v;
    return m;
}

class Stack<T> {
    private items: T[] = [];
    push(x: T): void { this.items.push(x); }
    pop(): T { return this.items.pop(); }
}

const a = ints.maxOf();          // T = int
const b = names.maxOf();         // T = string
const s = new Stack<Excel.Range>();

Output VBA code:

Public Function maxOf__Long(ByRef this_() As Long) As Long
    ' ...
End Function

Public Function maxOf__String(ByRef this_() As String) As String
    ' ...
End Function

For a class, one class module is emitted per type argument, such as Stack__Range.cls.

2.4.1 Rules

2.5 Structs, object literals, tuples, and destructuring

Containers that group multiple values are converted to VBA's Type (user-defined type). In a Type, the position of each field is determined at compile time, and neither memory allocation nor reference counting occurs on creation, so it is lighter than a class (which creates a COM object for each New) or a Scripting.Dictionary (late binding and hash lookup). In an array, the elements are laid out in a contiguous area.

2.5.1 Structs and object literals

struct Point { x: int; y: int; name?: string; }

function make(x: int, y: int): Point {
    return { x, y };              // name is omitted (only fields marked with `?` can be omitted)
}
Public Type Point
    x As Long
    y As Long
    name As String
End Type

Private Function make(ByVal x As Long, ByVal y As Long) As Point
    make.x = x
    make.y = y
End Function

2.5.2 Anonymous object types

An object literal with no expected type becomes an anonymous struct determined by its field names and value types. It can also be written in a type annotation in the form { a: A; b: B }. If the field names and types are the same, it is the same type regardless of the order written (they are emitted together as one Type).

const o = { count: 1, label: "two" };          // the type is { count: int; label: string }
function stats(xs: double[]): { min: double; max: double } { ... }

It is a different type from a named struct even if the fields are the same (they cannot be assigned to each other).

2.5.3 Tuples

[A, B] is an anonymous struct with fields by position. When the expected type is a tuple, an array literal becomes that value. Elements are referenced with integer literal subscripts (t[0]).

function divmod(a: int, b: int): [int, int] {
    return [a / b, a % b];
}
Public Type RAS_Tup1
    item0 As Long
    item1 As Long
End Type

Private Function divmod(ByVal a As Long, ByVal b As Long) As RAS_Tup1
    divmod.item0 = a \ b
    divmod.item1 = a Mod b
End Function

Types that contain type parameters cannot be used in the fields of anonymous object types and tuples (declare a struct).

2.5.4 Destructuring

In const / let declarations and in the variable of for...of, you can write an object pattern { a, b: alias } and an array pattern [a, , c]. They expand into declarations that extract struct or tuple fields and array elements. Nested patterns, default values, and ... are not supported.

const { x, y: py } = make(1, 2);
const [q, r] = divmod(17, 5);
for (const { x, y } of points) total += x * y;
ras_d1 = make(1&, 2&)
x = ras_d1.x
py = ras_d1.y

2.5.5 Arrays of structs

When the T of T[] is a struct, it becomes an array Dim a() As T. push in a loop uses the capacity-doubling method (§13.3), and literals write directly into elements.

In VBA, for (const p of ps) copies each element into p, but if the loop body only reads the fields of p and the array cannot be changed during the loop, the element is referenced directly without copying.

for (const p of ps) total += p.x + p.y;
For ras_i = 0 To RAS_Len_Point(ps) - 1&
    total = total + (ps(ras_i).x + ps(ras_i).y)
Next ras_i

The element is not referenced directly (it is copied) when any of the following holds: p is used as a whole (assigned or passed to a function), the fields of p are modified, or the loop body touches the array itself. When the array is an argument, there is the further condition that the loop body does not call a function and does not assign to an array element.

An array of structs cannot be put in a Variant, so the length is obtained not with the runtime RAS_Len but with RAS_Len_<type name>, generated for each struct. For the same reason, indexOf / includes / join / sort / reverse cannot be used (methods that take a callback, such as findIndex, can be used; write the arrow function directly as the callback).

2.5.6 Map whose value is a struct

A struct cannot be put in a Scripting.Dictionary. When the V of Map<K, V> is a struct, the compiler replaces this type with a class (RAS_StructMap__<K>_<V>.cls, one for each combination of K and V) that lays out the values in an array of structs and keeps only the key-to-index mapping in a Dictionary. Usage is the same as a normal Map (get / set / has / delete / size / keys() / values() / clear()).

const m = new Map<string, Point>();
m.set("a", { x: 1, y: 2 });
total += m.get("a").x;

2.5.7 Places where structs cannot be used

A VBA Type cannot be converted to a Variant and cannot appear in the public members of a class module. The following are compile-time errors.

Use a class when you want to share references, hold null, or put it in any.

2.6 Union types

A type whose value is one of several types is written A | B. Unlike any, only operations common to all members can be used; anything else is used after narrowing the type with a type guard (§2.6.4).

function describe(s: Excel.Worksheet | Excel.Chart): string {
    s.activate();                                  // common members can be used without narrowing
    if (s instanceof Excel.Worksheet) {
        return `${s.name}: ${s.usedRange.address()}`;  // here s is Excel.Worksheet
    }
    return s.chartTitle.text;                      // here s is Excel.Chart
}

function cellText(v: string | double): string {
    if (typeof v == "String") return v;            // v: string
    return v.toFixed(2);                           // v: double
}

Output VBA code:

Private Function describe(ByVal s As Object) As String
    s.Activate
    If (TypeOf s Is Worksheet) Then
        describe = s.Name & ": " & s.UsedRange.Address()
        Exit Function
    End If
    describe = s.ChartTitle.Text
End Function

Private Function cellText(ByVal v As Variant) As String
    If TypeName(v) = "String" Then
        cellText = v
        Exit Function
    End If
    cellText = RAS_ToFixed(v, 2&)
End Function

2.6.1 Types and storage

2.6.2 Assignment and operations

2.6.3 Members

2.6.4 Type narrowing

For local variables and arguments, the type is narrowed by type guards in conditional expressions.

Type guard When the condition is true When the condition is false
x instanceof T T (for a union type, the members that can be instances of T) The union type with the members of T removed
typeof x == "name" The members whose TypeName is "name" ("String" → string, "Long" → int and enums, "Worksheet" → Excel.Worksheet) The other members

2.6.5 Union types in the bundled type definitions

Among the members for which the type library returns Object / Variant, those whose actual return type is determined are made union types in the bundled type definitions.

Member Type
activeSheet, application.activeSheet, Workbook.activeSheet, Window.activeSheet Excel.Worksheet | Excel.Chart
Elements of a sheet collection (sheets(1), for (const s of thisWorkbook.sheets), Window.selectedSheets, sheets.add()) Excel.Worksheet | Excel.Chart
Worksheet.next, Worksheet.previous Excel.Worksheet | Excel.Chart
Shape.parent, Shapes.parent, ChartObject.parent, ChartObjects.parent, PageSetup.parent Excel.Worksheet | Excel.Chart
Chart.parent (the workbook for a chart sheet, a ChartObject for an embedded chart) Excel.Workbook | Excel.ChartObject
Name.parent (the workbook for a workbook-level name, the sheet for a sheet-level name) Excel.Workbook | Excel.Worksheet
Window.rangeFromPoint(x, y) Excel.Range | Excel.Shape
application.statusBar (false when Excel manages the display) string | boolean
application.getSaveAsFilename(...) (false on cancel) string | boolean
application.getOpenFilename(...) (false on cancel; an array of paths if multiSelect is true) string | boolean | any[]
const f = application.getOpenFilename("Excel workbooks,*.xlsx", 1, "Workbook to open", "Open", true);
if (typeof f == "Boolean") return;          // cancelled
if (typeof f == "Variant()") {
    for (const path of f) workbooks.open(path);
} else {
    workbooks.open(f);                     // f: string
}

for (const sh of thisWorkbook.sheets) {
    if (sh instanceof Excel.Worksheet) {
        sh.cells(1, 1).value = sh.name;
    } else {
        sh.chartTitle.text = sh.name;      // sh: Excel.Chart
    }
}

2.6.6 Cell values (cellValue)

A cell value can be, besides numbers, strings, and so on, a cell error value (#N/A, #DIV/0!, etc.; vbError of a VBA Variant). When VBA compares, operates on, or converts an error value, run-time error 13 (type mismatch) occurs only if the value is an error value, which makes it hard to find in testing. Such values are represented by the type cellValue, and places that use them without checking are warned about.

const v = ws.range("A1").value;          // v: cellValue
if (v == "Done") { ... }                  // warning W0313 (a run-time error for #N/A)
if (isError(v)) return;
if (v == "Done") { ... }                  // v: any. No warning
const n = cLng(v);                       // warning W0315 (a run-time error for "twelve")
const m: int = v;                        // warning W0315 (so is the implicit conversion)
if (isNumeric(v)) total += cLng(v);      // no warning

const rows = Excel.errorToNull(ws.range("A1:C9").toArray());   // any[][]
const price = Excel.errorToNull(ws.cells(r, 3).value) ?? 0;

function lookup(code: string) {          // the return value is inferred as cellValue
    return application.vLookup(code, Sheet2.range("A:C"), 3, false);
}

2.7 Excel formulas (fx`…`)

The counterpart of VBA's [A1] and [SUM(A1:A10)] (shorthand for Evaluate) is a template literal with the tag fx. […] is not used because it cannot be distinguished from an array literal.

const total = fx`SUM(A1:A10)`;                      // Evaluate("SUM(A1:A10)")
const price = ws.fx`VLOOKUP(${code}, 'Price list'!A:C, 3, FALSE)`;
                                                    // ws.Evaluate("VLOOKUP(" & code & ", 'Price list'!A:C, 3, FALSE)")
ws.range("B1").value = fx`TODAY()`;

2.8 Regular expression literals (/…/)

Writing /pattern/flags creates a VBScript.RegExp (§15.3) with that pattern and those flags set.

const re = /(\d{4})\/(\d{1,2})/g;          // Set re = RAS_SharedRegExp("(\d{4})\/(\d{1,2})", "g")
if (/^abc/i.test(s)) return;               // If RAS_SharedRegExp("^abc", "i").Test(s) Then
for (const m of /[A-Z]+/g.execute(s)) n += m.length;
const guide = /^ガイド\d+$/w;               // RAS_SharedRegExp("^(?:ガ|ガ)[イイ](?:ド|ド)[0-90-9]+$")
const own = /abc/;                         // Set own = RAS_RegExp("abc")
own.ignoreCase = true;

3. Function definitions and arguments (ByVal / ByRef)

To prevent the accidents caused by VBA defaulting to ByRef, RAS makes ByVal the default and requires pass-by-reference to be explicit.

3.1 Conversion example

RAS code:

function calculate(x: double, byref outResult: double): boolean {
    outResult = x * 2;
    return true;
}

Output VBA code:

Private Function calculate(ByVal x As Double, ByRef outResult As Double) As Boolean
    outResult = x * 2&
    calculate = True
End Function

3.2 Extension methods

Like C# extension methods, they let you add methods to existing types (primitive types, arrays, COM types such as Excel's, and RAS classes) after the fact and call them as x.method().

3.2.1 Syntax

The TypeScript this parameter syntax is reused. A function whose first argument is written as this: Type becomes an extension method (editor assets derived from TS highlight it as is).

// strutil.ras
export function isBlank(this: string): boolean {
    return this.trim().length == 0;
}

export function padLeft(this: string, width: int, ch: string = " "): string {
    return this.length >= width ? this : ch.repeat(width - this.length) + this;
}

// excelutil.ras
export function lastRow(this: Excel.Worksheet, col: int = 1): int {
    return this.cells(this.rows.count, col).end(xlUp).row;
}

export function sum(this: double[]): double {
    let t = 0.0;
    for (const v of this) t += v;
    return t;
}

3.2.2 Call site

import { isBlank, padLeft } from "src/strutil";
import * as xl from "src/excelutil";   // even with a namespace import, all extension methods in the module are enabled

if (!name.isBlank()) {
    code = id.padLeft(6, "0");
}
const last = Sheet1.lastRow();

Output VBA code:

    If Not StrUtil.isBlank(name) Then
        code = StrUtil.padLeft(id, 6&, "0")
    End If
    last = ExcelUtil.lastRow(Sheet1, 1&)

3.2.3 Resolution rules

  1. Type members take precedence: if the receiver's type (COM type library or RAS class) has a method/property of the same name, that one is called (same as C#). The extension method gets a "hidden by a type member and never called" warning.
  2. Scope: candidates are the extension methods defined in the same module and the exported extension methods of imported modules.
  3. Applicability: the receiver's static type must match the type of this, or be compatible through an implicit conversion (a widening conversion of §2.3, a matching array element type, class inheritance or interface implementation).
  4. Choose the most specific candidate: when several candidates apply, the one that needs fewer conversions is chosen. If none stands out, it is an ambiguity error.
  5. Receivers of type any / object: since the static type is unknown, extension methods are not resolved (the call becomes a late-bound member call). If an extension method of the same name is in scope, an "extension method is not used" warning is issued.
  6. null receiver: even when an object-typed receiver is Nothing, the call is made (same as C#). Inside the extension method you can test this == null.

3.2.4 Standard library

3.3 Named arguments

An argument can be passed in the form argumentName: value. Use it to skip over optional arguments (those with a default value or with ?) and specify only a later argument.

RAS code:

function label(a: int, b: int = 2, c: string = "x"): string { ... }

export function demo(ws: Excel.Worksheet) {
    const s = label(a: 123, c: "abc");
    const r = ws.range("A:A").find("x", lookAt: xlWhole, matchCase: true);
    msgBox("Done", title: "Summary");
}

Output VBA code:

s = label(123&, 2&, "abc")
Set r = ws.Range("A:A").Find("x",,, xlWhole,,, True)
MsgBox "Done",, "Summary"

3.4 Omitting arguments (undefined)

Writing undefined in the middle of a positional argument list means that optional argument is not specified (label(1, undefined, "z")). It is treated the same as an argument skipped with a named argument.

Passing an omitted argument through as is: if you write an optional argument of type any (tip?: any, with no default value) as is in an argument of an Excel / VBA member or of a late-bound call, then when it was omitted (the value is Empty) it is also omitted at the destination (sheet.hyperlinks.add(cell, "", screenTip: tip)). This lets you relay an optional argument to a member that cannot accept Empty as a value. The output is RAS_Opt(tip). When passed to a RAS function, it is passed as an ordinary value (Empty).

3.5 Variadic arguments (...rest: any[])

Declaring the last argument as ...name: any[] receives all arguments passed from that position onward as an array, in any number (VBA's ParamArray).

RAS code:

export function joinPath(first: string, ...rest: any[]): string {
    if (rest.length == 0) return first;
    return first + "\\" + rest.join("\\");
}

export function demo(): string {
    return joinPath("C:", "work", 2026);
}

Output VBA code:

Public Function joinPath(ByVal first As String, ParamArray rest() As Variant) As String
    Dim ras_rest As Variant

    ras_rest = rest
    If RAS_Len(ras_rest) = 0& Then
        joinPath = first
        Exit Function
    End If
    joinPath = first & "\" & RAS_Join(ras_rest, "\")
End Function

Public Function demo() As String
    demo = joinPath("C:", "work", 2026&)
End Function

3.6 Accessors (properties: get / set)

get name(): T { ... } (getter) and set name(value: T) { ... } (setter) declare a property. They become the VBA Property Get / Property Let / Property Set procedures. They exist so that Property procedures found in hand-written VBA can be written in RAS without changing the public name or shape. They can be written in two places.

The rules are common to both.

3.6.1 Module properties

An accessor written at the top level of a file becomes a property of that file's module. You can write one getter and one setter with the same name (it cannot be declared together with a function or variable of the same name; E0101).

3.6.2 Properties with arguments

Getters and setters can take arguments (both for classes and for modules). This corresponds to VBA's Property procedures with arguments (Property Get Item(ByVal key As String) As Variant).

RAS code:

// src/settings.ras
let cache: int;
let names: string[] = ["", "", ""];

/** Total. */
export get total(): int {
    return cache;
}
export set total(v: int) {
    cache = v;
}

// Property with arguments: the last argument of the setter is the assigned value
export get label(i: int): string {
    return names[i];
}
export set label(i: int, value: string) {
    names[i] = value;
}

export function demo(ws: Excel.Worksheet, o: object) {
    total = 3;
    total += 1;
    label(0) = "x";
    label(0) += "y";
    ws.cells(1, 2) = total;      // §3.6.3: assignment to the value of a cell range
    o.prop(1) = label(0);        // §3.6.3: late binding
}

// src/main.ras
export function run() {
    Settings.total = Settings.total + 1;
    Settings.label(2) = "z";
}

Output VBA code:

' Settings.bas
' Total.
Public Property Get total() As Long
Attribute total.VB_Description = "Total."
    total = cache
End Property

Public Property Let total(ByVal v As Long)
    cache = v
End Property

Public Property Get label(ByVal i As Long) As String
    label = names(i)
End Property

Public Property Let label(ByVal i As Long, ByVal value_ As String)
    names(i) = value_
End Property

Public Sub demo(ByVal ws As Worksheet, ByVal o As Object)
    total = 3&
    total = total + 1&
    label(0&) = "x"
    label(0&) = label(0&) & "y"
    ws.Cells(1&, 2&) = total
    o.prop(1&) = label(0&)
End Sub

' Main.bas
    Settings.total = Settings.total + 1&
    Settings.label(2&) = "z"

3.6.3 Assigning to properties with arguments on Excel / VBA objects and late-bound members

In VBA you can assign to a property with arguments, as in ListBox1.Selected(i) = True, ws.Cells(1, 2) = x and obj.Prop(i) = v. RAS lets you write the same form.


4. Anonymous functions (lambda expressions) and array operations

Anonymous functions are specialized for operating on arrays and collections (map, filter, forEach, reduce, some, every, find, findIndex, sort, etc.). Taking part of an array or string (the range xs[1..^1]) is covered in §4.5.

4.1 Transpilation specification

Lambda expressions are converted with the following priority.

  1. Loop fusion (default): when a lambda expression is written directly as a literal as the argument of an array method, no class is generated; it is expanded directly into a loop at the call site. A chain such as arr.filter(...).map(...) is fused into a single loop.
    • As in JavaScript, the index a callback receives is "the position within the array on which that method was called". Fusion does not change this. For the stage after a filter (the i in arr.filter(f).map((x, i) => ...), or the result of arr.filter(f).findIndex(g)), it is the position among the elements that passed the filter. Only when the later stage uses the index are the elements that passed counted at each filter.
  2. Closure class (only when escaping): only when the body cannot be identified at the call site, such as when the lambda is assigned to a variable, passed as a function argument, or becomes a return value, a class module (RAS_Lambda_001.cls) is generated as before.
    • Captured constants become public fields and are copied once at creation.
    • In arrow functions in the code-behind of a form and in the file of a sheet (ThisWorkbook), this represents that form (sheet or workbook) (the form that created the class is held in Captured_Me). Functions and variables of the form's code-behind refer to those of the form that created the class, not to the form name (the default instance). Referenced functions and variables are emitted as Public (a private method of a class called as this.helper() from an arrow function is emitted as Public too). VBA cannot place Public array or struct variables in an object module, so referring to an array or struct variable of a form or sheet file from inside an arrow function is an error (E0642). Constants have their values embedded.
    • The evaluation method is named Apply. It is called from the runtime (RAS_Runtime.bas) by late binding. Invoke cannot be used because it collides with the member name of IDispatch and causes a compile error in a class module ("This member identifier already exists in the object module").
    • The linter issues a hint (Information) that "this lambda is converted to a class and is therefore slow".

4.2 Conversion example (loop fusion)

RAS code:

const base = 10;
let arr = [1, 2, 3];
let result = arr.map(x => x * base);

Output VBA code:

Public Sub Main()
    Dim base As Long
    Dim arr() As Long
    Dim result() As Long
    Dim ras_i1 As Long

    base = 10&
    ReDim arr(0 To 2)
    arr(0) = 1&: arr(1) = 2&: arr(2) = 3&
    If RAS_Len(arr) > 0 Then
        ReDim result(0 To UBound(arr))
        For ras_i1 = 0 To UBound(arr)
            result(ras_i1) = arr(ras_i1) * base
        Next ras_i1
    Else
        Erase result
    End If
End Sub

4.3 Conversion example (escaping lambda)

RAS code:

const base = 10;
const f = (x: double) => x * base;
let result = applyAll(arr, f);

Output VBA code (RAS_Lambda_001.cls):

Public Captured_base As Long

Public Function Apply(ByVal x As Variant) As Variant
    Apply = x * Me.Captured_base
End Function

4.4 Host collections

Host (COM) collections such as worksheets / workbooks / ws.shapes / Excel.Range can also have their members processed with the same notation as arrays.

const names = worksheets.filter(ws => ws.visible == xlSheetVisible).map(ws => ws.name);
worksheets.forEach((ws, i) => { ws.cells(1, 1).value = i; });
const data = thisWorkbook.worksheets.find(ws => ws.name == "Data");   // null if not found

RAS code:

const names = worksheets.filter(ws => ws.visible == xlSheetVisible).map(ws => ws.name);

Output VBA code:

Dim names_() As String
Dim ras_e As Worksheet
Dim ras_n As Long

ras_n = 0&
If Worksheets.Count > 0& Then
    ReDim names_(0 To Worksheets.Count - 1&)
    For Each ras_e In Worksheets
        If ras_e.Visible = xlSheetVisible Then
            names_(ras_n) = ras_e.Name
            ras_n = ras_n + 1&
        End If
    Next ras_e
End If
If ras_n = 0& Then
    Erase names_
ElseIf ras_n <= UBound(names_) Then
    ReDim Preserve names_(0 To ras_n - 1&)
End If

4.5 Ranges and positions from the end (.. / ^)

With the same notation as C#, you can take part of an array or string and refer to positions counted from the end.

const last = xs[^1];          // the last element (xs[xs.length - 1])
const body = xs[1..^1];       // a copy without the first and last elements
const head = s[..3];          // the first 3 characters (s.slice(0, 3))
for (const i of 0..n) { }     // i = 0, 1, ..., n - 1
const odd = xs[1..].step(2);  // the 1st, 3rd, 5th, ... elements (0-based)
const rev = xs.toReversed();  // a reversed copy (xs is unchanged)
const t = m.transpose();      // a copy of a 2-D array with rows and columns swapped (t[c][r] is m[r][c])

RAS code:

function report(xs: int[], s: string) {
    const last = xs[^1];
    const body = xs[1..^1];
    for (const i of 0..body.length) {
        console.log(i, body[i]);
    }
    console.log(last, s[..^1]);
}

Output VBA code:

Private Sub report(ByRef xs() As Long, ByVal s As String)
    Dim last As Long
    Dim body() As Long
    Dim ras_t1 As Long
    Dim ras_t2 As Long
    Dim ras_t3 As Long
    Dim ras_i As Long
    Dim i As Long
    Dim ras_y1 As Long

    last = xs(RAS_Len(xs) - 1&)
    ras_t1 = RAS_Len(xs)
    ras_t2 = RAS_ClampRange(1&, ras_t1)
    ras_t3 = RAS_ClampRange(ras_t1 - 1&, ras_t1) - ras_t2
    If ras_t3 > 0& Then
        ReDim body(0 To ras_t3 - 1&)
        For ras_i = 0 To ras_t3 - 1&
            body(ras_i) = xs(ras_t2 + ras_i)
        Next ras_i
    Else
        Erase body
    End If
    For i = 0 To RAS_Len(body) - 1&
        Debug.Print CStr(i) & " " & CStr(body(i))
        ras_y1 = ras_y1 + 1&
        If (ras_y1 And ras_yieldMask) = 0& Then RAS_Yield
    Next i
    Debug.Print CStr(last) & " " & RAS_StrRange(s, 0&, Len(s) - 1&)
End Sub

4.6 VBA arrays held in any (multiple indexes, redim / redimPreserve / erase)

RAS arrays (T[] / T[][]) are 0-based, and RAS manages their size (§13.3). Hand-written VBA, on the other hand, puts arrays into a Variant and uses them with arbitrary lower bounds and multiple dimensions (ReDim a(1 To n, 1 To 3), v(i, j) after v = Range("A1:C10").Value, LBound(v, 2)). So that such code can be written as it is, there is a notation for handling an array held in any (VBA's Variant) with the same indexes as VBA. For newly written code, use typed arrays (T[]) and range.toArray().

function fillTable(rows: int, cols: int): any {
    let t: any;
    redim(t, 1, rows, 1, cols);               // ReDim t(1 To rows, 1 To cols)
    for (let r = 1; r <= rows; r++) {
        t[r, 1] = r;                          // t(r, 1) = r
        t[r, cols] = t[r, 1] * 2;
    }
    redimPreserve(t, 1, rows, 1, cols + 1);   // ReDim Preserve t(1 To rows, 1 To cols + 1)
    return t;
}
Private Function fillTable(ByVal rows_ As Long, ByVal cols As Long) As Variant
    Dim t As Variant
    Dim r As Long
    Dim ras_t1 As Variant
    Dim ras_y1 As Long
    Dim ras_t2 As Variant

    ReDim t(1 To rows_, 1 To cols)
    For r = 1 To rows_
        t(r, 1) = r
        RAS_Assign ras_t1, t(r, 1) * 2&
        If IsObject(ras_t1) Then
            Set t(r, cols) = ras_t1
        Else
            t(r, cols) = ras_t1
        End If
        ras_y1 = ras_y1 + 1&
        If (ras_y1 And ras_yieldMask) = 0& Then RAS_Yield
    Next r
    ReDim Preserve t(1 To rows_, 1 To cols + 1&)
    RAS_Assign ras_t2, t
    If IsObject(ras_t2) Then
        Set fillTable = ras_t2
    Else
        fillTable = ras_t2
    End If
End Function

5. Error handling

Based on TypeScript's try ... catch ... finally, it expresses VBA's On Error GoTo and On Error Resume Next safely.

5.1 Standard exception catching (abort type)

catch (e) is converted into an On Error GoTo label jump, and the try block is aborted at the point where the error occurs.

5.2 Error-ignoring block (forced-through type: On Error Resume Next)

A special syntax in which only a resume; statement is written in the catch block.

RAS code:

try {
    let ws = worksheets("NonExistent");
    ws.activate();
} catch {
    resume;
}

Output VBA code:

On Error Resume Next
Set ws = Worksheets("NonExistent")
ws.Activate
On Error GoTo 0

(Dim ws As Object is hoisted to the start of the procedure; §13.1)

5.3 finally and using


6. Main validation rules of the linter (static analysis)

It validates in real time in the editor and emits Diagnostics.

  1. Syntax errors
  2. Reassignment to const is forbidden
  3. Lambda capture violations
  4. Purity check of resume blocks
  5. Passing a literal to byref is forbidden
  6. (Added) Collision of identifiers that differ only in case: VBA is case-insensitive and the VBE rewrites the case of identifiers across all modules, so having both foo and Foo is an error (§13.6).
  7. (Added) Collision with VBA reserved words and built-in names: a warning that it will be renamed automatically (§13.6).
  8. (Added) Recursive or non-expandable inline functions: a directly or indirectly recursive inline function is an error.
  9. (Added) Dependence on unqualified range / cells / activeSheet: a warning (§13.4).
  10. (Added) Use of .select() / .activate() / selection: information (performance and stability).
  11. (Added) Characters that cannot be represented in the code page: information that they were escaped automatically (§13.7).
  12. (Added) Predicted violation of VBA structural limits: the 64 KB procedure limit, the 24 line-continuation limit, etc. (§13.8).
  13. (Added) Visualization of optimizations: places where inline expansion, bulk transfer and loop fusion were applied or could not be applied are shown with a Hint and CodeLens (with the reason).
  14. ** Spelling of host names:** writing Excel / VBA / Office members and globals in the VBA spelling (ws.Cells, MsgBox) gives a warning (W0304). The meaning does not change, and ras check --fix and the quick fix rewrite them to camelCase (§15.3.1).
  15. ** typeof comparison:** comparing with a JavaScript type name, as in typeof x == "string", gives a warning (W0312). typeof returns the same name as VBA's TypeName (§2.6.4).
  16. (Added) Use of a cell value (cellValue): using a cellValue value, which may be an error value (such as #N/A), in a comparison, an operation, a condition, a type conversion, or an assignment to something other than cellValue without narrowing it with isError() or the like gives a warning (W0313). This is because VBA raises run-time error 13 (type mismatch) only when the value is an error value (§2.6.6).

7. Toolchain architecture

7.1 Overall structure

┌──────────────── VS Code ────────────────┐
│ ras-vscode (thin extension)             │
│  - TextMate Grammar (TS-derived)        │
│  - the ras.path setting names the binary│
│  - just launches `ras lsp --stdio`      │
└──────────────┬──────────────────────────┘
               │ LSP (JSON-RPC over stdio)
┌──────────────▼──────────────────────────┐
│ ras (single binary)                     │
│  parser → resolver → typecheck → HIR    │
│  → optimization (§8, §9, §4) → VBA lowering │
│  → emitter (.bas/.cls/document modules) │
│  LSP server / watch / sync client       │
└──────────────┬──────────────────────────┘
               │ shared memory (MMF) + COM notification (§14.1 to 14.8)
               │ * if the workbook is closed, reads/writes the .xlsm directly (§14.9)
┌──────────────▼──────────────────────────┐
│ Excel  ─ RASBridge.xlam (sync add-in)   │
│        ─ target workbook (.xlsm)        │
└─────────────────────────────────────────┘

7.2 Implementation language

7.3 CLI

Command Description
ras init Generates ras.toml and a scaffold. For the empty workbook of --workbook, the font of the "Normal" style is chosen, as Excel does for a new workbook, according to the PC's display language (for Japanese, Yu Gothic 11)
ras check [--fix] Type check and lint only. --fix writes warnings that can be fixed mechanically (§6 rule 14) back to the source and then checks
ras build [--release] Outputs the VBA files to build/. --release defaults the optimization level to -O2
ras watch Incremental build plus live sync while watching for changes
ras sync [--pull] Syncs with Excel once (--pull is the Excel → local direction)
ras pack [<book>] Rewrites the VBA project inside the workbook file directly, without starting Excel (§14.9). --via-excel switches to writing through an invisible Excel
ras unpack [<book>] Extracts the VBA source from the workbook file into vba/, without starting Excel (§14.9)
ras lsp --stdio Starts as an LSP server (called from the VS Code extension)
ras setup The "Trust access to the VBA project object model" setting (sets the registry value AccessVBOM with the user's consent) and installation of RASBridge
ras typegen <TypeLib> Generates RAS type definitions (.d.ras) from a COM type library
ras fmt Formatter
ras test [<file>...] Runs the tests in test/ (§14.12). By default it runs on the Excel stand-in without using Excel, and --excel runs against the real Excel. --reporter json outputs the results as JSON
ras run [<Module.proc>] Runs a function without Excel and shows the output, errors and changed cells (§14.13). --json outputs the result as JSON
ras book dump [<book>] / ras book diff <before> <after> / ras book view [<book>] / ras book samples <recipe> / ras book new <book> Outputs the contents of a workbook as text, compares two workbooks, and shows it as a grid (§14.14)
ras sheet add / copy / remove / rename / list Adds, copies, deletes and renames sheets, changing the workbook and the files in objects/ together (§14.16)
ras excel run <Module.proc> [args…] / ras excel compile / ras excel compare Writes the project into a copy of the workbook and runs a function, or compiles the VBA, in an Excel started for it; reads and answers the dialogs and shows where errors are in the .ras sources (Windows only, §14.17)
ras explain [<code>] / ras cheatsheet Shows the explanation of an error or warning code (§14.15) and the syntax cheat sheet
ras doc <name> Shows the API of the type definitions (signature, description, VBA name, whether the stand-in has it) (§14.15)

7.4 Responsibilities of the VS Code extension (minimal)

7.5 Output layout (build artifacts)


8. Optimization: inline expansion and automatic expansion in loops

Function calls carry a large overhead in VBA (especially when arguments are Variant or the call crosses modules). RAS reduces calls with the following two mechanisms.

8.1 The inline keyword (explicit inlining)

inline function clamp(v: double, lo: double, hi: double): double {
    return v < lo ? lo : (v > hi ? hi : v);
}

8.2 Automatic expansion in loops

At -O1 and above, calls inside a loop body (including nested loops) that satisfy all of the following are expanded automatically.

Calls outside loops are expanded only at -O2 and only when the body is very small (cost 10 or less).

8.3 Semantics of expansion (guarantees)

After expansion, the evaluation order, side effects, and by-value / by-reference semantics of the source are preserved exactly.

8.4 Code conversion example

RAS code:

for (let i = 0; i < n; i++) {
    total += clamp(values[i], 0, 100);
}

Output VBA code:

    For i = 0 To n - 1
        ' @inline clamp (util.ras:1)
        If values(i) < 0 Then
            ras_inl1_ret = 0
        ElseIf values(i) > 100 Then
            ras_inl1_ret = 100
        Else
            ras_inl1_ret = values(i)
        End If
        total = total + ras_inl1_ret
    Next i

8.5 Other loop optimizations


9. Automatic bulk conversion between Range and 2D arrays

Reading and writing cells one by one costs one COM call each time and is extremely slow. RAS detects cell-access patterns in loops and automatically converts them to bulk transfers between a Range and a 2D array.

9.1 Writing (loop → array → bulk assignment to Range)

RAS code:

const ws = Sheet1;
for (let r = 2; r <= last; r++) {
    for (let c = 1; c <= 5; c++) {
        ws.cells(r, c).value = r * c;
    }
}

Output VBA code:

    If last >= 2 Then
        ReDim ras_buf1(0 To last - 2, 0 To 4)
        For r = 2 To last
            For c = 1 To 5
                ras_buf1(r - 2, c - 1) = r * c
            Next c
        Next r
        ws.Range(ws.Cells(2, 1), ws.Cells(last, 5)).Value = ras_buf1
    End If

9.2 Reading (bulk fetch of a Range → array reference)

RAS code:

let sum = 0;
for (let r = 2; r <= last; r++) {
    sum += ws.cells(r, 1).value;
}

Output VBA code:

    If last >= 2 Then
        ras_src1 = RAS_Read2D(ws.Range(ws.Cells(2, 1), ws.Cells(last, 1)))
        For r = 2 To last
            sum = sum + ras_src1(r - 2, 0)
        Next r
    End If

RAS_Read2D absorbs the VBA trap that ".Value of a single-cell Range returns a scalar, not an array", and always returns a 0-based 2D array.

9.2.1 Subscript rules (0-based)

9.3 Conditions for applying the conversion

The compiler converts automatically only when all of the following are satisfied (otherwise it does not convert and shows the reason as a Hint).

  1. The target sheet expression is invariant within the loop (a const variable, a code name, or an object fixed outside the loop).
  2. The subscripts are linear expressions of the induction variable (the forms r + k, c - k, where k is loop-invariant), and the rectangular region is statically determined from the loop range (before the loop starts).
  3. The property accessed is one of value / value2 / formula / formulaR1C1, and the same property is used before and after the conversion (.Value is never silently changed to .Value2, because dates and currency values would change).
  4. There are no other operations on the same sheet inside the loop: no formatting changes, Select, row/column insertion or deletion, other cell accesses, or unknown function calls that might touch the sheet (calls that could not be expanded, Application.Run, COM method calls).
  5. For writes, every cell in the rectangle is written unconditionally (no conditional writes, continue, or break). Bulk-writing partial writes would overwrite the formulas of the cells that are not written with values.
  6. The written region is not read back in the same loop (reading back is allowed only when it can be replaced by an array reference).
  7. There is no early exit by break / return / exception (for writes; reads may exit early).

9.4 Explicit control

9.4.1 A range extended up, down, left, and right (extend)

range.extend(up?: int, down?: int, left?: int, right?: int): Excel.Range returns a range with up rows added above, down rows below, left columns to the left, and right columns to the right (saving the trouble of combining Offset and Resize).

const r = Sheet1.range("B3:C3");
r.extend(1, 1, 1, 1);          // A2:D4
r.extend(down: 2);             // B3:C5 (named argument; §3.3)
r.extend(left: 1, right: 2);   // A3:E3
r.extend(undefined, 1);        // B3:C4 (undefined leaves that side unspecified)
Sheet1.range("A1:D4").extend(-1, -1, -1, -1);   // B2:C3 (negative numbers shrink)

9.4.2 A range specified by row and column numbers (ws.range(top, left, bottom, right))

The range of Excel.Worksheet can also be called with four row/column numbers. ws.range(top, left, bottom, right) returns the range from the cell (top, left) to the cell (bottom, right).

Sheet1.range(2, 4, 8, 9);              // D2:I8
Sheet1.range(1, 1, last, 0cE);         // A1:E{last} (can be combined with column-number literals, §2.2)

9.4.3 The bottom-right cell of a range (lastCell)

range.lastCell: Excel.Range is a read-only property that returns the bottom-right cell of a range (the cell in the last row and last column).

const last = Sheet1.usedRange.lastCell;           // bottom-right cell of the used range
const lastRow = Sheet1.usedRange.lastCell.row;    // last used row
Sheet1.range("B3:D9").lastCell;                   // D9

9.5 Extension methods for Range, sheet, and workbook (RAS standard library)

Frequently written Excel macro tasks — finding a table's headings, following merged cells as a single cell, counting the last row, and reading and writing a table by selecting columns by heading — are provided as extension methods of the RAS standard library (§3.2.4; usable without an import). Names and arguments match the APIs of xljs (cool0707/xljs) that do the same thing (sheet.find / findAll, lastRow, pick / untilBlank of toRowObjects, book.sheet, book.copySheet).

Member Description
ws.find(what, match?, strict?, visibleOnly?, order?): Excel.Range The first matching cell in the sheet (null if none)
ws.findAll(…) / range.findAll(…): Excel.Range[] All matching cells
ws.findByHeaders(column, row, strict?, visibleOnly?) / range.findByHeaders(…) The cell where a column heading and a row heading intersect
range.stepOffset(rows?, columns?, visibleOnly = true) The cell moved to, counting a merged cell as one and skipping hidden rows and columns
range.stepResize(rows = 1, columns = 1, visibleOnly = true, withinBorders = false) The range extended with the same way of counting
ws.lastRow(skipBlank?) / ws.lastColumn(skipBlank?), range.lastRow(…) / range.lastColumn(…): int The number of the last row / column with a value or formula (0 if none)
cell.readTable(pick?, untilBlank?): cellValue[][] The table data starting from the top-left cell of the heading row
cell.writeTable(values, pick?) Writes below the table's headings
book.sheet(name) / book.copySheet(sheet, name?, before?, after?) Returns a sheet by name or regular expression / copies a sheet
workbooks.opened(path) / workbooks.ensureOpen(path, readOnly?, updateLinks?) The open workbook / opens it if it is not open

9.5.1 Finding (find / findAll / findByHeaders)

const name = Sheet1.find("氏名");                          // also matches "氏 名" (with a full-width space)
const total = Sheet1.find(/^Total/);                        // regular expression
const codes = Sheet1.columns(1).findAll(/^A-\d+$/, visibleOnly: true);
const april = Sheet1.findByHeaders("Apr", "Sales");         // the cell where the column heading "Apr" and the row heading "Sales" intersect

9.5.2 Following cells (stepOffset / stepResize)

const value = Sheet1.find("Name").stepOffset(0, 1).value;   // right of the heading (one to the right even for a merged input field)
const body = Sheet1.find("Details").stepOffset(1, 0).stepResize(5, 3);
const box = Sheet1.range("B2").stepResize(10, 10, withinBorders: true);   // only inside the border frame

9.5.3 Last row and last column (lastRow / lastColumn)

const last = Sheet1.lastRow();                          // last row with a value or formula in the sheet
const lastA = Sheet1.columns(1).lastRow();              // last row of column A
const lastHead = Sheet1.rows(1).lastColumn();           // last column of row 1
const filled = Sheet1.columns(3).lastRow(skipBlank: true);   // do not count formulas that result in ""

9.5.4 Reading and writing a table (readTable / writeTable)

// From the top-left cell of the heading row, read the table's columns selected by heading (a 2D array; the heading row is not included)
const rows = Sheet1.find("Code").readTable(["Code", /Amount|Sales/, null, 3], untilBlank: true);
// Below the headings, write columns selected by heading (other columns are left as they are)
Sheet2.range("A1").writeTable(rows, ["Code", "Amount"]);

9.5.5 Sheets and workbooks (sheet / copySheet / opened / ensureOpen)

const ws = thisWorkbook.sheet(/^\d{4}-\d{2}$/);        // the first worksheet whose name matches (null if none)
const next = thisWorkbook.copySheet(Sheet1, "May");     // copy right after the source sheet and give it a name
const src = workbooks.ensureOpen(path, readOnly: true); // the workbook if open, otherwise open it
const book = workbooks.opened("sales.xlsx");            // null if not open

10. Controlling application state (one-line API)

A runtime API is provided that stops and resumes screen updating, events, automatic calculation, and so on in one line.

10.1 API list

RAS Description
using _ = fastMode(); Stops screen updating, events, automatic calculation, alert display, and status bar display, and restores the original state when leaving the scope (even on error)
using _ = fastMode({ calc: false }); Individual items can be excluded (screen, events, calc, alerts, statusBar, cursor). interactive: false additionally blocks user input (by default it is not blocked; §10.4.5)
@fast export function f() {...} A decorator that applies fastMode() to the whole function
suspendScreen() / resumeScreen() ScreenUpdating
suspendEvents() / resumeEvents() EnableEvents
suspendCalc() / resumeCalc() Calculation (xlCalculationManual ⇔ the original value)
suspendAlerts() / resumeAlerts() DisplayAlerts
suspendAll() / resumeAll() All of the above
status("Processing 50%") Shows text in the StatusBar (reset to False when fastMode ends)

10.2 Runtime behavior

10.3 Code conversion example

RAS code:

@fast
export function rebuildReport() {
    // ...
}

Output VBA code:

Public Sub rebuildReport()
    RAS_EnsureInit
    On Error GoTo RAS_Handler
    RAS_SuspendAll
    ' ... body ...
RAS_Finally_0:
    RAS_ResumeAll
    Exit Sub
RAS_Handler:
    RAS_ResetAppState
    RAS_ReportError "Report.rebuildReport", Err
End Sub

10.4 Automatic insertion of DoEvents

To keep Excel from showing "Not Responding" during long loops and to let the user interrupt with the Esc key, the compiler automatically inserts DoEvents, thinned out, at places where things are likely to stall. Users do not need to write DoEvents.

10.4.1 Insertion points

It is inserted at the end of a loop (just before returning to the next iteration). The target is a loop that falls under any of the following.

Handling of nested loops:

Outside loops, the standard library's sleep(ms) / waitUntil(...) split the wait into short pieces and call DoEvents between them.

10.4.2 Thinning out

A single DoEvents call is heavy, so it is thinned out in two stages.

  1. Counter check (expanded inside the loop): A check consisting only of one addition and a bit operation. The call to RAS_Yield is limited to once every N iterations.
  2. Time / input check (inside RAS_Yield):
    • DoEvents is called only when a certain time (default 100ms) has passed since the previous DoEvents, or when GetInputState() reports pending input (mouse or keyboard).
    • RAS_Yield looks at the time elapsed since the previous call and adjusts N automatically. N is increased or decreased in powers of 2 so that it is called roughly every 10ms.

Output VBA code (loop side):

    Do While ras_cond1
        ' ... body ...
        ras_y1 = ras_y1 + 1&
        If (ras_y1 And ras_yieldMask) = 0& Then RAS_Yield
    Loop

Output VBA code (runtime side, outline):

Public Sub RAS_Yield()
    Dim now_ As Double
    now_ = RAS_TickMs()                ' GetTickCount value corrected for its 49.7-day wraparound
    RAS_AdjustYieldMask now_           ' raise or lower ras_yieldMask by the interval since the previous call
    If GetInputState() <> 0 Or now_ - ras_lastYield >= RAS_YIELD_MS Then
        ras_lastYield = now_
        DoEvents
    End If
End Sub

10.4.3 Where it is not inserted

10.4.4 Explicit control

10.4.5 Reentry and interruption during DoEvents

During DoEvents, user operations and events are processed, so the runtime automatically takes the following measures.

11. 32-bit / 64-bit support for declare (external DLL functions)

11.1 Syntax

The TS declare module syntax is reused.

declare module "user32" {
    function GetForegroundWindow(): ptr;
    @alias("GetWindowTextW")
    function GetWindowText(hWnd: ptr, lpString: wstr, nMaxCount: int): int;
}
declare module "kernel32" {
    function Sleep(dwMilliseconds: int): void;
    function GetTickCount64(): long;  // 64-bit only → §11.3
}

11.2 Types for declarations

RAS type VBA7 side VBA6 side Notes
ptr ByVal x As LongPtr ByVal x As Long Handles and pointers
int ByVal x As Long same as left
short ByVal x As Integer same as left
byte ByVal x As Byte same as left
long ByVal x As LongLong not available
float ByVal x As Single same as left
double ByVal x As Double same as left
wstr ByVal x As LongPtr ByVal x As Long StrPtr(s) is passed automatically on the calling side (for W-version APIs)
astr ByVal x As String same as left ANSI string (for A-version APIs)
byref T ByRef x As T same as left Output arguments and structures

11.3 Output

For every declare, the compiler emits both the VBA7 form (PtrSafe, LongPtr) and the VBA6 form using conditional compilation.

#If VBA7 Then
Private Declare PtrSafe Function GetForegroundWindow Lib "user32" () As LongPtr
Private Declare PtrSafe Function GetWindowText Lib "user32" Alias "GetWindowTextW" (ByVal hWnd As LongPtr, ByVal lpString As LongPtr, ByVal nMaxCount As Long) As Long
#Else
Private Declare Function GetForegroundWindow Lib "user32" () As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextW" (ByVal hWnd As Long, ByVal lpString As Long, ByVal nMaxCount As Long) As Long
#End If

12. Automatic boilerplate generation

12.1 Common to all modules

The following is added to every module automatically. Users do not write it.

No standard module is generated from a file that has no meaningful code (a file with only comments, blank lines and imports, which generates no functions, variables, constants, types or the like). Such a file is not included in the output of ras build, nor in what sync and ras pack write to the workbook. A module generated earlier is removed by sync as one that is no longer generated. Files for sheets and ThisWorkbook (§12.2) are treated as "modules with no code" when they have no code, because the module itself cannot be deleted (code generated earlier is cleared by sync; §14.6).

12.1.1 Correspondence between files and modules

RAS files and VBA modules correspond one to one, so that you can tell from the name alone which module of the workbook a file's code goes into, and which file the code of a workbook module came from.

RAS file VBA module Notes
src/<name>.ras Standard module <name>
objects/<sheet code name>.ras The module of that worksheet §12.2. objects/ corresponds to "Microsoft Excel Objects" in the VBE Project Explorer
objects/ThisWorkbook.ras The workbook module (ThisWorkbook) §12.2
forms/<form name>.ras The code module of that user form §14.11.2

12.1.2 Calling by module name (no import)

The name of the standard module of a src/ file (the module name from §12.1.1; main.ras → Main) is, like a sheet's code name (§12.2), a global name that can be referenced from any file without import. Main.hoge() resolves the same as when you write import * as Main from "src/main", and the generated VBA is the same (Main.hoge()). This is the same notation as qualifying a call to another module's Public procedure with the module name in VBA.

// src/util.ras
export function bar(): int {
    return Main.hoge() + 1;     // export function hoge in src/main.ras
}

// objects/Sheet1.ras
export function baz() {
    msgBox(Util.bar());         // export function bar in src/util.ras
}

12.1.3 import paths

In the from of an import, from any file, write the path from the project folder (the folder containing ras.toml) without the .ras extension. The notation does not depend on where the file is, so you do not need to change imports when you move a file.

import { padLeft } from "src/lib/str";        // src/lib/str.ras
import { setupBook } from "test/helper";      // test/helper.ras (only from test-side files)
import { z } from "validation";               // the RAS standard library has no path

12.2 Sheet and ThisWorkbook files (document modules)

The code of worksheet and ThisWorkbook modules (document modules) is written in objects/<sheet code name>.ras and objects/ThisWorkbook.ras (objects/ is the directory corresponding to "Microsoft Excel Objects" in the VBE Project Explorer, placed directly under the project alongside src/ and forms/). The compiler emits such a file not as a standard module but as the entire code of that document module. Document modules cannot be imported as files even in the VBE, so sync (§14.6) and ras pack (§14.9) write directly into the code module. This is the same form as a form's code-behind (§14.11.2).

Implementation note (current version): This section, §12.1.1, §12.2.1 to §12.2.3, the handling of document modules in §14.6, §14.7.1 to §14.7.3 and §14.9, and ras sheet in §14.16 are implemented. The VBA generated for on in §12.2.3 (the listener class, off(), the name set in OnAction, cancelling by returning false), ras sheet against a workbook open in Excel (§14.16), and duplicating the file of a sheet duplicated in Excel (§14.7.2) were verified on a real Excel 2021.

// objects/Sheet1.ras (module of the sheet with code name Sheet1)
let lastEdited = "";

@on("Worksheet.Change")
function onChange(target: Excel.Range) {
    lastEdited = target.address;
    this.range("D1").value = now();
}

@on("Worksheet.BeforeDoubleClick")
function onDoubleClick(target: Excel.Range, byref cancel: boolean) {
    cancel = true;
}

/** Clears the input area (can be called from other modules as `Sheet1.clearInput()`). */
export function clearInput() {
    this.range("A2:C100").clearContents();
}
// objects/ThisWorkbook.ras (workbook module)
@on("Workbook.Open")
function setup() { ... }

@on("Workbook.SheetChange")
function onAnySheetChange(sh: object, target: Excel.Range) { ... }

12.2.1 ActiveX controls on a sheet

An ActiveX control placed on a sheet (command button, combo box, etc.) is a member of that sheet's module in VBA, and its events are received in the sheet's module. In RAS too, you write this in that sheet's file.

// objects/Sheet1.ras
@on("CommandButton1.Click")
function run() {
    this.CommandButton1.caption = "Running…";
    rebuildReport(this.ComboBox1.text);
}

@on("ComboBox1.Change")
function kindChanged() { ... }

@on("TextBox1.KeyDown")
function keyDown(keyCode: MSForms.ReturnInteger, shift: short) {
    if (keyCode.value == vbKeyReturn) this.range("B2").select();
}

12.2.2 Events received with WithEvents

Events of an object held in a variable (VBA's WithEvents) are received with @on("<variable name>.<event>"), writing the variable's name. There is no notation corresponding to WithEvents; the compiler declares a variable that has an @on handler with WithEvents.

// objects/ThisWorkbook.ras: receives the events of all open workbooks
let app: Excel.Application;

@on("Workbook.Open")
function start() {
    app = application;          // receiving starts at the point of assignment; assigning null stops it
}

@on("app.SheetChange")
function onAnyChange(sh: object, target: Excel.Range) { ... }

@on("app.WorkbookBeforeClose")
function onClose(wb: Excel.Workbook, byref cancel: boolean) { ... }
// src/watcher.ras: class fields can receive events too (when attaching the same handler to several objects)
export class ButtonWatcher {
    private button: MSForms.CommandButton;

    constructor(button: MSForms.CommandButton) { this.button = button; }

    @on("button.Click")
    private clicked() { msgBox(this.button.caption); }
}

Class events (event): Writing event name(arguments); in a class makes it an event raised by objects of that class (VBA's Event). An event is raised by calling it the same way as a method (VBA's RaiseEvent). The receiving side writes @on("<variable name>.<event>") for a variable or field of that class's type.

// src/Bell.ras
export class Bell {
    event Rang(times: int, byref heard: int);

    ring(times: int): int {
        let heard = 0;
        this.Rang(times, heard);     // RaiseEvent Rang(times, heard)
        return heard;                // the value the receiving side put in the byref argument
    }
}

// objects/Sheet1.ras
let doorBell: Bell;

@on("doorBell.Rang")
function onRang(times: int, byref heard: int) { heard += times; }

12.2.3 Event handlers attached at run time (on / addEventListener)

@on decides the correspondence between handler and event at compile time. When it must be decided at run time (attaching the same handling to all text boxes of a form, attaching and detaching depending on conditions, attaching to objects created at run time), call the object's on. It corresponds to the DOM's addEventListener and jQuery's on.

// forms/frmEdit.ras
let edited = 0;

@on("UserForm.Initialize")
function init() {
    this.btnOK.on("Click", () => { this.hide(); });
    this.btnCancel.addEventListener("Click", cancel);       // same as on; a function name can be passed too

    // Attach to a collection or array: attaches to every control that has the event. The handler receives which control it is as its first argument
    this.controls.on("KeyDown", (c, keyCode) => { if (keyCode.value == 27) unload(this); });
    [this.btnOK, this.btnCancel].on("MouseMove", (button) => { button.backColor = rgb(220, 235, 255); });

    // Narrow down by kind and attach to all text boxes
    for (const c of this.controls) {
        if (c instanceof MSForms.TextBox) {
            c.on("Change", () => {
                edited++;                                    // event handlers can rewrite module variables (§4)
                c.backColor = c.text == "" ? rgb(255, 230, 230) : rgb(255, 255, 255);
            });
        }
    }
    this.txtName.on("KeyDown", (keyCode, shift) => {         // argument types are determined by the event
        if (keyCode.value == 13) this.btnOK.setFocus();
    });
}

function cancel() {
    unload(this);
}
// src/watch.ras: sheets, workbook, Application, shapes
export function start() {
    const l = Sheet1.on("Change", (target) => { status(`Changed: ${target.address}`); });
    thisWorkbook.on("BeforeClose", () => confirmClose());    // returning false cancels
    application.on("SheetActivate", (sh) => { console.log(sh.name); });
    l.off();                                                 // detach

    // Shapes and Form Control buttons: sets the macro name in OnAction
    Sheet1.shapes("btnReload").on("Click", reload);
}

function confirmClose(): boolean {
    return msgBox("Close it?", vbYesNo) == vbYes;
}

export function reload() {
    Sheet1.calculate();
}

12.3 Initialization guarantee (@init)

An @init function is run "exactly once for each state of the VBA project".

If you write initialization only in Workbook_Open, it is not run, or fails, in the following cases:

RAS calls RAS_EnsureInit from all of the following paths, and limits it to once with an initialized flag.

  1. Workbook_Open. It initializes right there and calls the @on("Workbook.Open") handlers. However, if the workbook is leaving Protected View ("Enable Editing"), it is deferred until the next Workbook_Activate / Workbook_WindowActivate. This is because Workbook_Open at that moment occurs before the Protected View workbook closes, and object model calls (such as Range.Select) fail with error 1004 (the same as the workaround for Microsoft's "Object Model calls may fail from WorkbookOpen event when exiting Protected View"; whether the workbook is in Protected View is checked with Application.ProtectedViewWindows). Deferring with Application.OnTime is not used: if the workbook is closed before the scheduled call, Excel reopens the workbook to make the call (for example when it was opened and immediately closed inside a macro), and the schedule cannot be cancelled from an event that fires while closing
  2. Auto_Open
  3. Workbook_Activate / Workbook_WindowActivate (the handlers deferred in 1 are also called here)
  4. The beginning of every macro entry point (@macro / argument-less exported Subs, button and ribbon callbacks)
  5. The ribbon's onLoad callback

The calls from Workbook_Open / Workbook_Activate / Workbook_WindowActivate are boilerplate that the compiler adds to the ThisWorkbook module (§12.1.1). They are written to ThisWorkbook even in a project that has no objects/ThisWorkbook.ras (no code).

If EnableEvents is left as False during initialization, a warning is logged and it is set back to True (this can be disabled in ras.toml).

12.4 Automatic wrapping of macro entry points

The following is added automatically to functions that can be called directly by the user (macro entry points).

12.5 Restoring the ribbon reference

When @ribbon is specified, the IRibbonUI reference is also saved with ObjPtr into a hidden defined name (a hidden name in Workbook.Names), and is restored automatically so that RAS.ribbon.invalidate() works even after a state reset (the restore code using CopyMemory is emitted to work on both 32-bit and 64-bit, per §11).


13. Automatically avoiding VBA pitfalls

The compiler and runtime avoid the following automatically, without the user having to think about them.

13.1 Declarations and initialization

13.2 Operations and evaluation

13.3 Strings, arrays and collections

13.4 References to sheets and Ranges

13.5 Control flow

13.6 Identifiers

13.7 Character encoding

13.8 Structural limits of VBA


14. Excel sync (live sync / offline writing)

14.1 Purpose and approach

14.2 Components

Implementation note (current version): The current implementation uses neither RASBridge nor shared memory. ras (ras sync / ras watch / the sync thread of the LSP server) operates the VBE object model (VBComponents, CodeModule) directly through COM. The connection (step 1 of §14.3), the application rules (§14.6), and the handling of drift (§14.7) are as described in this section and the following ones; read "Bridge" as "ras's sync thread". The transfer through shared memory (§14.4) and the Bridge-side polling (§14.5) will be added later as a speed-up of the same rules.

14.3 Connection

  1. Find the workbook given in the workbook key of ras.toml (full path) by enumerating the running Excel instances from the COM ROT (Running Object Table). Multiple instances are supported.
  2. If it is found, create the shared memory Local\RAS.<workspaceId> (workspaceId is generated from the workbook's full path and a random session token) and call Application.Run "RASBridge.xlam!RAS_Connect", <name>, <token> through COM.
  3. If the workbook is not open: ras watch waits and connects when the workbook is opened (notified from RASBridge's Application.WorkbookOpen event). ras pack writes directly to the file (§14.9).

14.4 Shared memory layout

Offset  Size  Contents
0       4     magic "RAS1"
4       4     protocol version
8       8     writer sequence number (incremented by ras)
16      8     acknowledged sequence number (incremented by the Bridge)
24      4     state (0=empty, 1=sent, 2=applying, 3=done, 4=failed)
28      4     payload length (bytes)
32      ...   payload

14.5 Notification

14.6 Application by the Bridge

14.7 Excel → local direction (--pull / automatic)

Implementation note (current version): Two-way sync of unmanaged modules (saving to vba/ and detecting changes) and the vba: import are not implemented. Instead, on every sync, the workbook's hand-written VBA is converted to RAS, imported into the project, and moved under RAS management (§14.7.1).

14.7.1 Importing hand-written VBA (moving to RAS management)

Live sync (ras sync, ras watch, the VS Code language server) and ras pack read the workbook's VBA project before writing, convert the hand-written code that RAS does not yet manage into RAS, and import it into the project. This feature moves an existing workbook as is into a RAS project, and can be disabled with [sync] pull-unmanaged = false in ras.toml.

In the workbook Imported into Condition
Standard module Module1 src/Module1.ras No RAS-GENERATED line, and it has code. The project has no module (file) with the same name
Hand-written code in the module of sheet Sheet1 / ThisWorkbook objects/Sheet1.ras / objects/ThisWorkbook.ras (§12.2) No RAS-GENERATED line, and it has code (modules with only Option statements and comments are excluded). The corresponding file does not exist, or exists without code (a file left as created by §14.7.2 is replaced with the imported content)
User form frmInput created in the VBE forms/frmInput.form.json and forms/frmInput.ras (same as §14.11.6) No marker line (' RAS-FORM). forms/ has no file with the same name
Class module Equipment export class Equipment in src/Equipment.ras No RAS-GENERATED line, and it has code. The project has no module (file) with the same name

Replacement: The first line of an imported file gets the marker // RAS-IMPORTED <name>. Sync treats files with the marker as follows.

Imported file The workbook's hand-written code
Has no // TODO(VBA): line Replaced with the code generated from that file (no overwrite option needed). Standard modules, forms, and sheet / ThisWorkbook modules are all replaced as a whole module
Has a // TODO(VBA): line Left as is, not replaced. The module generated from that file is not written (for ThisWorkbook, the boilerplate to add (§12.3) is not written either). It is shown in the sync result as "not replaced"

14.7.2 Creating a file for each sheet

Sync (ras sync, ras watch, the VS Code language server) and ras pack create, for each worksheet of the workbook and for ThisWorkbook, the module's file objects/<code name>.ras (objects/Sheet1.ras) / objects/ThisWorkbook.ras (§12.2) if it does not exist. This runs after the import of §14.7.1. It can be disabled with [sync] sheet-files = false in ras.toml.

// This is the module of the sheet "Sales" (code name Sheet1) (created during sync).
// The code written in this file becomes the module of sheet Sheet1 in the workbook (spec §12.2).
// Events are received by functions with @on("Worksheet.<event name>"). Example:
//
//   @on("Worksheet.Change")
//   function onChange(target: Excel.Range) {
//       // When a cell value changes. This sheet is represented by this: this.range("A1")
//   }

14.7.3 Importing code added in the VBE

When a module that RAS generated (one with a RAS-GENERATED line) is edited in the VBE, sync compares the generated code with the current module and imports what was added into the RAS file. This is to bring edits such as adding a sheet event procedure in the VBE (choosing from the object and procedure lists) or appending a procedure to a standard module back into the RAS file.

14.7.4 Blocks written as VBA (vba), and type-based rewriting in import

vba blocks: Writing vba`…` at the top level of a file outputs the VBA inside the backticks as is into that file's module. It is for keeping, inside the project, VBA that cannot be written in RAS (As Any in Declare, conditional compilation, a backward GoTo, etc.).

// src/Util.ras
vba`
Private Declare PtrSafe Function SafeArrayAllocDescriptor Lib "oleaut32" ( _
        ByVal cDims As Long, ByRef ppsaOut() As Any) As Long
`;

vba`
Public Function EmptyLongArray() As Long()
    If SafeArrayAllocDescriptor(1, EmptyLongArray) <> 0 Then Err.Raise 5
End Function
`;
export declare function EmptyLongArray(): any;

export function demo(): int {
    return uBound(EmptyLongArray());   // -1
}

Handling in import (§14.7.1): After conversion (VBA → RAS), import finishes in the following order.

  1. Type-based rewriting: Among the things VBA does implicitly, those that cannot be decided without knowing types are rewritten from the result of type-checking the imported files as a project. Rewrites are limited to those that give the same result as VBA.

    Converted RAS Type Rewrite
    if (n), while (n) number, enum n != 0
    !n integer ~n (VBA's Not is a bitwise operation)
    a && b, a || b integer (one side may be any) a & b, a | b
    A Range used as a value (comparison, assignment, embedding in a string, condition) Excel.Range Add .value (default member)
    f(…) = v (the function returns a Range) Excel.Range f(…).value = v
    Assignment among numbers, strings, dates, and booleans — cStr(x), cLng(x), x as int, etc. Boolean → number is (x ? -1 : 0), number → boolean is x != 0
    Comparison of a number with a string or boolean — cDbl(x) for a string, -1 / 0 for true / false
    letValue(x) (the right side of an assignment without Set) x.value for Range, x for numbers, strings, etc. Where the type is unknown (any, object), it remains letValue(x)

    The mechanical fixes of ras check --fix (spelling of Excel / VBA members, etc.) are also applied at the same time.

  2. Procedures that do not compile: A procedure in which errors remain after step 1 is replaced, for that procedure only, with a vba block (and a declare function), and imported again. A procedure whose original VBA is wrong (VBA does not compile until use, so errors in unused procedures tend to remain) is also kept as is this way. Within a block, project names (enum members, names like Trim_) are rewritten to the generated VBA names. Class methods and Property cannot be made vba blocks, so they remain as errors.

  3. The sync result shows the names of the procedures left as VBA.

Other things kept as VBA at the conversion stage (vba blocks) are: Declare; ranges of conditional compilation; procedures containing statements that cannot be converted (error handling with Resume <label>, a forward GoTo, etc.); arrays with a specified size at module level (Private a(1 To 8) As String); a Type with a fixed-size array field; and Types in sheets, ThisWorkbook, and forms (struct cannot be written in those files). Procedures that use them are also kept as VBA, and the argument types of the declare function are any. Other Types become struct.

Separately from import, a function in a sheet or ThisWorkbook file whose name equals a hidden member of Worksheet / Workbook (the Excel 5 events OnSheetActivate, OnDoubleClick, OnEntry, OnCalculate, etc., and drawing-object collections such as Buttons) is output in VBA with a trailing _ (as is, it would not compile, with "This member identifier already exists in the object module").

Built-ins used by import:

Name Meaning VBA
letValue(x) The value that VBA's v = x (without Set) stores. If x is an object, the value of its default member (v = ws.Range("A1") is the cell value); otherwise x RAS_LetValue(x)
dynamicArray() The array with no elements yet that Dim a() declares (isArray is true, and uBound is run-time error 9 until redim). Used as the initial value of an any variable (§4.6) RAS_DynamicArray()
isAllocated(a) Whether the array has space to hold elements (false for an array still at dynamicArray() and after erase). Not Not a (an array variable) in VBA code becomes this, and Not a becomes (isAllocated(a) ? 1 : -1) RAS_IsAllocated(a)

VBA arrays are handled with their declared lower bound, so import makes them any (§4.6) (Dim a() As String → let a: any = dynamicArray();, ReDim a(1 To n) → redim(a, 1, n);, a(i, j) → a[i, j]).

14.8 Source maps and debugging

14.9 Offline writing (Excel not running)

Without starting Excel, ras reads and writes the VBA project inside the workbook file directly. It is supported from the first release. It is used for builds and generating deliverables in CI, for working in environments without Excel, and for reflecting changes while the workbook is closed.

14.9.1 Target files

Format Support
.xlsm / .xltm / .xlam Supported (xl/vbaProject.bin inside the OPC zip)
.xlsb Supported (same)
.xlsx Converted to .xlsm and output at ras pack time (--convert). The original file is not rewritten
.xls (BIFF8) Not supported

14.9.2 File structure and write procedure

vbaProject.bin is a compound file (CFB), and the following are rewritten according to [MS-OVBA].

  1. VBA/<module> stream: The module source is encoded in the target's code page (§13.7) and stored in the MS-OVBA compression format. P-code (the performance cache) is not written, and the stream contains only the source (MODULEOFFSET = 0).
  2. VBA/_VBA_PROJECT stream: Replaced with the minimal form that indicates no performance cache (7-byte header, Version = 0xFFFF). As a result, Office recompiles from the source on the next open, and no P-code inconsistency occurs even between Office versions with different build numbers (including 32-bit / 64-bit).
  3. VBA/dir stream (compressed): PROJECTCODEPAGE and the module records (name, Unicode name, stream name, kind, MODULEOFFSET, MODULEPRIVATE, etc.) are regenerated to match additions, deletions, and renames.
  4. PROJECT stream: The Module= / Class= / Document= / BaseClass= lines and the [Workspace] section are regenerated. Existing values such as ID, CMG / DPB / GC (protection information), and HelpFile are preserved.
  5. PROJECTwm stream: The MBCS / Unicode name mapping table of the module names is regenerated.
  6. Class attributes: Attribute lines such as VB_PredeclaredId are stored at the beginning of the source (the constraint that required Import in live sync does not exist offline).
  7. Document modules: ThisWorkbook and sheet modules are rewritten only if they correspond to workbookPr/@codeName in xl/workbook.xml and sheetPr/@codeName of each sheet. The whole module source is replaced with code generated from the corresponding file (§12.2) (the leading Attribute lines are left as they were. Handling of modules with hand-written code remaining, etc., is the same as §14.6). ras pack and sync do not create or delete sheets (adding, duplicating, and deleting sheets is ras sheet; §14.16). If the workbook has no sheet corresponding to a file in objects/, it is an error (E0610; §12.2).
  8. User forms and other storages: Unmanaged forms (designer storage) are reconstructed from .frm / .frx in vba/. For forms in forms/, the designer storage is generated from the FormSpec and written (§14.11). Storages with no changes are preserved byte for byte.
  9. OPC package: The vbaProject.bin part, relationships, and [Content_Types].xml (application/vnd.ms-office.vbaProject, with the workbook's main content type changed to the macro-enabled version) are made consistent. Other parts are copied as zip entries without recompression.

14.9.3 Safety

14.9.4 Offline reading (ras unpack)


14.10 Debug execution (JavaScript runtime)

An execution path separate from VBA, for setting breakpoints, stepping, and inspecting variables in VS Code. It converts RAS source to JavaScript and runs it on Node.js, performing only the Excel operations through COM against a real Excel. In environments without Excel (macOS, Linux, Windows without Excel installed), it runs against a stand-in that loads the project's workbook (§14.10.8).

14.10.1 Policy

14.10.2 Output (ras build --target js)

The following files are written to build/debug/ (recreated on every build).

File Contents
<module>.js / <module>.js.map The JavaScript and Source Map for each module. Mapping is per statement, and sources is a relative path to the .ras file. Only modules of the standard library (<stdlib>/…; there is no file on disk) have the source text in sourcesContent
@forms/<form name>.js / .js.map A form's code-behind (forms/<form name>.ras). §14.10.7
ras-runtime.js The runtime ($rt). Numeric conversion, overflow checks, string functions, error objects, VBA standard functions, and access to Excel
ras-forms.js The user form runtime (MSForms objects and events, communication with the host that displays forms). §14.10.7
ras-scripting.js Scripting.FileSystemObject, Scripting.Dictionary, VBScript.RegExp, and ADODB.Stream for when COM is unavailable. §14.10.5
ras-excel.js The Excel stand-in (objects such as Application, Workbook, Worksheet, and Range, plus workbook and sheet events). Used when Excel is unavailable. §14.10.8
ras-main.js The launcher. Run it with node --enable-source-maps build/debug/ras-main.js <module name.function name> (--list prints the runnable functions as JSON)
ras-debug.json The list of runnable functions and the list of forms (read by the VS Code extension)

What can be run is top-level functions callable without arguments, Main (top-level statements), and forms (<form name>.show displays the form; §14.10.7). Before running, module initialization and the @init function are executed once (the same as VBA's RAS_EnsureInit).

14.10.3 Connecting to Excel

14.10.4 Semantics matched to the VBA build

14.10.5 What is not reproduced, and limitations

14.10.6 Monitoring Excel dialogs

A COM call does not return while Excel is showing a modal dialog. This mainly happens in the following cases during debug execution, and since Excel is behind VS Code, the program looks frozen if nothing is done.

Only while a call has not returned for 0.3 seconds or more, ras_com.node inspects the top-level windows of the Excel process on a separate thread (when no call is pending, such as while stopped at a breakpoint, it does nothing).

How dialogs are handled is chosen with dialogs in launch.json (or the setting ras.debug.dialogs, or the environment variable RAS_DIALOGS).

Value Behavior
notify (default) Notifies and brings the dialog to the front (if the OS refuses to bring it to the front, the taskbar flashes). The user responds
dismiss Notifies, and then closes the dialog with a response if one can be chosen safely (see below). Intended for runs nobody is watching (agents, CI)
off No monitoring

Responses that dismiss chooses:

Dialog Response
A VBA run-time error "End" (access key E). "Debug" is not chosen because it leaves the VBE in break mode and later COM calls would no longer go through
Has an IDCANCEL / IDCLOSE button That button
Has only one possible response (excluding Help; an information message or a compile error) That button. If the call still does not return after closing a VBE dialog (a compile error), VBA is stopped in break mode, so the VBE's "Reset" (control ID 228) is run to make the call return (as with "End" for a run-time error, VBA's state is reset)
An Office dialog with no child windows WM_CLOSE (treated the same as Cancel)
Anything else (those that need a choice, such as "Yes / No") Not closed. It only notifies and waits for the user's response

Buttons are pressed with BM_CLICK, and if the dialog does not close, it retries with a WM_COMMAND notification (up to 3 times). It does not give responses that involve entering a value and continuing (such as typing into an InputBox). As a result of closing the dialog, the original call may return with an error (such as error 1004 for a canceled operation).

14.10.7 User forms

A form's code-behind (§14.11.2) is also a target of debug execution. The debug execution process cannot receive Excel's form events, so the form is not displayed in Excel but in a VS Code panel. The code-behind runs as JavaScript like other modules, and breakpoints, stepping, and variable inspection are available. Excel operations (reading and writing cells and so on) are still performed against the real Excel.

Trigger Events
Creating an instance UserForm.Initialize (after module variables are initialized)
Display UserForm.Activate, then Enter of the first control in tab order
Focus move (click, Tab key, setFocus()) BeforeUpdate (if the value changed), AfterUpdate, and Exit of the control being left, then Enter of the control moved to. If cancel in BeforeUpdate / Exit cancels it, the focus does not move, and that click or input does not take place either
Input (TextBox / ComboBox) Change (per character)
Click Click of a CommandButton and the like. A CheckBox / OptionButton / ToggleButton changes its value and raises Change and Click (an OptionButton in the same group becomes false and raises Change). A CheckBox / ToggleButton with tripleState set to true changes in the order false → null → true → false, as in Excel (tripleState has no effect on an OptionButton)
List selection (ComboBox / ListBox) Change, Click
SpinButton arrows Moves the value by smallChange and raises Change, SpinUp / SpinDown
ScrollBar / MultiPage / TabStrip operations Change
Double-click DblClick
Pressing and releasing a key KeyDown of the control that has the focus (the form without one), KeyPress for a key that types a character (including Enter, Backspace, Esc, and Ctrl+letter), the input (Change), KeyUp. Setting keyCode.value to 0 in KeyDown cancels its KeyPress and input, and setting keyAscii.value to 0 in KeyPress cancels its input (the text is put back). Setting keyAscii.value to another character types that character. Keys of the IME's conversion raise nothing
Pressing and releasing a mouse button MouseDown and MouseUp of the control (the form outside the controls) (button 1 left, 2 right, 4 middle, shift, the position from the control's top left in points). A click then raises Click
Enter / Esc key Click of the CommandButton whose default / cancel is true
Close button (the panel's ✕, closing the panel's tab) UserForm.QueryClose (closeMode = vbFormControlMenu). If cancel is set to a nonzero value, it does not close (if the tab was closed, the panel is reopened). On closing, UserForm.Terminate
unload(this) UserForm.QueryClose (closeMode = vbFormCode), UserForm.Terminate

Handlers attached to a control with on (§12.2.3) are called after that control's @on handlers, in the order they were attached (except for Enter / Exit / BeforeUpdate / AfterUpdate raised by the form). They are detached when the form is closed.

Change and the like are also raised when properties are changed in code, as in VBA (changes to text, value, and listIndex). MouseMove, drag and drop, and Deactivate are not raised. The panel does what a key does by default (moving the caret, selecting in a list and so on) itself, so setting keyCode.value to 0 cancels only the text it types.

14.10.8 Debug execution without Excel (Excel stand-in)

So that programs that operate Excel can be debugged even in environments where Excel cannot be driven through COM. In place of Excel, the workbook of workbook in ras.toml is loaded as a file, and the program reads and writes that workbook's cells. Formulas are calculated by the GridCraft calculation engine used by xljs (cool0707/xljs; xljs's vendor/gridcraft, including changes to match Japanese Excel).

14.10.9 Pausing (debugger statement)

debugger; is a statement that pauses execution at that position if a debugger is attached (the same as TypeScript / JavaScript). It is used to stop where a breakpoint cannot be placed or is hard to place (right after starting a run in the playground, module initialization, tests).

export function rebuild() {
    for (let r = 2; r <= last; r++) {
        if (ws.cells(r, 1).value == "") debugger;   // stop only on rows where the cell is empty
        total += ws.cells(r, 2).value;
    }
}

14.10.10 Debugging in the playground (browser developer tools)

The playground (web/) runs the output of ras build --target js (§14.10.2) in a Web Worker. For the debugger it uses the browser's developer tools (such as Chrome / Edge DevTools) as is, and the playground itself has no debugger (the same policy as §14.10.1).

14.10.10 Run mode of the sheet preview

When the VS Code extension's sheet preview is showing the project's workbook (workbook in ras.toml), the switch at the right end of the ribbon tabs toggles between edit mode and run mode. Edit mode edits the workbook file (§14.14). Run mode corresponds to Excel with "Design Mode" turned off, and operations on the sheet raise the program's events.

14.11 User forms (forms/)

User form designs (control layout and properties) are managed as text and written into the workbook without starting Excel. Existing forms in a workbook can also be extracted. The design format, the generation process, and the reading of designer storage are ports of the FormSpec and its pure Go implementation from xlflow (MIT License, Copyright (c) 2026 harumiWeb) (crates/ras-form).

14.11.1 Files

File Contents
forms/<Name>.form.json The design. FormSpec (schemaVersion 1; a JSON format based on xlflow's FormSpec). The file name must match form.name
forms/<Name>.ras The code-behind. Written in RAS and compiled into the form's code module (§14.11.2). If absent, the form is treated as having no code
forms/assets/ etc. Images for Image controls (BMP / JPEG / PNG / GIF / WebP / TIFF / ICO). The location is arbitrary; FormSpec refers to them by a path relative to the project root
{
  "schemaVersion": 1,
  "kind": "ras.userform",
  "basis": "designer",
  "form": { "name": "frmInput", "caption": "Input", "width": 240, "height": 180 },
  "controls": [
    { "id": "logo", "name": "imgLogo", "type": "Image", "left": 12, "top": 12, "width": 32, "height": 32, "picture": { "path": "forms/assets/logo.bmp" } },
    { "id": "kind", "name": "cboKind", "type": "ComboBox", "left": 56, "top": 12, "list": ["Normal", "Rush"], "selectedIndex": 0 },
    { "id": "name", "name": "txtName", "type": "TextBox", "left": 12, "top": 56, "width": 150, "height": 18, "controlTipText": "Name" },
    { "id": "ok", "name": "btnOK", "type": "CommandButton", "caption": "OK", "left": 12, "top": 84 }
  ]
}

Differences from xlflow's FormSpec (RAS supports a wider range):

Item Handling in RAS
tag / controlTipText Available on all controls (in xlflow, written in properties for everything except Page)
anchor RAS-specific. The edges at which a control keeps its distance when the parent is resized (§14.11.16)
form.resizable / form.minimumWidth / form.minimumHeight / form.maximumWidth / form.maximumHeight RAS-specific. Whether the user can resize the form, and the minimum and maximum inner size (§14.11.17)
placeholder of TextBox RAS-specific. A hint shown in gray in an empty box (§14.11.18)
list / selectedIndex of ComboBox / ListBox Written to the workbook (§14.11.5). In xlflow, used only to record retrieved values
Control properties Single-valued properties can be written with the same values as the VBA properties of the same name (the name with a lowercase first letter). In xlflow these are unsupported.
- TextBox: locked, multiLine, wordWrap, autoSize, passwordChar, scrollBars, maxLength, enterKeyBehavior, tabKeyBehavior, enterFieldBehavior, autoTab, autoWordSelect, hideSelection, selectionMargin, integralHeight, dragBehavior, imeMode, backStyle, specialEffect, borderColor
- ComboBox: style (0: DropDownCombo, 2: DropDownList), showDropButtonWhen, dropButtonStyle, listRows, listWidth, listStyle, matchEntry, matchRequired, the editing properties such as locked, maxLength, and autoSize, imeMode, backStyle, specialEffect, borderColor
- ListBox: multiSelect, listStyle, matchEntry, locked, integralHeight, imeMode, specialEffect, borderColor
- Columns of ComboBox / ListBox: columnCount (-1 means all columns of the item), columnWidths (the width of each column, separated by ;, as in "72 pt;;1 in"; units are pt (the default), in, and cm; an empty field and -1 mean automatic; written in the order of MS-OFORMS MorphDataColumnInfo, from the last column, as Excel does), boundColumn, textColumn, columnHeads
- CommandButton: default, cancel, takeFocusOnClick, locked, wordWrap, autoSize, backStyle
- CheckBox / OptionButton / ToggleButton: tripleState, locked, wordWrap, autoSize, backStyle; for CheckBox / OptionButton, alignment and specialEffect (0 or 2); for OptionButton, groupName
- Label: wordWrap, autoSize, backStyle, specialEffect, borderColor
- SpinButton / ScrollBar: min, max, smallChange, orientation, delay; for ScrollBar, largeChange and proportionalThumb. value must lie between min and max. A disabled one (enabled: false) is written with its arrows disabled too (PrevEnabled / NextEnabled set to 0), as Excel does
- Image: specialEffect, borderColor
- Frame: specialEffect, borderColor, cycle
- TabStrip / MultiPage: style (0: Tabs, 1: Buttons, 2: None), tabOrientation, multiRow, tabFixedWidth, tabFixedHeight (for MultiPage, written to the hidden TabStrip inside it)
- All except Image, Frame, TabStrip, and Page: mousePointer. Controls that receive focus: tabStop
- Controls that hold a value (TextBox, ComboBox, ListBox, CheckBox, OptionButton, ToggleButton, SpinButton, ScrollBar): controlSource (the cell the value is linked to; "Sheet1!B2"); for ComboBox / ListBox, rowSource (the cell range the items are read from; "Sheet1!A2:A10"; cannot be combined with list). These two are written to the control's site (OleSiteConcrete)
Lengths (listWidth, tabFixedWidth, tabFixedHeight) are in points, borderColor is a color, and passwordChar is a one-character string
Properties not written Written with the same values as when a control is created in Excel (ComboBox always shows the drop button and has matchEntry 1; ListBox has matchEntry 0 and a scroll bar; Frame has specialEffect 3; CheckBox / OptionButton / ToggleButton have backColor buttonFace and foreColor buttonText; ToggleButton is center-aligned; controls with text use MS UI Gothic 9pt as the font; and so on). xlflow writes ComboBox and ListBox with the MS-OFORMS defaults (no drop button, matchEntry 2). When importing (ras form pull), only values that differ from these are written out
value of CheckBox / OptionButton / ToggleButton In addition to true / false ("True" / "False", and 0 / 1 / -1 are also accepted), the indeterminate state (VBA Null) can be written as "Null". tripleState is written to the MS-OFORMS MultiSelect field, as Excel saves it (the specification does not document where it is stored)
Form properties In form, properties of the VBA UserForm of the same name can be written with the same values.
- Written to the designer block (the VBFrame stream; [MS-OVBA] 2.3.5): startUpPosition (0: Manual, 1: CenterOwner (default), 2: CenterScreen, 3: WindowsDefault), showModal, tag (up to 130 characters), helpContextId, rightToLeft, whatsThisButton, whatsThisHelp. Booleans are written as VBABOOL (0 / -1)
- Written to the form record (the f stream): enabled (false also writes Enabled = 0 in the designer block), borderColor, cycle, mousePointer, specialEffect, zoom (10 to 400), drawBuffer, scrollBars, keepScrollBarsVisible (0: None, 1: Horizontal, 2: Vertical, 3: Both (default)), scrollWidth / scrollHeight (in points; 0 means the size of the form), scrollLeft / scrollTop
When importing (ras form pull), only values that differ from a new form are written out. Properties with no line in the designer block are not written out (for StartUpPosition, the VBE writes no line when it is 0 (Manual), so a missing line is written out as 0). Left / Top (ClientLeft / ClientTop) are not handled because the size of the window frame varies by environment
Fonts For controls with no font, the font the VBE saves for new controls is written: with target.codepage 932 the Japanese edition's MS UI Gothic 9pt (charset 128, pitchAndFamily 2), otherwise the English edition's Tahoma 8pt (charset 0) (without a font, MSForms draws with a different typeface). Items written in font replace this; items not written are left as they are (the same as changing only Font.Name from VBA). On import, a font identical to this default is not written out. font.pitchAndFamily (0 to 255; the Windows lfPitchAndFamily) can be written. 0 means it is not saved, and on import an unsaved font is written out as 0 (it does not appear in the designer's font editing). Bold, italic, underline, and strikethrough are written with CFE_AUTOCOLOR (0x40000000) added to the effects, as the VBE does when they are set from VBA (without it, MSForms draws the text slightly differently). Also, for a disabled (enabled: false) Label, TextBox, CommandButton, ComboBox, CheckBox, OptionButton, or ToggleButton, CFE_DISABLED / CFE_AUTOCOLOR (0x40002000 in FontEffects; the setting that draws text in a muted color) is written to the font effects, as Excel does. xlflow writes neither
Pictures and mouse icons picture can be written on Image, and also on Label, CommandButton, CheckBox, OptionButton, and ToggleButton (a picture beside the caption; the position is picturePosition: 0 LeftTop to 12 Center, default 7 AboveCenter), on Frame and Page (background; pictureAlignment, pictureSizeMode, pictureTiling), and on the form (form.picture, form.pictureAlignment, etc.). mouseIcon can be written on controls that have mousePointer, and on the form, and is the pointer used when mousePointer is 99 (Custom). Both are specified with { "path": … } / { "remove": true }, as in "Pictures" below. In xlflow, only picture of Image is supported

Pictures (picture) and mouse icons (mouseIcon)

14.11.2 Code-behind (forms/<Name>.ras)

Code such as the form's event handling is written in RAS. The compiler parses forms/<Name>.ras together with the modules in src/ and outputs it as the form's code module, not as a standard module (ras build does not write it to build/; ras pack / ras sync write it to the workbook together with the designer storage).

// forms/frmInput.ras
let count = 0;
/** Whether the form was closed with OK (readable and writable from other modules as `frmInput.accepted`). */
export let accepted = false;

@on("UserForm.Initialize")
function init() {
    this.caption = `Input (${count})`;
}

@on("btnOK.Click")
function ok() {
    if (this.txtName.text == "") {
        msgBox("Please enter a name");
        this.txtName.setFocus();
        return;
    }
    count++;
    accepted = true;
    this.hide();
}

@on("txtName.Exit")
function leave(cancel: MSForms.ReturnBoolean) {
    cancel.value = this.txtName.text.length > 20;
}

@on("UserForm.QueryClose")
function closing(byref cancel: short, closeMode: short) {
    if (closeMode == vbFormControlMenu) cancel = 1;
}

/** The entered name (callable from other modules as `frmInput.enteredName()`). */
export function enteredName(): string {
    return this.txtName.text;
}

14.11.3 Commands

Command Behavior
ras form new <Name> Creates forms/<Name>.form.json (240×180, caption = name, no controls) and forms/<Name>.ras with example usage shown in comments. Does nothing if they already exist
ras form check Compiles the project, validates all forms, and goes as far as the same generation as writing to the workbook. Exit code 1 if there are errors
ras form pull [<Name>…] [--book <file>] [--force] Extracts the forms in the workbook into forms/. Code is converted to RAS (§14.11.6)
ras check / ras build Validate the forms together with the RAS sources (including code-behind) (ras build does not output forms to build/)
ras pack Writes all forms (designer storage and code modules) to the workbook together with the RAS-managed modules
ras sync Applies the forms to the workbook open in Excel, together with the RAS-managed modules (§14.11.7)
ras watch Also watches changes in forms/ (if the workbook is open, ras sync; if closed, the same write as ras pack)

14.11.4 Writing (ras pack)

  1. The designer storage (<Name>/f, o, \x01CompObj, \x03VBFrame, the per-container i<ID>/ substorages, and the x of MultiPage) is generated from scratch from the FormSpec. Automated tests confirm that reading back a generated form and writing it again yields the same designer storage (crates/ras-form/tests/fixtures.rs), and that for every property the written value can be read back (the tests in crates/ras-form/src/scalars.rs). tools/excel-check is used to compare against a real Excel.
  2. The code module VBA/<Name> is created. A new form gets a form attribute header containing VB_Base = "0{GUID}{GUID}" (two new GUIDs); for an existing form, the header is kept and only the code is replaced.
  3. The first line of the code is the marker line ' RAS-FORM forms/<Name>.form.json design=<hash> code=<hash>, which indicates that the form was generated by RAS. design is the hash of the designer storage and code is the hash of the code that follows (16 hex digits); live sync uses them to decide whether anything changed (§14.11.7). After the marker come the compiled code-behind and, if needed, generated code (§14.11.5).
  4. A BaseClass=<Name> line is added to the PROJECT stream, and a reference to the Microsoft Forms 2.0 Object Library (MSForms) is added to the dir stream if it is missing.
  5. If a form of the same name already exists, its designer storage is replaced entirely. If neither the design nor the code has changed, it is treated as "no change".
  6. In the following cases it is an error and nothing is written: the name equals a RAS module, a non-form module of the same name exists, or a form of the same name without a marker (created in the VBE) exists (--overwrite allows replacing it).

ras unpack does not extract forms with a marker into vba/. A form removed from forms/ is not deleted from the workbook (delete it in the VBE).

14.11.5 List items (list / selectedIndex)

MS-Forms does not save the items of a ComboBox / ListBox in the designer storage (even if you AddItem at design time, they disappear when you save and reopen the workbook). So list and selectedIndex are output into the code module as code that runs when the form is loaded.

' RAS-FORM forms/frmInput.form.json design=… code=…
Option Explicit
Option Compare Binary

Private Sub init()
    Me.txtName.Text = ""
End Sub

Private Sub UserForm_Initialize()
    RAS_FormInit '--- RAS ---
    On Error GoTo RAS_OnError
    init
    Exit Sub
RAS_OnError:
    RAS_EventError "frmInput.UserForm_Initialize", Err.Number, Err.Source, Err.Description
End Sub
'--- RAS BEGIN ---
Private Sub RAS_FormInit()
    With Me.cboKind
        .AddItem "Normal"
        .AddItem "Rush"
        .ListIndex = 0
    End With
End Sub
'--- RAS END ---

14.11.6 Extraction (ras form pull)

Reads the forms of the workbook (the saved file) and writes forms/<Name>.form.json, forms/<Name>.ras, and image files. Excel is not used. Use it when moving a form created in the VBE under forms/ management, or when re-importing a form whose design was fixed in the VBE.

14.11.7 Live sync (ras sync, ras watch, the VS Code language server)

When the workbook is open in Excel, forms are applied in the same sync as the modules of §14.6 (Windows only).

State Behavior
The workbook has no such form Import it (create)
The marker line is the same Do nothing
design is the same but code differs Rewrite only the code in the CodeModule
design differs Re-import the form (update)
A form of the same name without a marker (created in the VBE) Error. If overwriting is specified, it is re-imported. A form imported by sync (§14.7.1) is re-imported

14.11.8 Running in Excel

"Run in Excel" in VS Code (the CodeLens at the top of a form's code-behind, the button in the designer's title bar, and the command "Run Form in Excel"; Windows only) syncs to the workbook (§14.11.7) and then shows the form in Excel itself.

14.11.9 Creating instances and return values (new / showModal / close)

VBA forms have no way to pass values when creating them (constructor arguments) and no way to receive a value when they are shown modally and closed. So values have to be passed through the default instance and module variables, which makes problems likely: closing with the × button unloads the form and the value is lost, or the previous state remains in the default instance. In RAS, you can create a form instance with new, pass arguments to constructor, show it with showModal(), and receive the value of this.close(value).

// forms/frmInput.ras
function constructor(name: string, limit: int = 20) {
    this.txtName.text = name;
    this.txtName.maxLength = limit;
}

@on("btnOK.Click")
function ok() {
    this.close(this.txtName.text);       // showModal() returns this value
}

@on("btnCancel.Click")
function cancel() {
    this.close();                        // no value: showModal() returns the type's default ("")
}

// src/main.ras
export function ask() {
    const name = new frmInput("Yamada", 10).showModal();   // name: string
    if (name == "") return;                                // cancelled or closed with the × button
    msgBox(`Hello, ${name}`);
}

14.11.10 Display scaling (DPI)

When the Windows display scaling is other than 100% (125%, 150%, and so on), VBA creates the form's window from the design size, but the sizes of the title bar and border are not scaled in proportion to points. The inside of the form therefore becomes smaller (or larger) than the design, so controls at the right and bottom edges are clipped or extra margin appears. In forms written by RAS, when the form is loaded (RAS_FormInit, called at the start of UserForm_Initialize; §14.11.5), the inner size (InsideWidth / InsideHeight) is adjusted to match form.width / form.height.

Private Sub RAS_FormInit()
    If Abs(Me.InsideWidth - 240) >= 1 Then Me.Width = Me.Width + 240 - Me.InsideWidth
    If Abs(Me.InsideHeight - 180) >= 1 Then Me.Height = Me.Height + 180 - Me.InsideHeight
    ...(the list items)
End Sub

14.11.11 Limitations

14.11.12 Input validation (validation)

Form input is validated with rules built zod-style, and errors are shown in a label under each control. As in modern web input forms, a control is validated when its input is committed (focus leaves it), and once committed it is re-validated on each subsequent edit (so the error disappears as soon as it is fixed). The library is the bundled module validation written in RAS (crates/ras-compiler/stdlib/validation.ras), output only when used.

// forms/frmOrder.ras
import * as z from "validation";

const form = new z.FormValidator();       // placed in a module variable, so control events are connected

function constructor() {
    form.rule(this.txtName, z.string().required("Please enter a name").max(20));
    form.rule(this.txtAge, z.int().min(0).max(150));
    form.rule(this.txtMail, z.string().email());
    form.rule(this.chkAgree, z.boolean().required("Agreement is required"));
}

// Change the rules depending on earlier input: rule / remove can be called again at any time
@on("cboKind.Change")
function kindChanged() {
    if (this.cboKind.text == "Corporate") {
        form.rule(this.txtCorp, z.string().required("Please enter the company name"));
    } else {
        form.remove(this.txtCorp);
    }
}

@on("btnOK.Click")
function ok() {
    if (!form.validateAll()) return;      // validates everything, shows errors, and moves focus to the first error
    this.close(this.txtName.text);
}

14.11.13 Progress bar (ProgressBar)

A progress bar combining a label, a percentage, and a bar is placed in the design like a built-in control and operated through properties. MSForms has no progress bar (the Windows common control one is an ActiveX control that is not necessarily present on every PC), so RAS builds one by combining MSForms labels.

Upload progress                                    56%
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━──────────────────────
{ "id": "pb", "name": "pbUpload", "type": "ProgressBar", "caption": "Upload progress", "value": 56,
  "left": 12, "top": 12, "width": 240, "height": 24 }
// forms/frmUpload.ras
@on("btnStart.Click")
function start() {
    this.pbUpload.caption = "Uploading";
    for (let i = 0; i < files.length; i++) {
        upload(files[i]);
        this.pbUpload.value = (i + 1) * 100 / files.length;
    }
}

// Can be referenced from other modules too, like a control
frmUpload.pbUpload.value = 0;

14.11.14 File and folder picker (FilePicker)

A pair of a text box for entering a path and a button attached to its right. Pressing the button shows Application.FileDialog and puts the chosen path in the box. You can also type or paste directly into the box. The dialog's properties have the same names and values as FileDialog, and can be written in the design or in code.

[C:\Users\me\Documents\report.xlsx            ][...]
{ "id": "fp", "name": "fpBook", "type": "FilePicker", "left": 12, "top": 12, "width": 240,
  "title": "Select a workbook", "filters": [{ "description": "Excel workbooks", "extensions": "*.xlsx; *.xlsm" }] }
// forms/frmImport.ras
@on("fpBook.Change")                       // box event (typing, pasting, or choosing with the button)
function changed() {
    this.btnOK.enabled = this.fpBook.path != "";
}

@on("btnOK.Click")
function ok() {
    this.close(this.fpBook.path);           // the (first) path in the box
}

// Show the dialog from code: an array of the chosen paths. Cancel gives an empty array
export function chooseFolder(): string[] {
    this.fpBook.dialogType = 4;             // msoFileDialogFolderPicker
    return this.fpBook.browse();
}

14.11.15 Dialogs built in code (dialog)

Dialogs that only let the user pick a button, dialogs with several input fields plus OK / Cancel, and progress bars showing how far a process has come are built from code alone, without creating a form design (forms/). The library is the bundled module dialog written in RAS (crates/ras-compiler/stdlib/dialog.ras).

import { Dialog, choose, Progress } from "dialog";
import * as z from "validation";

// A dialog with arbitrary buttons: the number of the button pressed (from 0). × and Esc give -1
export function confirmSave() {
    switch (choose("Save changes?", ["Commit changes", "Commit as new name", "Cancel"], title: "Save", cancel: 2)) {
        case 0: save(); break;
        case 1: saveAs(); break;
        default: return;                                  // cancel or ×
    }
}

// A dialog with input fields (the default buttons are OK and Cancel)
export function exportSheet() {
    const d = new Dialog("Export", "Choose the output settings");
    const kind = d.select("Format", ["CSV", "TSV", "Fixed length"]);
    const file = d.file("Output file", dialogType: 2).addFilter("CSV", "*.csv").required("Please choose an output file");
    const head = d.checkbox("Include headings", true);
    const eol = d.radio("Line ending", ["CRLF", "LF"]);
    const sheets = d.list("Sheets", worksheets.map(s => s.name), multi: true);
    const memo = d.text("Memo", "", multiline: true).rule(z.string().max(200));
    d.onChange((f) => { eol.enabled = kind.index != 2; });   // change items while shown
    if (d.show() != 0) return;                               // 0: OK
    writeFile(file.text, kind.index, head.checked, eol.text, sheets.selected, memo.text);
}

// A modeless progress bar (shown as soon as it is created; the cancel button or × sets cancelled)
export function rebuild() {
    const last = Sheet1.cells(Sheet1.rows.count, 1).end(xlUp).row;
    const p = new Progress("Calculating", max: last);
    for (let r = 1; r <= last; r++) {
        if (p.cancelled) break;
        p.value = r;
        p.message = `Row ${r} / ${last}`;
        work(r);
    }
    p.close();
}

14.11.16 Anchors (anchor)

Specifies the edges at which a control keeps its distance when the parent (form, Frame, MultiPage) is resized, with the same idea as the Windows Forms Anchor. MSForms has no such property, so the generated code moves the controls in UserForm_Resize.

{ "id": "ok", "name": "btnOK", "type": "CommandButton", "left": 150, "top": 140, "anchor": "bottom,right" },
{ "id": "note", "name": "txtNote", "type": "TextBox", "left": 8, "top": 8, "width": 220, "height": 120, "anchor": "top,bottom,left,right" }

14.11.17 Resizing forms (resizable, minimum / maximum size)

Lets the user resize the form by dragging its border, and sets the range of the inner size. They correspond to FormBorderStyle.Sizable, MinimumSize, and MaximumSize of Windows Forms. MSForms has none of these, so they are not written to the designer storage; the generated code handles them. Combined with anchors (§14.11.16), controls follow the user's resizing.

"form": {
  "name": "frmNote", "width": 240, "height": 180,
  "resizable": true, "minimumWidth": 200, "minimumHeight": 150, "maximumWidth": 480
}

14.11.18 Placeholder (placeholder)

While a TextBox is empty and does not have focus, a gray hint is shown over the box (equivalent to HTML's placeholder). MSForms has none, so when writing, a label overlaid on the box is added, and the generated code switches it between shown and hidden.

{ "id": "name", "name": "txtName", "type": "TextBox", "left": 12, "top": 12, "width": 160, "height": 18, "placeholder": "Enter a name" }

14.12 Testing (ras test)

Test RAS programs automatically without launching Excel. Tests are written in the same form as vitest / Jest (describe / test / expect) and run on the same JavaScript runtime as debug runs (§14.10) with the Excel stand-in (§14.10.8). The goal is identical results on Mac, Linux, Windows without Excel, and CI.

14.12.1 Principles

14.12.2 Files

Path Contents
test/**/*.test.ras Test files. Each file is one test suite
test/**/*.ras (other than .test.ras) Helper modules for tests. They can be imported from test files and can use the test API (§14.12.4–§14.12.6)
test/fixtures/ Location for workbooks (.xlsx / .xlsm) and text files that tests load (a convention; useWorkbook in §14.12.5 accepts any path relative to the project root)
build/test/ JavaScript and source maps output by ras test, and the workbooks of failed tests (§14.12.8). Recreated on every run

14.12.3 What can be written in a test file

Only the following can be written at the top level of a test file.

In the body (lambda) of a describe, only const / let declarations and call statements of describe / test / hooks can be written. Any other statement (ws.cells(1, 1).value = 1;, for, etc.) is an error (E0702). Put setup code in a hook or in the body of a test.

// test/report.test.ras
import { rebuildReport, lastRow } from "src/report";

describe("lastRow", () => {
    beforeEach(() => useWorkbook("test/fixtures/sales.xlsx"));

    test("returns the last row of the data", () => {
        expect(Sheet1.lastRow()).toBe(120);
    });

    test.each([[1, 120], [3, 98]])("last row of column %i is %i", (col: int, want: int) => {
        expect(Sheet1.lastRow(col)).toBe(want);
    });
});

describe("rebuildReport", () => {
    let last: int;

    beforeAll(() => {
        useWorkbook("test/fixtures/sales.xlsx");
        last = Sheet1.lastRow();
    });

    test("writes twice the row number in column C", () => {
        rebuildReport();
        expect(Sheet1.cells(2, 3).value).toBe(4);
        expect(Sheet1.cells(last, 3).value).toBe(last * 2);
    });

    test("does not raise an error on an empty sheet", () => {
        Sheet1.cells.clearContents();
        expect(() => rebuildReport()).not.toThrow();
    });
});

14.12.4 Test declarations and hooks

In test files and test helper modules, the following names can be used without import (from the bundled type definitions ras:test; they are not available in other modules). If the user declares the same name, that declaration takes precedence.

API Description
describe(name, body) Groups tests. Can be nested. A test's name is the describe names joined with > (lastRow > returns the last row of the data)
test(name, body, options?) / it(...) Declares a test. body is a lambda with no arguments. options is { timeout: int } (milliseconds)
test.skip / describe.skip Not run (the result is "skipped")
test.only / describe.only Run only the items marked only in that file. With --ci (§14.12.7), the presence of only is an error (to prevent forgetting to remove it)
test.todo(name) A planned test with no body (the result is "todo")
test.each(table)(name, body) / describe.each(...) Creates a test for each row of the table. If a row is a tuple or array, its elements are passed as the arguments of body; if it is a struct, the struct is passed as a single argument. The name can contain %s (stringified), %i / %d (integer), %f (real number), %%, and $fieldName (for struct rows)
beforeAll(fn) / afterAll(fn) Run once before the first test and after the last test of that describe (the file, at the top level)
beforeEach(fn) / afterEach(fn) Run before and after each test in that describe. beforeEach runs starting from the outermost, and afterEach starting from the innermost

14.12.5 Workbooks and test isolation

14.12.6 expect and replacements (mocks)

expect(actual) provides the following assertions (matchers). Adding .not inverts the assertion. On failure, the test stops and the expected and actual values are shown (a diff for arrays and structs).

Matcher Assertion
toBe(expected) Same comparison as RAS == (numbers are compared by value across types, strings are case-sensitive, objects by identity (Is))
toEqual(expected) Compares arrays, structs, tuples, and Maps element by element. A 2-D array from Range.value can be compared with an array literal ([[1, 2], [3, 4]])
toBeCloseTo(expected, digits = 2) The absolute difference between actual and expected is less than 10 ^ -digits / 2
toBeGreaterThan / toBeGreaterThanOrEqual / toBeLessThan / toBeLessThanOrEqual Ordering of numbers, dates, and strings
toBeTruthy() / toBeFalsy() Same judgment as a RAS conditional expression
toBeEmpty() Empty (the value of an empty cell)
toBeNothing() Nothing
toContain(item) An array element, or a substring of a string
toHaveLength(n) The length of an array or string
toMatch(pattern: string) The string matches the regular expression (VBScript.RegExp syntax)
toThrow(expected?) actual is a lambda with no arguments. Succeeds if running it raises an error. If expected is an integer, it narrows by error number; if a string, by a string contained in the description
toMatchSnapshot(hint?) Compares the value with the one recorded before (a snapshot). See "Snapshots" below

Replacing dialogs and external calls: Things whose responses are fixed in debug runs (§14.10.8) can be replaced from a test. The replacements are undone when the test ends (if set in beforeEach, they apply to all tests in that describe).

API Description
mockMsgBox(handler) Calls handler(prompt, buttons, title) instead of msgBox and returns its return value (vbYes, etc.). If omitted, vbOK
mockInputBox(handler) Calls handler(prompt, title, defaultValue) instead of inputBox and application.inputBox
mockGetOpenFilename(handler) / mockGetSaveAsFilename(handler) Calls handler(...) instead of the file selection dialog (return false to cancel)
mockRun(macroName, handler) Calls handler(...args) instead of application.run(macroName, ...) (a call to hand-written VBA)
mockCreateObject(progId, factory) Makes createObject(progId) / new use the object returned by factory() (replaces a COM object that the stand-in lacks with a RAS class that has the same members)

14.12.7 ras test

ras test                          # run all tests
ras test test/report.test.ras     # specify a file
ras test -t "lastRow"             # filter by a string contained in the name (describe > test)
ras test --list                   # list the tests without running them
ras test --reporter json          # output results as JSON (for editors and AI agents)
ras test --watch                  # watch for changes and re-run the affected test files
Option Description
[<file>...] Test files (or folders) to run. If omitted, all files matching include
-t, --name <text> Run only the tests whose full name contains text (filtering by a describe name selects all tests in it)
--list Lists the tests (does not run them, per §14.12.3). Combined with --reporter json, it outputs a tree of files, names, positions (line, column), and nesting
--reporter <pretty|json|junit> Output format. The default is pretty. json is JSON Lines with one event per line (file start, test result, overall summary); junit is JUnit XML
--watch When the source changes, re-runs the test files that (transitively) import the changed modules
--excel Runs against the real Excel instead of the Excel stand-in (Windows only). See "--excel" below
--ci Makes test.only, dialogs that are not replaced, and snapshots not recorded yet into errors
-u, --update-snapshots Records the snapshots again and removes the unused ones
--sequence Runs test files one at a time
--bail <n> Aborts when the number of failures reaches n
--inspect-brk[=[<host>:]<port>] Starts the Node that runs each test file with the inspector (127.0.0.1:0 by default) and stops it at its first line until a debugger attaches. The timeout is turned off. The inspector's address is given by an event { "type": "inspector", "file", "url", "pid" } with --reporter json, and on the standard error otherwise. Used by the debugging of tests in the VS Code extension (§14.12.10)

The test result event of --reporter json has the following form.

{"type":"test","file":"test/report.test.ras","name":["rebuildReport","writes twice the row number in column C"],
 "line":21,"status":"failed","durationMs":38,
 "failure":{"kind":"expect","matcher":"toBe","expected":"240","actual":"0",
            "location":{"file":"test/report.test.ras","line":24,"column":9}},
 "printed":[],"workbook":"build/test/workbooks/report.test/rebuildReport > writes twice the row number in column C.xlsx"}

14.12.8 Workbooks of failed tests

14.12.9 [test] in ras.toml

[test]
include = ["test/**/*.test.ras"]   # patterns for test files (relative to the project root)
timeout-ms = 10000                 # timeout per test
excel = "standIn"                  # "standIn" (default) / "com" (same as --excel)
save-workbooks = "failed"          # "failed" (default) / "always" / "never"
event-errors = "fail"              # "fail" (default) / "ignore" (§14.12.5)
excel-calls = "vba"                # with --excel, the project's functions a test calls: "vba" (default; the VBA written into the copy) / "js" (JavaScript; §14.12.7)

14.12.10 Editor

14.12.11 Limitations

14.13 Running from the CLI (ras run)

Performs a debug run (§14.10) without VS Code. Use it when you can work only through the CLI, as an AI agent does, or for one-off checks that are hard to turn into tests.

ras run Report.rebuildReport              # run and show the result
ras run rebuildReport --json              # output the result as JSON (the module name can be omitted if it is unambiguous)
ras run --list                            # list the functions that can be run
ras run ask --msgbox vbYes --inputbox "2026/4"

14.14 Viewing and comparing workbook contents as text (ras book)

Turns .xlsx / .xlsm files into text without Excel. It spares AI agents from guessing a sheet's structure or cell contents, and it also gives humans a way to check run results. Reading is done by the same crates/ras-workbook as the Excel stand-in.

ras book dump Book.xlsm                                   # list of sheets, used range, formulas, names, tables
ras book dump Book.xlsm --sheet Sheet1 --range A1:F20     # cell values and formulas
ras book dump Book.xlsm --sheet Sheet1 --format csv       # text (default) / json / csv / markdown
ras book dump Book.xlsm --sheet Sheet1 --styles           # also the formats (font, fill, borders)
ras book diff before.xlsm build/debug/workbooks/Book.xlsm # differences in cells and structure
ras book diff before.xlsm after.xlsm --styles             # also the differences in formats

Grid view (ras book view): The Excel stand-in keeps formatting but does not render it, so there is a separate view for people to look at sheets.

ras book view Book.xlsx                                        # creates build/view/Book.html (--open opens it in the browser)
ras book view build/debug/workbooks/Book.xlsx --diff Book.xlsx # highlights changed cells
ras run Report.rebuildReport --view                            # shows the workbook after the run, with changes highlighted

Cell editing (ras book edit, the editor's sheet preview): Rewrites the workbook file so that the result is the same as editing the cells in Excel. It is a way to fix workbook data in environments without Excel, and the editor's sheet preview (above) can edit cells with the same processing.

ras book edit Book.xlsm --sheet Sheet1 --set B2=100 --set "C2==B2*2"   # enter into cells
ras book edit Book.xlsm --sheet Sheet1 --clear A1:C3                    # clear formulas and values
ras book edit Book.xlsm --sheet Sheet1 --insert 3:4                     # insert rows (B:C for columns, B2:C3 for cells)
ras book edit Book.xlsm --sheet Sheet1 --delete B2:C3 --shift left      # delete cells and shift left
ras book edit Book.xlsm --op '{"op":"copy","sheet":"Sheet1","from":"A1:B2","to":"D1"}'

New workbooks (ras book new): Makes a workbook for the input of tests and debugging anew from CSV and JSON files. The sheet names and code names follow the project's workbook (workbook of ras.toml; another with --template), and the contents of --sheet <sheet>=<file> (a sheet name or code name) are written from A1. Sheets the template does not have are added at the end; --no-template makes only the sheets of --sheet. A file that exists is not replaced without --force.

ras book new test/fixtures/sales.xlsx --sheet Sheet1=data/sales.csv --sheet Master=data/master.json

Sample workbooks (ras book samples): Makes the workbooks that tests take as input by editing a source workbook. The edits are those of ras book edit (the same result as entering the cells in Excel; formulas are calculated again), so Excel is not needed. Which workbooks are made and how is written in a recipe (JSON) kept in the repository, so they can be made again.

ras book samples test/fixtures/samples.json            # make every workbook of the recipe
ras book samples test/fixtures/samples.json --only wrong.xlsx
ras book samples test/fixtures/samples.json --check    # are the files as the recipe makes them (exit code 1 if not)
{
  "source": "real-report.xlsx",
  "samples": [
    { "output": "wrong.xlsx", "edits": [
      { "sheet": "Ledger", "set": { "S14": "X", "AC52": "type\nbroken" } },
      { "sheet": "Ledger", "clear": ["A80:AG80"] },
      { "op": "name", "name": "Print_Area", "scope": "Ledger", "ref": "'Ledger'!$A$1:$AG$70" },
      { "op": "sheet", "action": "remove", "sheet": "Basics" }
    ] }
  ]
}

Implementation note (current version): The parts and data that ras book edit's activeX (inserting ActiveX controls from the sheet preview) writes (xl/activeX, <controls>, VML shapes) follow the form of files saved by Excel and are confirmed by this repository's reading (grid, changes by object, the compiler's list of controls) and tests. In Excel 2021, it was confirmed that a workbook with all 10 kinds placed and a workbook with them resized can be opened, and that clicking a control to activate it does not change its appearance (text size). The colors of check boxes, option buttons, and labels are the same window colors that Excel places on a sheet (BackColor &H80000005, ForeColor &H80000008) (not the colors of a user form's buttons). As differences from controls Excel places, the font is the default font above rather than the workbook's Normal font (e.g. Yu Gothic 11pt), and the size when the size is omitted also differs in part from the size Excel's COM (OLEObjects.Add) places (check boxes and option buttons are 144 × 30 px, etc.).

14.15 Machine-readable diagnostics, explaining errors, and warnings about APIs unavailable in the stand-in

14.16 Adding, duplicating, deleting, and renaming sheets (ras sheet)

Lets you add, duplicate, delete, and rename sheets from VS Code and the CLI without operating Excel. A sheet and its file (objects/<code name>.ras; §12.2) correspond one to one, so the commands change the workbook's sheet and the file in objects/ together.

ras sheet list                                   # list of sheets (tab name, code name, file, visibility)
ras sheet add Totals                             # adds sheet "Totals" at the end and creates objects/Sheet3.ras
ras sheet add Totals --code-name Summary --after Sheet1
ras sheet copy Sheet1 April                      # duplicates Sheet1 as "April" and duplicates objects/Sheet1.ras too
ras sheet remove Sheet3                          # deletes the sheet and the file
ras sheet rename Sheet1 --name Revenue --code-name Sales

14.17 Running, compiling and comparing in Excel (ras excel)

Writes the project into a copy of the workbook and, in an Excel started for this alone, runs a function or compiles the VBA (Windows only). It checks from the CLI alone what the stand-in (§14.10.8) cannot: how the code behaves in the real Excel, and whether a workbook with hand-written VBA compiles. Nothing is left stopped at a VBE dialog for a person to close.

ras excel compile                                   # compile the VBA and show where the errors are
ras excel run Report.rebuildReport                  # run a function (the module name can be left out)
ras excel run checkReport "C:\data\report.xlsx" 3 --json
ras excel run Hand.boom --book Hand.xlsm --timeout 60

15. Project layout

15.1 Directories

myproject/
  ras.toml
  src/            *.ras (standard modules; one per file. §12.1.1)
  objects/        modules for sheets and ThisWorkbook (<code name>.ras, ThisWorkbook.ras). Corresponds to "Microsoft Excel Objects" in the VBE (§12.2)
  vba/            unmanaged VBA modules and user forms (two-way sync)
  forms/          user form designs (*.form.json) and code-behind (*.ras) (§14.11)
  types/          additional type definitions (*.d.ras)
  test/           tests (*.test.ras) and test helpers and fixtures. Not included in the build (§14.12)
  build/          generated output (.bas / .cls / .rasmap)
  build/sync/     the code last written by sync / ras pack (used to import code added in the VBE. §14.7.3)
  build/debug/    JavaScript and source maps for debug runs (§14.10)
  build/test/     JavaScript for test runs, and the workbooks of failed tests (§14.12)

15.2 ras.toml

[project]
name = "SalesReport"
workbook = "C:/work/SalesReport.xlsm"

[target]
host = "excel"          # currently only "excel"
vba6 = true             # also emit Declare statements for VBA6 (32-bit Office 2007 and earlier)
codepage = 932

[build]
opt-level = 1           # 0: no inlining / 1: automatic inlining in loops / 2: aggressive
inline-threshold = 40
erl = true              # add line numbers

[pack]
backup-generations = 5
# sign = "cert:CurrentUser/My/<thumbprint>"   # certificate used to re-sign

[doevents]
enabled = true
interval-ms = 100       # minimum interval between DoEvents calls
loop-threshold = 10000  # minimum iteration count for a constant-count loop to get an insertion

[sync]
enabled = true
compileCheck = true
shared-memory-mb = 64
pull-unmanaged = true   # on sync / ras pack, convert hand-written VBA in the workbook to RAS and import it (§14.7.1)
sheet-files = true      # on sync, create objects/<code name>.ras and objects/ThisWorkbook.ras for sheets and ThisWorkbook that have no file (§14.7.2)

[test]                  # §14.12.9
include = ["test/**/*.test.ras"]
timeout-ms = 10000

15.3 Host type definitions

15.3.1 Name spelling

The Excel / VBA / Office type libraries define member names in PascalCase (Cells, ScreenUpdating). In RAS source, they are referenced as follows, to match JavaScript naming conventions. Completion, quick info, and diagnostic messages also show this spelling.

Target Spelling in RAS Examples
Properties and methods camelCase ws.cells(r, 1).value, application.screenUpdating, range.interior.color
Global objects and functions camelCase application, thisWorkbook, activeSheet, worksheets, msgBox(...), left(s, 1), debug.print(...), err.number
Types (interfaces and enums) and namespaces stay PascalCase Excel.Worksheet, XlCalculation, VBA.ErrObject
Enum constants as in the type library xlUp, vbCrLf, msoTrue

15.3.2 File operations that use file numbers

VBA's Open / Close / Print # / Write # / Input # / Line Input # / Get / Put / Seek / Lock / Unlock / Width # / Name / Reset are statements with their own syntax and cannot be called as functions. In RAS, they are written as built-in functions. Names and argument order follow VB.NET's Microsoft.VisualBasic.FileSystem, which turned the same statements into functions (FileOpen, PrintLine, LineInput, etc.). The generated VBA contains the original statements.

export function writeLines(path: string, lines: string[]) {
    const f = freeFile();
    fileOpen(f, path, forOutput);
    for (const line of lines) printLine(f, line);
    fileClose(f);
}

export function readLines(path: string): string[] {
    const lines: string[] = [];
    const f = freeFile();
    fileOpen(f, path, forInput, accessRead, lockShared);
    while (!eof(f)) lines.push(lineInput(f));
    fileClose(f);
    return lines;
}

Output VBA code (excerpt):

    f = FreeFile()
    Open path_ For Output As #f
    For ras_i = 0 To RAS_Len(lines) - 1&
        line = lines(ras_i)
        Print #f, line
    Next ras_i
    Close #f
    ...
    Open path_ For Input Access Read Shared As #f
    ...
    Do While Not EOF(f)
        Line Input #f, ras_t1
        ...
        lines(ras_len_lines) = ras_t1
        ...
    Loop
    ...
    Close #f
RAS VBA Description
fileOpen(n, path, mode, access?, share?, recordLength?) Open path For mode [Access …] [Lock …] As #n [Len = …] Opens a file. mode is forInput / forOutput / forAppend / forBinary / forRandom (FileIO.OpenMode), access is accessRead / accessWrite / accessReadWrite (FileIO.OpenAccess), and share is lockShared / lockRead / lockWrite / lockReadWrite (FileIO.OpenShare). When not specified, use accessDefault / lockDefault (placeholders for writing the later arguments)
fileClose(n1, n2, …) / fileClose() Close #n1, #n2 / Close Closes files. With no arguments, closes all of them
reset() Reset Closes all files
printLine(n, a, b, …) Print #n, a; b Writes the values one after another, then a line break (printLine(n) is an empty line)
print(n, a, b, …) Print #n, a; b; Writes the values one after another, with no line break
writeLine(n, a, b, …) Write #n, a, b Writes comma-separated values, then a line break (strings are enclosed in "; the format that Input # can read)
write(n, a, b, …) Write #n, a, b, Same, with no line break
input(n, v1, v2, …) Input #n, v1, v2 Reads comma-separated values into variables
lineInput(n) Line Input #n, v Reads one line and returns it (string)
inputString(n, count) Input$(count, #n) Reads count characters and returns them
fileGet(n, v, record?) Get #n, record, v Reads from a forBinary / forRandom file into a variable
filePut(n, value, record?) Put #n, record, value Writes to a forBinary / forRandom file
seek(n) / seek(n, position) Seek(n) / Seek #n, position Returns / moves the position of the next read or write (bytes or records, 1-based)
lock(n, from?, to?) / unlock(n, from?, to?) Lock #n, from To to / Unlock … Prohibits / allows reads and writes by other processes
fileWidth(n, width) Width #n, width The line width (the number of columns at which Print # wraps; 0 means unlimited)
rename(oldPath, newPath) Name oldPath As newPath Renames (moves) a file or folder

15.3.3 The Like operator and Null (like / dbNull)

VBA's Like operator and Null are keywords, neither functions nor variables. In RAS, they are written as the built-in function like and the constant dbNull.

export function isCode(s: string): boolean {
    return like(s, "[A-Z]##-*");
}

export function clearMemo(rs: object) {
    rs.fields("memo").value = dbNull;
    if (isNull(rs.fields("note").value)) {
        rs.fields("note").value = "";
    }
}
Public Function isCode(ByVal s As String) As Boolean
    isCode = s Like "[A-Z]##-*"
End Function

Public Sub clearMemo(ByVal rs As Object)
    rs.fields("memo").Value = Null
    If IsNull(rs.fields("note").Value) Then
        rs.fields("note").Value = ""
    End If
End Sub

15.4 Strings, arrays, paths, files, CSV, JSON, XML, and timing (RAS standard library)

15.4.1 Strings

Extension methods (ras_text; usable without an import. §3.2.4) and the arguments of the built-in split / trim.

Member Description
s.width(): int The width, counting half-width characters as 1 and full-width characters as 2 (the same as the Shift_JIS byte count; used for the columns of fixed-length text)
s.leftWidth(n) / s.rightWidth(n) The part from the start / end that fits in width n (a full-width character is not included if only half of it would fit)
s.midWidth(start, n = -1) The part that fits in width n, starting from position start counted by width (from 0); omit n to go to the end
s.toValue(): any A value of the type that fits the content: "TRUE" / "FALSE" become a boolean, a number (including full-width digits and digit separators) becomes a double, a date becomes a date, and anything else stays the original string
s.countMatchChars(other): int The number of shared characters (regardless of order; a character counts as many times as it occurs in both)
s.longestCommonSubsequence(other): string The longest common subsequence
s.split(re) Splits at the places that match a regular expression (/\s*,\s*/) (RAS_SplitRegExp; always all matches, regardless of global). Unlike JavaScript, what capture groups match is not included. An empty string gives an empty array (as VBA's Split does, like split(","))
s.trim(chars) / trimStart(chars) / trimEnd(chars) Removes the characters contained in chars from both ends / the start / the end (RAS_TrimChars; "  x  ".trim("  ")). With no argument, only half-width spaces, as with VBA's Trim$

15.4.2 Arrays

Extension methods (ras_array; usable without an import).

15.4.3 Paths (path)

Used with import * as path from "path"; (RAS_Path). It handles path strings only and does not touch files. Both \ and / are accepted as separators; when joining, \ is used.

15.4.4 Files and folders (fs)

Used with import * as fs from "fs"; (RAS_Fs; creates one Scripting.FileSystemObject and reuses it).

Reading and writing text files with a specified character encoding: The TextStream of Scripting.FileSystemObject and the Open statement (§15.3.2) handle only ANSI (Shift_JIS on Japanese Windows) or UTF-16, so reading and writing is done with ADODB.Stream (§15.3).

import * as fs from "fs";

export function convert(src: string, dest: string) {
    const text = fs.readText(src);                        // detect the encoding and read (BOM → UTF-8 → Shift_JIS)
    fs.writeText(dest, text, "shift_jis");                // write as Shift_JIS
    fs.writeText(dest + ".txt", text, "utf8bom");         // UTF-8 with BOM
    fs.writeText(dest + ".log", "appended\r\n", append: true); // append to the end (no BOM is written)
    for (const line of fs.readLines(src, "utf8")) {      // array of lines (line breaks are CR LF, LF, or CR)
        debug.print(line);
    }
    debug.print(fs.detectEncoding(src));                  // "utf8bom" / "utf8" / "cp932" / "utf16le" / "utf16be"
}

15.4.5 CSV (csv)

Used with import * as csv from "csv"; (RAS_Csv). Tables are passed as 2-D arrays (rows × columns; the same form as range.toArray() / range.fromArray(). §9.2.1).

import * as csv from "csv";

export function importSales(src: string) {
    const rows = csv.read(src, cast: true);                    // detects the encoding; converts to numbers, dates, TRUE/FALSE
    Sheet1.range("A1").fromArray(rows);
    const data = Sheet1.range("A1").currentRegion.toArray();
    csv.write(src + ".out.csv", data);                         // UTF-8 with BOM (no garbled text when opened in Excel)
    csv.write(src + ".sjis.csv", data, "shift_jis");
    const tsv = csv.stringify(data, delimiter: "\t");          // tab-separated string
    const back = csv.parse(tsv, delimiter: "\t");              // any[][]
    debug.print(back.rows, back.cols);
}

15.4.6 JSON (json)

Used with import * as json from "json"; (RAS_Json).

import * as json from "json";

export function loadSettings(p: string): string {
    const v = json.read(p);                                    // detects the encoding
    if (!json.isMap(v)) return "";
    const settings = v as Map<string, any>;                    // an object is a Map<string, any>
    const items = settings.get("items") as any[];              // an array is an any[] (0-based)
    debug.print(items.length, json.get(v, "items[0].name"), json.get(v, "owner.mail") ?? "(none)");
    settings.set("updated", now());
    json.write(p, settings);                                   // indent 2, UTF-8 without BOM
    return json.stringify(settings);                           // single-line JSON
}

15.4.7 XML (xml)

Used with import * as xml from "xml"; (RAS_Xml). It does not use MSXML; RAS parses and writes the XML itself (so debug runs and tests give the same results). A document is represented as a tree of xml.XmlNode.

import * as xml from "xml";

export function readOrders(p: string) {
    const root = xml.read(p);                                    // the root element; the encoding is decided by the BOM and the XML declaration
    for (const order of root.elements("order")) {               // child elements
        debug.print(order.attr("id"), order.childText("customer/name"), order.element("total").text);
    }
    debug.print(root.descendants("item").length);               // descendant elements

    const doc = xml.element("orders");                           // a new document
    const o = doc.addElement("order").setAttr("id", "A-1");
    o.addElement("name", "apples & oranges");                    // & and the like become &amp; when written
    o.addComment("memo");
    xml.write(p + ".out.xml", doc);                              // <?xml version="1.0" encoding="UTF-8"?> and indent 2
    debug.print(xml.stringify(doc, 0));                          // single line
}

15.4.8 Timing (console.time / timeLog / timeEnd)

console.time("Totals");
// …
console.timeLog("Totals");     // Totals: 125.0ms (keeps timing)
console.timeEnd("Totals");     // Totals: 310.0ms (ends)

16. Editor support (IntelliSense) and documentation comments

16.1 Documentation comments (JSDoc style)

Documentation comments use the JSDoc style (/** ... */).

/**
 * Returns the last row of the given column.
 *
 * Returns `1` for an empty column.
 * @param col Column number (1-based; matches Excel's column numbers)
 * @returns The row number of the last row
 * @example
 * const last = Sheet1.lastRow(2);
 * @see {@link firstEmptyRow}
 */
export function lastRow(this: Excel.Worksheet, col: int = 1): int { ... }

16.1.1 Targets

A /** */ written immediately before a declaration is treated as that declaration's documentation. The declarations are functions, extension methods, classes, class members, interfaces, module-level const / let, external functions declared with declare, and declarations in type definitions (.d.ras).

16.1.2 Supported tags

Tag Purpose
(body) The summary. The first paragraph is shown as the summary in the completion list, and the full text in quick info. Markdown can be used
@param name description Describes an argument. Shown as the description of that argument in parameter info
@returns description Describes the return value
@template T description Describes a generic type parameter (§2.4)
@throws description Errors that may be raised
@example A usage example (shown as a code block)
@remarks Additional notes
@deprecated description Deprecated. Shows a strikethrough and a warning at use sites
@see / {@link name} A link to a related item. In quick info, {@link} becomes a link that jumps to the definition
@since The version in which it was added
@property Only for members with arguments in type definitions (.d.ras). Indicates that the member is a property with arguments rather than a method, and allows assignment to the call form (listBox.selected(i) = true, ws.cells(1, 2) = v) (§3.6.3)
@emitAs name Only for properties in type definitions (.d.ras). In generated code, refers to the property name instead of this property. Used when there is a successor property that returns the same value and works in more cases (Range.Count → CountLarge, because count gives an error for ranges larger than the Long limit, such as cells of a whole sheet). The source keeps the original name (count)

16.1.3 Output to VBA

16.2 IntelliSense features

ras lsp provides the equivalent of VS Code's IntelliSense as standard LSP features.

Feature LSP method Description
Member list (completion) textDocument/completion, completionItem/resolve After a ., shows the members of the receiver's type (RAS classes, COM types such as Excel, the built-in members of arrays and strings, and the array methods of collections (§4.4)) and the extension methods that apply. Members of COM types and globals are shown in camelCase (§15.3.1). At positions other than after a ., shows the variables, functions, types, keywords, and snippets in scope. Inside an argument list, also shows the names of named arguments (§16.2.1)
Quick info (hover) textDocument/hover Shows the signature in RAS syntax, the JSDoc (summary, arguments, return value, example), and the inferred type
Parameter info textDocument/signatureHelp Triggered by ( and ,; highlights the signature and the current argument, and shows the @param description of that argument. It is also shown for members added by RAS (extend; §9.4.1). For members that RAS gives an extra calling form (range of a sheet; §9.4.2), that form is shown as another signature (overload), and the one that fits the arguments is selected (3 or more arguments, or a first argument that is a number)
Excel formulas Completion, hover, parameter info Inside a fx`…` formula, shows completion, signatures, and descriptions of Excel worksheet functions (§2.7)
Go to definition / Go to type definition textDocument/definition, typeDefinition Also goes to the original definition for generics and extension methods
Find references textDocument/references
Rename textDocument/rename, prepareRename Rejected if the new name collides with another name differing only in case (§13.6) or is a VBA reserved word
Symbol list textDocument/documentSymbol, workspace/symbol Outline view and symbol search
Inlay hints textDocument/inlayHint The inferred types, the inferred type arguments of generics, and byref arguments at the call site (shown as byref)
Semantic tokens textDocument/semanticTokens Colors byref arguments, extension methods, COM members, and so on, which the TextMate grammar cannot distinguish
Diagnostics textDocument/publishDiagnostics The linter rules of §6, and compile errors at sync time (§14.6)
Code actions textDocument/codeAction Quick fixes (rewrite host names written in VBA spelling to camelCase (§15.3.1; at that spot only / throughout the file; also responds to source.fixAll on save), add the import for a function or extension method that is not imported, replace a literal passed to a byref argument with a temporary variable, add as to a narrowing conversion, etc.)
CodeLens textDocument/codeLens The state of optimizations applied (inlining, bulk transfer, loop fusion, DoEvents insertion), "Show generated VBA", "Run in Excel" and "Debug run" for functions that can be started on their own, and "Run in Excel" and "Debug run" at the top of a form's code-behind (§14.10.7, §14.11.8)
Formatting textDocument/formatting, rangeFormatting The same as ras fmt. However, before formatting, the same fixes as ras check --fix (§6 rule 14) are applied
Folding textDocument/foldingRange

16.2.1 Member list details

16.2.2 Quick info details

16.2.3 Type definitions for Excel and others

16.2.4 Responsiveness

16.2.5 Find references and rename details

16.2.6 Semantic tokens

16.2.7 Candidates that are not imported


17. Reference implementations and libraries used

Selection policy: it can be bundled into a single static binary; the license is permissive, such as MIT / Apache-2.0; and maintenance is ongoing. GPL implementations are used only as design references, and their code is not reused. The version and license of each library are checked when it is adopted.

17.1 The compiler itself (Rust)

Purpose Choice Reason / notes
Lexing logos Generates a fast lexer
Syntax tree rowan rust-analyzer's lossless CST. It preserves whitespace and comments, so it suits the formatter, the LSP, and retrieving JSDoc
Incremental computation salsa Query-based incremental computation used in rust-analyzer. The basis of the LSP's responsiveness (§16.2.4)
Parsing Hand-written recursive descent References: oxc_parser (a fast TS parser written in Rust; handling of the TS grammar), Biome's JS/TS parser (error recovery on a rowan-style CST), and rust-analyzer's parser (building trees with an event-based approach). RAS has its own syntax such as byref / inline, so an existing TS parser is not reused
Position conversion line-index From rust-analyzer. Converts between byte positions and the LSP's UTF-16 positions
JSDoc parsing In-house Reference: oxc's JSDoc parsing implementation
Formatter In-house (intermediate representation + printer approach) References: Biome's biome_formatter and Prettier's design
CLI error display annotate-snippets Error display with source in the same format as rustc
CLI arguments clap
Configuration files toml, serde ras.toml
File watching notify, notify-debouncer-full ras watch
Parallelism rayon Parallel code generation per module
Code page conversion encoding_rs Conversion to CP932 (Shift_JIS, equivalent to Windows-31J) and others, and detection of characters that cannot be represented (§13.7)
CRC32 crc32fast The same CRC-32 as the Bridge side's RtlComputeCrc32; used to check content hashes (§14.6)
Testing insta (snapshots), proptest, cargo-fuzz Snapshot tests of RAS → VBA output, and fuzzing of the parser

17.2 LSP

Purpose Choice Reason / notes
LSP transport layer lsp-server + lsp-types rust-analyzer's synchronous LSP foundation. It lets us control the thread design combined with salsa ourselves
Alternative tower-lsp-server An asynchronous (tokio) high-level framework (a community fork of the original tower-lsp). An alternative if lsp-server turns out to be too much to implement

17.3 Offline writing (§14.9)

No Rust library that can write vbaProject.bin was found (ovba is read-only), so we built our own. Reading and writing vbaProject.bin (CFB, MS-OVBA, module sources, and the designer storage of user forms) is shared with xljs and lives in the vba module of the umya-spreadsheet fork (umya_spreadsheet::vba). What remains in crates/ras-ovba is the byte-preserving manipulation of OPC packages (pack / unpack, adding, copying, deleting, and renaming sheets, creating an empty workbook, and reading .xlsb) and the RAS-specific parts (the markers of the managed region, and detecting generated forms).

Purpose Choice / reference Notes
Reading and writing OPC (zip) zip Unchanged entries are raw-copied without recompression
Reading and writing compound files (CFB) cfb Storage and stream operations for vbaProject.bin
MS-OVBA compression and decompression In-house (vba::compression in the umya-spreadsheet fork) References: Kavod.Vba.Compression (C#, MIT), NetOfficeFw/VbaCompression (C#), Beakerboy/MS-OVBA-Compression (Python)
Procedure for generating vbaProject.bin In-house (vba in the umya-spreadsheet fork) References: Beakerboy/vbaProject-Compiler (Python; generates vbaProject.bin from source), NetOfficeFw/vbamc (C#; a compiler that generates vbaProject.bin)
For read verification and tests ovba (Rust, read-only) Used for cross-checking by re-reading the written vbaProject.bin with another implementation (§14.9.3; the tests of vba in the umya-spreadsheet fork and the tests of crates/ras-ovba). The VBA reading part of calamine is also a reference
Verification tool oletools (olevba, Python) Analyzes the output files in CI and checks that the source and the dir stream are consistent
OPC part layout Reference: XlsxWriter's add_vba_project How to write [Content_Types].xml and the relationships
User forms (§14.11) Port of internal/vba/userforms from xlflow (Go, MIT) FormSpec, validation, generation and reading of MS-OFORMS designer storage, and images (StdPicture). No compatibility with xlflow is kept (kind is only ras.userform)
Specifications [MS-OVBA], [MS-CFB], [MS-VBAL], [MS-OFORMS] Primary sources. The implementation treats them as authoritative

17.4 Windows integration (live sync §14.1–14.8, ras typegen)

Purpose Choice / reference Notes
Win32 API and COM windows Shared memory (CreateFileMappingW), ROT (GetRunningObjectTable), IDispatch, ITypeLib / ITypeInfo (ras typegen)
IDispatch calls Thin in-house wrapper The windows crate has only low-level APIs, so calls by name (GetIDsOfNames → Invoke) and VARIANT conversion are written in-house
VBE manipulation and sync approach References: Ariawase's vbac.wsf (VBA export/import), Rubberduck (C#, GPL-3) Rubberduck is GPL, so it is a design reference only

17.5 References for language design and static analysis

Reference Purpose
[MS-VBAL] (VBA language specification) Primary source for the semantics of the output VBA (evaluation order, type conversion, default members, etc.)
Rubberduck's list of inspections Checking the coverage of VBA pitfalls (§13) and linter rules (design reference only)
twinBASIC Design reference for extending a VBA-compatible language (generics, etc.) (commercial; reference only)
TypeScript / C# language specifications Syntax (TS), and the semantics of numeric types, extension methods, and generics (C#)

17.6 VS Code extension

Purpose Choice Notes
LSP client vscode-languageclient Only launches ras lsp --stdio (§7.4)
TextMate grammar Derived from microsoft/TypeScript-TmLanguage Adds byref / byval / inline / noinline / resume and numeric literal suffixes
Bundling and packaging esbuild, @vscode/vsce

18. Open issues

None at present.

Decided