RAS Playground 日本語 GitHub

Getting started

Cheat sheet

RAS is a language with TypeScript-like syntax that compiles to VBA (.bas / .cls) and runs in Excel. For the detailed specification, see RAS_Language_Specification.md. This cheat sheet can also be shown with ras cheatsheet. All code examples pass ras check.

Differences from TypeScript (read this first)

Types

RAS VBA Notes
int / long / short / byte Long / LongLong / Integer / Byte Integer literals are int (0xFF, and the column number 0cAA = 27). long is 64-bit Office only
double / float Double / Single Decimal literals are double
currency / decimal Currency / Variant (CDec) 1.5m is a decimal
string / boolean / date String / Boolean / Date
any / object Variant / Object Members of object are late-bound
cellValue Variant A cell value: an any that may be an error value (narrow it with isError)
T[] / T[][] Dynamic array / 2-D array Indexes start at 0
Map<K, V> Equivalent to Scripting.Dictionary Keys are numbers, strings, or dates
struct / { a: A; b: B } / [A, B] Type Value types
A | B Variant / Object Narrow with instanceof / typeof
Excel.Range etc. Range etc. Bundled type definitions

Variables and control flow

export function basics(): string {
    const limit = 10;                 // const for anything that is never reassigned
    let total = 0;                    // int
    let ratio = 0.0;                  // double
    let name: string = "";
    const names: string[] = ["a", "b"];

    for (let i = 0; i < limit; i++) {
        if (i % 2 == 0) {
            continue;
        }
        total += i;
    }
    for (const n of names) {
        name += n.toUpperCase();
    }
    for (const i of 0..names.length) {   // i = 0, 1, ..., length - 1
        name += names[^(i + 1)][..1];     // from the end, one at a time: its first character
    }
    while (total > 100) {
        total = total / 2;            // integer division
    }
    ratio = total as double / limit;  // real division
    switch (names.length) {
        case 0:
            return "none";
        case 1:
        case 2:
            return `${name}: ${total} (${ratio})`;   // template string
        default:
            return name;
    }
}

Functions, extension methods, and lambdas

/** A doc comment (becomes a VBA comment and an editor hint). */
export function area(width: double, height: double = 1.0): double {
    return width * height;
}

// byref: modifies the caller's variable
function increment(byref n: int, by: int = 1) {
    n += by;
}

// Variadic parameters (VBA ParamArray): make the last parameter ...name: any[]. An empty array if none are passed
export function joinPath(first: string, ...rest: any[]): string {
    return rest.length == 0 ? first : first + "\\" + rest.join("\\");   // joinPath("C:", "work", 2026)
}

// Extension method: make the first parameter this, and you can call ws.lastRow()
export function lastRow(this: Excel.Worksheet, col: int = 1): int {
    return this.cells(this.rows.count, col).end(xlUp).row;
}

export function lambdas(): int {
    const xs = [3, 1, 2];
    const doubled = xs.map(x => x * 2).filter(x => x > 2);
    const sum = doubled.reduce((acc, x) => acc + x, 0);
    let count = 0;
    increment(count, by: 2);          // named argument
    return sum + count + area(2.0) as int;
}

Properties (get / set)

let cache = 0;
let names: string[] = ["", "", ""];

// Module properties (VBA Property Get / Let; Property Set if the value is an object type)
export get total(): int {
    return cache;
}
export set total(v: int) {            // read-only if you write no setter
    cache = v;
}

// Property with arguments: the last setter parameter 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 useProps(ws: Excel.Worksheet, o: object) {
    total = 3;                        // read and write like a variable (Module.total from other files)
    total += 1;
    label(0) = "x";                   // for a property with arguments, assign to the call form
    label(0) += "y";
    ws.cells(1, 2) = total;           // you can also assign to an Excel property with arguments (assigns to the cell's value)
    o.prop(1) = label(0);             // member of object / any (looked up at run time)
}

