RAS Playground 日本語 GitHub

Working with Excel

Sheet and workbook code

Files in src/ become standard modules, and files in objects/ directly under the project become the modules of sheets and ThisWorkbook (the "Microsoft Excel Objects" in the VBE). RAS files and VBA modules correspond one to one (spec §12.1.1), and the file becomes the whole module (spec §12.2).

// objects/Sheet1.ras (the module of the sheet with code name Sheet1)
@on("Worksheet.Change")
function onChange(target: Excel.Range) {
    this.range("D1").value = target.address;      // this is this sheet (VBA's Me)
}

/** Can be called from other modules as Sheet1.clearInput(). */
export function clearInput() {
    this.range("A2:C100").clearContents();
}

Event handlers attached at run time

To attach the same handling to many controls, or to attach and detach it conditionally, attach it from any file with target.on("event", handler) (addEventListener is the same). Detach it with the off() it returns (RAS_Listener. Spec §12.2.3). In a sheet file, you can also write this.CommandButton1.on("Click", ...) for a control on the sheet.

// src/watch.ras
export function startWatch() {
    Sheet1.on("Change", (target) => {
        debug.print(target.address);
    });
    application.on("SheetActivate", (sh) => {
        debug.print("activate");
    });
}

In a form, you can attach to all members of a collection, as in this.controls.on("Change", (c) => { … }). For a shape or Form control button, register a macro with shape.on("Click", reload) (OnAction).

Adding, copying, deleting, and renaming sheets

Instead of creating or deleting files in objects/ directly, use ras sheet ("RAS: Add Sheet" and so on in VS Code) to change the workbook's sheets and the files together (spec §14.16).

ras sheet list                                   # list of sheets (tab name, code name, file)
ras sheet add Summary --after Sheet1             # adds a sheet and creates objects/Sheet3.ras
ras sheet copy Sheet1 April                      # copies the sheet and also copies objects/Sheet1.ras
ras sheet rename Sheet1 --name Revenue --code-name Sales   # also changes the file name and source references (Sheet1.…)
ras sheet remove Sheet3                          # stops with the reason if there is code or references (--force deletes)

If the workbook is closed, it rewrites the workbook file; if it is open in Excel, it operates Excel (Windows only).

On sync (ras sync, ras watch, VS Code) and ras pack (including when VS Code creates a project), for each sheet and ThisWorkbook in the workbook, the file objects/Sheet1.ras / objects/ThisWorkbook.ras is created if it does not exist (spec §14.7.2. It can be turned off with [sync] sheet-files = false in ras.toml). The created file contains only comments with examples of how to write, and does not change the workbook's module until you write code.