The same forms work inside a class (get item(key: string): int { ... } / set item(key: string, value: int) { ... }, bag.item("k") = 1). Writing export get / export set in a sheet file (objects/Sheet1.ras) or a form's code-behind makes them properties of that sheet or form (Sheet1.count = 3, frmInput.count).

Structs, tuples, classes, and enums

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

enum Color { red, green = 5, blue }

interface Shape {
    area(): double;                   // member names cannot contain _ (VBA cannot implement them. E0342)
}

export class Rect implements Shape {
    private w: double;
    private h: double;
    constructor(w: double, h: double) {
        this.w = w;
        this.h = h;
    }
    area(): double {
        return this.w * this.h;
    }
}

function divmod(a: int, b: int): [int, int] {
    return [a / b, a % b];
}

export function values(): double {
    const p: Point = { x: 1, y: 2 };
    const q = p;                      // a copy (value type)
    const [quot, rem] = divmod(17, 5);
    const { x, y } = p;
    const box: Shape = new Rect(2.0, 3.0);
    const ages = new Map<string, int>();
    ages.set("a", quot + rem + x + y + q.x);
    const c = Color.green;
    return box.area() + ages.get("a") + (c as int);
}

Error handling

export function errors(path: string): string {
    try {
        if (path == "") {
            throw new Error("The path is empty");
        }
        const book = workbooks.open(path);
        book.close(false);
        return "ok";
    } catch (e) {
        return `Error ${e.code}: ${e.description}`;   // VBA Err.Number / Description
    } finally {
        status("");
    }
}

export function ignoreErrors() {
    // On Error Resume Next: write only resume; in the catch
    try {
        Sheet1.showAllData();
    } catch {
        resume;
    }
}

Working with Excel

// Turns off screen updating, events, and automatic calculation for the whole function (restored when it ends)
@fast
export function fill() {
    const ws = Sheet1;                              // refer to sheets by code name
    const last = ws.cells(ws.rows.count, 1).end(xlUp).row;
    for (let r = 2; r <= last; r++) {
        // A loop that reads and writes cells one at a time is converted to bulk Range <-> array transfers
        // A cell error value (#N/A etc.) causes a run-time error when calculated or compared, so turn it into null first
        ws.cells(r, 3).value = (Excel.errorToNull(ws.cells(r, 2).value) ?? 0) * 2;
    }
    ws.cells(1, 0cAA).value = "Column AA";        // 0cAA is column number 27 (A = 1. A column-letter literal like 0x)
    ws.range("C1").value = "Doubled";
    ws.range("C1").font.bold = true;
    ws.range("C2:C" + last).numberFormat = "#,##0";
    // A range extended with rows / columns up, down, left, and right (extend(up, down, left, right). Can be named; negative numbers shrink it)
    ws.range("A2:C2").extend(up: 1, down: last - 2).borders.lineStyle = xlContinuous;
    ws.usedRange.lastCell.interior.color = rgb(255, 255, 0);   // the bottom-right cell of the range (lastCell)
    ws.range(2, 1, last, 3).font.italic = true;   // a range by row / column numbers (top row, left column, bottom row, right column) = A2:C{last}
}

export function readAll(): double {
    const ws = Sheet1;
    const data = ws.range("A1").currentRegion.toArray();   // 2-D array (cellValue[][]. Indexes start at 0)
    let total = 0.0;
    for (let r = 1; r < data.length; r++) {
        const v = data[r][1];
        if (isError(v)) continue;                       // skip error values (#N/A etc.)
        total += v as double;
    }
    const names = worksheets.map(s => s.name);         // collections can be used like arrays
    debug.print(names.join(","), total);
    return total;
}

export function ask(): string {
    if (msgBox("Continue?", vbYesNo + vbQuestion) != vbYes) {
        return "";
    }
    return inputBox("Enter a month", "Input", "2026/4");
}

// Evaluates an Excel formula (VBA's [SUM(A1:A10)] / Evaluate). ${...} embeds a value
export function sums(code: string): double {
    const ws = Sheet1;
    const total = fx`SUM(A1:A10)`;
    const hit = ws.fx`SUMIF(A:A, "${code}", B:B)`;
    if (isError(total) || isError(hit)) return 0;      // a formula's result can also be an error value
    return total + hit;
}

Ranges, sheets, workbooks, strings, and arrays have extension methods from the RAS standard library (usable without an import; spec §9.5 and §15.4).

import * as path from "path";
import * as fs from "fs";

export function report() {
    const ws = Sheet1;
    const head = ws.find("Code");                         // the first matching cell (ignores full-width / half-width and whitespace differences; null if none)
    if (head == null) return;
    const totals = ws.findAll(/^Total/, visibleOnly: true); // by regular expression, visible cells only
    const price = ws.findByHeaders("Unit price", "A-1");    // the cell where a column header and a row header intersect
    const next = head.stepOffset(0, 1);                    // one to the right, treating a merged cell as one and skipping hidden rows / columns
    const last = ws.columns(1).lastRow(skipBlank: true);   // the last row of column A (formulas returning "" are not counted. 0 if empty)
    const rows = head.readTable(["Code", /Amount|Sales/], untilBlank: true);   // read, choosing columns by header (cellValue[][])
    ws.range("H1").writeTable(rows, ["Code", "Amount"]);                       // write below the headers, choosing columns
    const copy = thisWorkbook.copySheet(Sheet1, "May");    // copy and name it (right after the original)
    const month = thisWorkbook.sheet(/^Sheet\d+$/);          // a sheet by name or regular expression (null if none)
    console.time("load");
    for (const p of fs.walk(path.join(thisWorkbook.path, "data"), "*.csv")) {
        debug.print(path.basename(p, ".csv"), "コード".width(), "コード".width());   // width (full-width 2, half-width 1): 6 4
    }
    console.timeEnd("load");                                // load: 12.3ms
    debug.print(totals.length, price.row, next.address, last, copy.name, month == null, "a, b ,c".split(/\s*,\s*/).length, " x ".trim(" "));
}

Code for sheets and ThisWorkbook (events and so on) goes in files under objects/. The file becomes the whole module of that sheet.

// objects/Sheet1.ras (the module of the sheet with code name Sheet1)
// Events are @on("Worksheet.EventName"). This sheet is this
@on("Worksheet.Change")
function changed(target: Excel.Range) {
    if (target.column == 1) {
        this.range("D1").value = target.address;
    }
}

// An exported function can be called from other modules as Sheet1.clearInput()
export function clearInput() {
    this.range("A2:C100").clearContents();
}
// objects/ThisWorkbook.ras (the workbook module)
@on("Workbook.Open")
function opened() {
    status("");
    // Attach an event handler at run time: on(event, handler). addEventListener does the same
    const l = Sheet1.on("SelectionChange", (target) => { status(target.address); });
    this.on("BeforeClose", () => msgBox("Close?", vbYesNo) == vbYes);   // returning false cancels
    l.off();                                                                   // detach
}

on works on controls (this.btnOK.on("Click", () => { ... })), sheets, workbooks, and application. It also works on arrays and collections (this.controls.on("Change", (c) => { ... }), [this.txtA, this.txtB].on(...); the handler receives the member as its first argument). Handlers attached in a form's code-behind are detached when the form closes. For a shape, pass the name of the function to run as a macro (shape.on("Click", reload); it is set as OnAction). Events of a specific control are written as @on("btnOK.Click").

User forms (forms/<name>.form.json and .ras)

// forms/frmInput.ras (code-behind. this is the form)
export let cancelled = false;         // a public variable: frmInput.cancelled / f.cancelled from other modules

function constructor(name: string, limit: int = 20) {   // the arguments of new frmInput(...)
    this.txtName.text = name;
}

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

@on("btnCancel.Click")
function cancel() {
    cancelled = true;
    this.close();                     // no value (also for the × button): the type's default ("")
}
// from a function in src/
export function askName() {
    const name = new frmInput("Smith").showModal();   // unloaded when closed
    if (name == "") return;                           // cancelled
    const f: frmInput = new frmInput(name, 10);       // the form name can also be written as a type
    f.show();
}
// forms/frmEntry.ras (input validation. Attach zod-style rules and they are validated when the input is committed,
// with the error shown in a label named <control name>Error. If there is none, a transparent label is created under the control)
import * as z from "validation";

const form = new z.FormValidator();

function constructor() {
    form.rule(this.txtName, z.string().required("Enter a name").max(20));
    // z.int().min(0).max(150) / z.string().email() / .regex(…) / .refine(v => …, "…") etc.
    // When the rules depend on a previous input, call rule / remove again in a Change handler
}

@on("btnOK.Click")
function submit() {
    if (!form.validateAll()) return;  // validates everything and focuses the first error
    this.close(this.txtName.text);
}
// forms/frmWork.ras (progress bar. Put
// { "type": "ProgressBar", "name": "pbWork", "caption": "Working", "value": 0 } in the .form.json.
// It shows a caption, a percentage, and the bar; the bar's default color is the system highlight color)
@on("btnOK.Click")
function run() {
    const total = 200;
    this.pbWork.max = total;                  // min / max (default 0 / 100)
    for (let i = 1; i <= total; i++) {
        this.pbWork.value = i;                // the bar and the percentage at the top right move (this.pbWork.text is "56%")
    }
    this.pbWork.caption = "Done";
    this.pbWork.barColor = rgb(16, 124, 16);  // trackColor / foreColor / valueColor / showValue / visible …
}
// forms/frmPick.ras (file / folder picker. Put
// { "type": "FilePicker", "name": "fpBook", "title": "Select a workbook",
//   "filters": [{ "description": "Excel workbooks", "extensions": "*.xlsx; *.xlsm" }] } in the .form.json.
// The "..." at the right of the field opens Application.FileDialog. You can also paste into the field)
@on("fpBook.Change")                          // the field's event (picked / pasted)
function changed() {
    this.btnOK.enabled = this.fpBook.path != "";
}

@on("btnOK.Click")
function ok() {
    this.fpBook.dialogType = 4;               // FolderPicker (1 Open / 2 SaveAs / 3 FilePicker)
    const chosen = this.fpBook.browse();      // an array of the chosen paths. An empty array if cancelled
    if (chosen.length == 0) return;
    this.close(this.fpBook.paths.join(";"));  // paths: the paths in the field (without the "…")
}

Even when the display scale (DPI) is not 100%, the inner size of the form matches the design (adjusted on load).

Without the form designer, you can also build and show a dialog from code alone (import … from "dialog"; spec §14.11.15).

import { Dialog, choose, Progress } from "dialog";

export function confirmSave(): string {
    // Any buttons: the number of the button pressed (from 0). × and Esc (the cancel button) give -1
    const r = choose("Save your changes?", ["Commit changes", "Commit as...", "Cancel"], title: "Save", cancel: 2);
    if (r < 0) return "";
    return r == 0 ? "save" : "saveAs";
}

export function askExport() {
    const d = new Dialog("Export", "Choose the output settings");   // laid out in one column from the top. The buttons are OK and Cancel
    const kind = d.select("Format", ["CSV", "TSV"]);                // also text / password / combo / list / radio / folder / label
    const file = d.file("Output", dialogType: 2).required("Choose an output location");   // rule(z.string()…) can be attached too
    const head = d.checkbox("Write a header row", true);
    if (d.show() != 0) return;                     // anything other than OK (Cancel, ×). It does not close with OK if a rule fails
    debug.print(kind.text, kind.index, file.text, head.checked);
}

export function longWork() {
    const p = new Progress("Calculating", max: 500);    // modeless, shown immediately. "Stop" or × sets cancelled
    for (let i = 1; i <= 500; i++) {
        if (p.cancelled) break;
        p.value = i;
        p.message = `${i} / 500`;
    }
    p.close();
}

Reading and writing files (Open / Print # / Close)

export function copyLines(src: string, dest: string) {
    const inp = freeFile();
    fileOpen(inp, src, forInput);                     // Open src For Input As #inp
    const out = freeFile();
    fileOpen(out, dest, forAppend);                   // For Output / Append / Binary / Random
    while (!eof(inp)) {
        const line = lineInput(inp);                  // Line Input #inp, line
        printLine(out, line, "\t", line.length);     // Print #out, line; vbTab; … (print does not add a newline)
    }
    writeLine(out, "Total", 3, true);                 // Write #out, "Total", 3, True
    fileClose(inp, out);                              // Close #inp, #out (with no arguments, closes all)
    if (dir(dest + ".bak") != "") kill(dest + ".bak");
    fileCopy(dest, dest + ".bak");
}

There are also input(n, a, b) (Input #), inputString(n, charCount), fileGet / filePut (Get / Put), seek, lock / unlock, fileWidth, rename(old, new) (Name … As …), and reset(). The modes of fileOpen (forInput etc.), accessRead, and lockShared are written as constants.

Files, CSV, JSON, and XML with a specified encoding (fs / csv / json / xml)

Open and TextStream only handle Shift_JIS (ANSI) or UTF-16. Read and write UTF-8 (with or without BOM), Shift_JIS, EUC-JP, and so on with fs.readText / fs.writeText (they use ADODB.Stream). CSV, JSON, and XML are parsed and written by the standard libraries (spec §15.4.4 to §15.4.7).

import * as fs from "fs";
import * as csv from "csv";
import * as json from "json";
import * as xml from "xml";

export function formats(dir: string) {
    const text = fs.readText(dir + "\\in.txt");                      // detects the encoding (BOM → UTF-8 → Shift_JIS)
    fs.writeText(dir + "\\out.txt", text, "shift_jis");             // "utf8" (default. No BOM) / "utf8bom" / "eucjp" / "utf16le" …
    fs.writeLines(dir + "\\log.txt", ["start", "end"], append: true);
    const lines = fs.readLines(dir + "\\log.txt", "utf8");          // an array of lines (CR LF, LF, CR)

    const rows = csv.read(dir + "\\sales.csv", cast: true);         // any[][] (converts numbers, dates, and TRUE/FALSE)
    csv.write(dir + "\\copy.csv", rows);                             // UTF-8 with BOM (does not garble in Excel). "shift_jis" also works
    const tsv = csv.stringify(rows, delimiter: "\t");

    const v = json.parse("{\"name\": \"Smith\", \"items\": [{\"price\": 120}]}");
    const order = v as Map<string, any>;                              // an object is Map<string, any>, an array is any[]
    const price = json.get(v, "items[0].price") ?? 0;                 // extract by position (null if missing)
    order.set("total", price * 2);
    json.write(dir + "\\order.json", order);                         // indent of 2

    const root = xml.read(dir + "\\orders.xml");                     // the root element (xml.XmlNode)
    for (const o of root.elements("order")) {
        debug.print(o.attr("id"), o.childText("customer/name"));
    }
    const doc = xml.element("orders");
    doc.addElement("order").setAttr("id", "1").addElement("name", "apple");
    xml.write(dir + "\\new.xml", doc, encoding: "shift_jis");        // the encoding in the XML declaration is also Shift_JIS
    debug.print(lines.length, tsv.length, json.stringify(order), xml.stringify(doc, 0));
}

VBA arrays (arrays held in any, ReDim)

To work with arrays using the same indexes as hand-written VBA (1-based, multi-dimensional), hold them in a variable of type any (spec §4.6). In new code, use T[] and range.toArray().

export function table(rows: int): any {
    let t: any;
    redim(t, 1, rows, 1, 3);                      // ReDim t(1 To rows, 1 To 3). The elements are null (Empty)
    for (let r = lBound(t); r <= uBound(t); r++) {
        t[r, 1] = r;                              // t(r, 1) = r (indexes as written; comma-separated indexes are only for any)
        t[r, 3] = t[r, 1] * 2;
    }
    redimPreserve(t, 1, rows, 1, uBound(t, 2) + 1);   // ReDim Preserve (only the last dimension can change)
    const v: any = Excel.errorToNull(Sheet1.range("A1:C3").value);   // the value of multiple cells is a 1-based 2-D array
    t[1, 2] = v[1, 1];
    let total = 0;
    for (const x of v) {                          // For Each (all elements)
        total += x ?? 0;
    }
    let copy = t;                                 // arrays are values (copied on assignment, as an any argument, and as a return value)
    erase(copy);                                  // Erase (isArray(copy) stays true)
    return t;
}

Writing VBA as is (vba blocks)

VBA that RAS cannot express (As Any in Declare, conditional compilation, and so on) goes in a vba block and is output into the module as is. Declare functions to be called from RAS with declare function. Importing an existing workbook also leaves procedures that cannot be converted in this form.

vba`
Public Function LegacyTotal(ByVal n As Long) As Long
    LegacyTotal = n * 2
End Function
`;
declare function LegacyTotal(n: int): int;

export function useLegacy(): int {
    return LegacyTotal(21);
}

Tests (test/*.test.ras)

// test/report.test.ras
describe("fill", () => {
    beforeEach(() => {
        Sheet1.range("A1:B3").value = [["Name", "Qty"], ["a", "1"], ["b", "2"]];
    });

    test("writes the doubled value to column C", () => {
        Sheet1.cells(2, 3).value = Sheet1.cells(2, 2).value * 2;
        expect(Sheet1.cells(2, 3).value).toBe(2);
        expect(Sheet1.range("A2:A3").value).toEqual([["a"], ["b"]]);
    });

    test("answers No to the confirmation", () => {
        const box = mockMsgBox(() => vbNo);
        expect(msgBox("Continue?", vbYesNo)).toBe(vbNo);
        expect(box.calls.length).toBe(1);
    });

    test.each([[1, 2], [2, 4]])("double of %i is %i", (n: int, want: int) => {
        expect(n * 2).toBe(want);
    });
});

Commands (usable without Excel)

Command Description
ras check Type check and lint (--fix fixes warnings that can be fixed mechanically; --message-format json for JSON)
ras check --target stand-in Also warns about APIs that cannot be used when running without Excel
ras explain E0301 Explanation of an error or warning code and how to fix it
ras doc Range.find Signature and description of an API, and whether the stand-in has it (--list Excel.Worksheet lists the members)
ras run Module.func Run without Excel and show the output, errors, and changed cells (--json; --view for HTML with a grid view)
ras test Run test/**/*.test.ras (-t name, --reporter json)
ras book dump Book.xlsm List sheets, formulas, and names (cells with --sheet Sheet1 --range A1:F20)
ras book diff a.xlsx b.xlsx Differences between two workbooks
ras book view Book.xlsx Create HTML that shows the sheets in a grid
ras book edit Book.xlsm --sheet Sheet1 --set B2=100 Edit cells and write to the workbook (--clear A1:C3, --insert 3:4, --delete B:B, --op '<JSON>')
ras sheet list / add Summary / copy Sheet1 / rename Sheet1 --code-name Sales / remove Sheet3 List, add, duplicate, rename, and remove sheets (changes the workbook and the objects/ files together)
ras build / ras pack Output VBA / write it into the workbook