Language and projects
Language specification
1. Design philosophy and basic policy
- Target: A transpiled language that converts to standard VBA (
.bas,.cls, and the Excel document modulesThisWorkbook/ sheet modules). - Syntax: A subset of TypeScript plus the minimum extensions needed to absorb VBA-specific features. The syntax is kept so that existing TS-family editor assets (TextMate grammars, etc.) are easy to reuse. The only added keywords are
byref/byval/inline/noinline/resume; every other extension is expressed with decorators (@xxx) and by repurposing existing TS syntax (declare module,using, etc.). - Delegation of static verification: Strict type checking and constraint verification are handled on the RAS side (compiler and LSP).
- Zero boilerplate: The compiler automatically inserts the "boilerplate that must be written every time" and the "code that avoids pitfalls you step on if you do not know about them" in VBA, so the user does not have to write them (§12, §13).
- Speed is the compiler's responsibility: In VBA, function calls, COM calls (cell access),
Variantarithmetic, and late binding are slow. In RAS, the compiler converts code the user writes naturally into fast VBA through inline expansion, bulk transfer, and concrete typing (§8, §9). - Target environment: Excel for Windows (Office 2007 or later, 32-bit / 64-bit). Other Office hosts such as Access / Word are not supported for the time being. Excel for Mac is out of scope (Mac-specific
#If Macbranches,Libpaths, AppleScript integration, etc. are not generated). - Keep the output VBA readable: Generated code must be debuggable by humans. Every statement carries a source map that traces back to the original RAS source position (§14.8).
2. Type system and variable declarations
- Variable and constant declarations: Use
let(reassignable) andconst(not reassignable).
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& |
- Column number literal (
0c): Writing Excel column letters after0cgives anintwith that column number (1-based) (ws.cells(r, 0cAA)becomesws.Cells(r, 27&)). Case is not distinguished. A value beyond0cXFD(16384, the last column in Excel 2007 and later), or anything other than column letters (0c1, a_separator) is a syntax error. A type suffix cannot be added (Lis also treated as a column letter). It can also be used in ranges (for (const c of 0cB..0cE)covers columns B to D). - In VBA, an integer literal with a small value becomes the
Integertype, and300 * 200overflows inIntegerarithmetic. RAS always emits numeric literals with a type suffix to avoid this pitfall. - Assignment to a
short/bytevariable is implicitly allowed if the constant is within the range of that type (same as C#).
2.3 Numeric operations and type conversion
Follows the C# rules.
Type of binary operations: Both operands are promoted to the "larger" of the two in this order:
int<long<float<double(an explicit cast is required whencurrencyordecimalis mixed in). Operations betweenbyte/shortare promoted toint(the pitfall where VBA'sInteger * IntegerstaysIntegerand overflows is avoided by insertingCLng)./between integers: Integer division (truncation toward 0). Converted to VBA's\(the operands are integer types, so VBA rounding does not occur). To get real-number division, make one sidedouble.%: For integers, VBA'sMod(the sign follows the dividend, matching C#); if a real number is involved, the runtimeRAS_FMod.RAS_FModis the exact remainder, like C'sfmodand JavaScript's%: it does not computea / b, so a large quotient does not overflow (1e308 % 1e-10).Overflow: Overflow in integer arithmetic is a run-time error (VBA error 6). Overflow in a constant expression is a compile error (equivalent to C#
checked).Implicit type conversion: Only widening conversions (
byte→short→int→long,int→double,float→double, etc.) are implicitly allowed. Narrowing conversions are made explicit withx as int(repurposing the TSassyntax).Real-to-integer conversion truncates: VBA's
CLnguses banker's rounding, sox as intis converted toCLng(Fix(x))to truncate toward 0 like C#. To round, useMath.round(x).Principle of concrete type output: Variables, arguments, and return values whose type is statically determined are declared with a concrete type (because
Variantcan be about twice as slow or worse).Variantis used only where the type isany.Automatic resolution of
Set:Setis added automatically to assignments of object types, based on type information. When the type of the right-hand side is not statically determined in an assignment to ananytype, the runtime helperRAS_Assign(which branches onIsObject) is used.Type inference: The type of the initializer expression is used as is (
let x = 1isint,let y = 1.5isdouble).
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
Determining type arguments: The type arguments of a call are inferred from the argument types. If they cannot be inferred, specify them explicitly, as in
f<int>(...). If they are still undetermined, it is an error.Combinations emitted: All calls in the project (including calls from inside other generic functions) are followed transitively, and only the combinations reached are emitted. A generic function that is never called emits nothing. If it is
exported, an information message is shown.Names:
originalName__VBAType[_VBAType...](for example,maxOf__Long,Map__String_Long). Arrays getArr(forT = int[],__LongArr). If a name exceeds VBA's identifier length limit (255 characters), a shortened name with a hash is used.Sharing the same VBA type: Even if the type arguments differ, combinations that produce the same VBA type notation (for example,
anyanddecimal, orobjects with late binding) share one implementation.Macro entry points and calls from outside: A generic function cannot be a macro entry point or the target of
@onorApplication.Run(error). To have it called from outside, wrap it in a non-generic function with concrete types.Setand comparison operators: WhetherSetis needed (§2), whether==becomesIsor=(§13.2), and whether conversion throughVariantis needed are decided for each concrete type after expansion. Each implementation is optimized as code with concrete types and is also a target of inline expansion (§8).Type parameter constraints: Constraints can be written as
T extends type. The following constraints are provided as standard.Comparable: types that support<,>, etc. (numeric types,string,date,currency)Numeric: types that support arithmetic operationsObjectType: object types (types assigned withSet)
A type argument that does not satisfy the constraint is an error at compile time.
No infinite expansion: Recursion in which the type argument grows with each call (such as calling
f<T[]>insidef<T>) is an error.Default type arguments: A type parameter of a class or interface can have a default type argument written as
T = type. A type written with the type arguments omitted becomes that type argument (Sheetsininterface Sheets<T = Worksheet | Chart>isSheets<Worksheet | Chart>). Type parameters after one with a default type argument also need default type arguments (E0171). They cannot be written on type parameters of functions (the type arguments are inferred from the arguments).Code size warning: A warning is issued when the number of implementations emitted from one generic definition exceeds the threshold (default 16). The size limits of procedures and modules after expansion are checked by the rules in §13.8.
Lambdas: Lambdas that are turned into classes inside a generic function (§4.1) are also emitted as separate classes for each combination of type arguments.
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
- An object literal
{ a: 1, b: x }(including the shorthand{ x, y }) becomes a value of that struct when the expected type is a struct. Missing or extra fields and type mismatches are compile-time errors. Only fields declared asname?: Tcan be omitted, and an omitted field gets the default value (0/""/false/ an empty array). - A literal writes directly into the destination fields (no temporary variable or copy is created).
return { ... }writes directly to the return value, andarr.push({ ... })writes directly into the array element. Only when the right-hand side refers to the destination (p = { x: p.y, y: p.x }) is it assembled in a temporary variable and then assigned. - A struct is a value type. Assignment copies, and
const q = p; q.x = 1;does not changep(unlike TypeScript objects). It is passed to functions by reference (ByRef).
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;
getreturns a copy of the value. For a key that is not registered, it returns a struct with all fields at their default values (check withhas). To change a value, take it out into a variable, modify it, andsetit again (m.get(k).x = 1is an error because it would assign to a copy).- Reference by subscript (
m[k]) is not supported. - There is one object per map, and no object is created per element.
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.
- Assigning to
any/object, or passing to a function that takesany(includingconsole.log). Pass the fields individually. publicfields of a class (make themprivate), and members of an interface. They can be used in the arguments and return values of class methods (emitted asFriend).- The arguments, return value, and captures of an arrow function that is stored in a variable or passed as an argument (one that is converted to a class; §4.1).
- 2D arrays of structs, and
null.
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
- VBA type: If all members are object types (classes, interfaces, host types,
object,Map, function types), it is stored in anObject; otherwise in aVariant. Member access uses late binding. - Normalization: Nested union types are flattened and duplicate members are removed. Members are displayed with value types first, then object types (
int | stringis shown asstring | int). Ifanyis included, the result isany; ifobjectis included, the other object types are absorbed intoobject. null:| nullcan be written only on union types that include an object type (Excel.Range | string | null).string | int | nullis an error.- Types that cannot be included:
void, structs (they do not fit in aVariant; §2.5.7), type parameters, andwstr/astr. - Unions can also be used in array elements,
Mapvalues, type arguments, and type aliases (type Shape = Circle | Square;,(Circle | Square)[],Box<string | int>).
2.6.2 Assignment and operations
- Assignment: A value that can be assigned to any of the members can be assigned to the union type. A value of a union type can be assigned to a type to which all members can be assigned (
Excel.Worksheet | Excel.Chartcan be assigned toobject). - Assignment to a type that only some members can be assigned to: The assignment is made with a warning (
W0306) (const ws: Excel.Worksheet = activeSheet;). As with VBA'sSet ws = ActiveSheet, if the value turns out to be a member that cannot be assigned (a chart sheet), a run-time error occurs (for value types, VBA's implicit type conversion applies). The warning is not issued if you narrow withinstanceof/typeofor convert withas. Assignment to a type that none of the members can be assigned to is an error. - Numeric widening: A value that is accepted by widening rather than being exactly a member's type is converted to that member's type before being stored (putting
1intostring | doublegivesCDbl(1&)). This is becausetypeofreturns the type name of the stored value. ==/!=: Can be written if the value can be compared with any of the members. When comparing union types stored in aVariant, values of different kinds (number, string, boolean, date, error value, object) are not equal (unlike VBA's=, it neither converts nor raises an error; the runtimeRAS_UnionEq). Two error values (such as#N/A) are compared by error number.- Ordering comparisons and string concatenation: Can be written only when they work for all members (
<betweenint | doublevalues,"a" + v). Perform arithmetic after narrowing. as: Can be written if conversion to or from any of the members is possible (v as double).- Conditional operator and array literals: A union type is not inferred from values of different types (
cond ? 1 : "a"is errorE0302). Add a type annotation, as inconst x: string | int = ....
2.6.3 Members
- Common members: A property or method can be used when all member types have a member with the same name. Completion also shows only the common members. Members of a union type that includes a value type cannot be referenced (extension methods that accept a union type as the receiver can be called).
- Properties: The type is the union of the types of each member. Properties whose type differs between members, and properties that are read-only in any member, cannot be assigned to.
- Methods: The arguments must be accepted by the methods of all members. The return value is the union of each member's return value (
voidif any of them isvoid). Named arguments can be used only when the argument names and order are the same in every method. Generic methods cannot be called. - Members that exist in only some types: When a member of a host type (Excel, etc.) exists in only some of the member types, a warning (
W0305) is issued, and it is typed as a member of the type that has it and called with late binding (activeSheet.cells(1, 1)isExcel.Range; a run-time error occurs if a chart sheet is active). A member that exists only in a RAS class is an error. - Members not in the type definitions: A host member that is in none of the member types' type definitions is called with late binding after warning
W0301, the same as for a single type.
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 |
- Combinations:
!=and!swap true and false. The result ofaapplies to thebina && band ina || b. Ifx instanceof A || x instanceof Bis true, the type isA | B. - Scope of effect: Each branch of
if, each branch of the conditional operator, the body ofwhile/for, and the right-hand side of&&/||. When one branch of anifexits withreturn/throw/break/continue, it also applies to the statements after theifin the same block.if (!(s instanceof Excel.Worksheet)) return; s.cells(1, 1).value = 1; // s: Excel.Worksheet any/object: Narrowed byinstanceof(activeSheet, etc.).anyis also narrowed by basic type names such astypeof x == "String".- Not narrowed: Variables that are assigned within that scope (
=, compound assignment,++/--), module variables, fields, andthis. A narrowed variable cannot be passed to abyrefargument (E0415; because if the callee rewrites it, the narrowing no longer holds). typeofnames:typeofreturns the same names as VBA'sTypeName("String","Long","Double","Boolean", class names). Comparing with JavaScript names ("string","number", etc.) never matches, so a warning (W0312) is issued.- Generated VBA: The variable stays in its declared type (
Object/Variant), and members at narrowed locations are also called with late binding.instanceofbecomesTypeOf … Is, andtypeofbecomesTypeName.
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[] |
- Kinds of sheets: The sheet collection is declared as
interface Sheets<T = Worksheet | Chart>(§2.4.1). Excel 4.0 macro sheets appear asWorksheetobjects. Dialog sheets (DialogSheet) are not in the type definitions, so in a workbook that contains dialog sheets, the false branch ofinstanceof Excel.Worksheetis not necessarily anExcel.Chart. - The
getOpenFilenamearray: The array Excel returns is 1-based, but all RAS arrays are 0-based (§13.3), so the generated VBA converts it to 0-based with the runtimeRAS_Rebase1.typeofgives"Variant()". - Existing code:
const ws: Excel.Worksheet = activeSheet;andactiveSheet.cells(1, 1)still compile as is, with a warning (W0306/W0305). - Not made union types: Values that vary with the arguments or situation (
selection,application.inputBox/evaluate/run/caller,Range.value, etc.), values that may returnNull, and values that switch between a single object and a collection depending on whether an argument is given (chartObjects(...), etc.) remainobject/any. Those that may return a cell error value (Range.value, etc.) arecellValue(§2.6.6).
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.
- Type:
cellValueis "ananythat may be an error value". It is stored in aVariantlikeany, andtypeofis the same. Any value can be assigned to it (ws.range("A1").value = 1). - Values of
cellValue: In the bundled type definitions:Range.value/value2,evaluate(fx`…`, andevaluateofApplication/Worksheet),match/index/vLookupofApplication, andcvErr.toArray()/usedTable()arecellValue[][], andtoColumn()/toRow()arecellValue[]. A subscript ofcellValueand an element infor...ofare alsocellValue(thevalueof multiple cells is a 2D array). A variable or function return value without a type annotation is inferred ascellValue, like any other type. You can also writecellValueon your own functions, fields, and arguments. - Warning (
W0313): A warning is issued when acellValuevalue is used as follows: comparison (==/!=/<, etc.), operation (+/-/!/++, etc.), condition (if/while/&&/ ternary operator),switch, subscript, conversion withas(exceptas any), and assignment to a variable, argument, return value, or field of a type other thancellValue(includingany, since once it is put inanyit is no longer warned about afterward). No warnings are issued in test files. - Uses that are not warned:
== null/!= null(they becomeIsEmpty/IsNull),??(an error value is notnull, so the result is alsocellValue),typeof, template literals (they becomeError 2042, same asCStr), member references, assignment tocellValuevariables, arguments, and fields, andas any(which states explicitly that it is used as is). In the bundled type definitions, arguments that accept error values arecellValue(isError,isNumeric,isDate,isEmpty,isNull,isObject,isArray,typeName,varType,debug.print, the lookup value ofmatch/vLookupofApplication, and the judgment functions ofWorksheetFunctionsuch asisError/isNA/isErr/ifError/ifNa).console.logalso accepts it. - Narrowing (same scope as §2.6.4): For a
cellValuein a local variable or argument, it becomesanyon the false side ofisError(v)(VBA'sIsError,WorksheetFunction.IsError), on the true side ofisNumeric(v)/isDate(v)/isEmpty(v)/isNull(v)/isObject(v)/isArray(v), and on the false side oftypeof v == "Error". For other type names such astypeof v == "String", it becomes that type on the true side. The same applies after exiting, as inif (isError(v)) continue;. If the variable is assigned within that scope, the narrowing does not hold. - Conversion:
Excel.errorToNull(v)turns an error value intonulland changes thecellValuein the type toany(cellValue[][]becomesany[][]; §13.3). Add a default value with??(Excel.errorToNull(v) ?? 0). - Warning (
W0315): A cell also holds text people typed ("twelve" in a column of quantities, "TBD" in a column of dates). VBA'sCInt/CLng/CLngLng/CLngPtr/CByte/CSng/CDbl/CCur/CDecraise run-time error 13 on text that is not a number, andCDateon text that is not a date, so a conversion of a cell's value without a check is warned about. It applies when the argument is acellValuevalue, or a local variable initialized with one (or with theany/stringresult of a function given one, such asExcel.errorToNull(…)ortrim(…)), also afterisError()has narrowed it toany. There is no warning when the same function checks the same expression withisNumeric(…)(isDate(…)forcDate) ortypeof. Besides the explicit conversions, an implicit conversion of the same value is warned about: given to a variable of a number's type (byte,short,int,long,float,double,currency,decimal) ordate(a declaration with a type annotation, an assignment) or to an argument of the project's own function (const n: int = v; VBA converts it asCIntdoes and raises the same run-time error 13).W0313is not given for the same argument (W0315covers it). No warnings are issued in test files.
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()`;
- Meaning:
fx`formula`is the same asevaluate("formula"), andobj.fx`formula`is the same asobj.evaluate("formula"). The type of the value isany. An unqualifiedfxbecomes VBA'sEvaluate(…), like an unqualifiedevaluate(as with VBA's[…], it isApplication.Evaluatein a standard module and that sheet'sEvaluatein a sheet module). ${…}: As in an ordinary template literal, the value of a RAS expression is converted to a string and embedded (it becomes a&concatenation). If there is no${…}, it is emitted as a string literal. A"inside the formula is rewritten as""in the VBA string.- Tags: The only tag allowed is
fx; any other tagged template is an error. No newline can be placed betweenfxand the template (a newline makes it a separate expression). - Conversion from VBA (§14.7.1):
[A1],[$B$2],[Sheet1!A1:B2], and[SUM(A1:A3)]in expressions becomefx`…`. A bracketed name consisting only of an identifier ([name], such as[_Default]) stays as a name. - Editor (§16.2): The contents of the formula are colored as an Excel formula (functions, cell references, sheet names, strings, numbers, error values,
TRUE/FALSE, operators; inside${…}it is RAS). Completion shows Excel worksheet functions (about 520 in the calculation engine of the Excel stand-in; it insertsNAME(), and shows parameter info inside the(of a function and the signature and description on hovering over a function name. Nothing is shown inside formula strings or cell references. The list of functions (crates/ras-compiler/stdlib/formula_functions.json) is generated from the stand-in's engine, and an automated test checks that they match.
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;
- Meaning: The same as creating one with
new VBScript.RegExp()and settingpatternand the flag properties. The type isVBScript.RegExp. For VBA, a call to the runtimeRAS_RegExp(pattern, flags)is emitted (it is created withCreateObject("VBScript.RegExp"); no reference setting is required). - Reusing the object: A literal used only for matching creates one object and reuses it (
RAS_SharedRegExp; one per pattern and flags, created on first use). Even if written inside a loop or a function called many times,CreateObjectand pattern parsing happen only once. This applies to literals on whichtest/execute/replaceis called directly (/^abc/i.test(s)), and to aconstinside a function whose variable is used only intest/execute/replacecalls. In every other case (rewriting properties, passing as an argument, putting in aletor a field, returning from a function, etc.), the program could modify or retain the object, so a new object is created each time it is evaluated (RAS_RegExp). - Flags:
g(global: find all matches),i(ignoreCase: do not distinguish upper and lower case),m(multiline: make^and$also match the start and end of each line),w(do not distinguish half-width from full-width). They can be combined (/abc/giw). Other characters and duplicate flags are errors. - Pattern: The characters written between
/and/are passed topatternas is. Unlike string literals,\is not doubled (\d). A/in the pattern is written\/(it can be written as is inside[…]). The syntax is that ofVBScript.RegExp(lookbehind(?<=…)/(?<!…), named groups(?<name>…)and\k<name>, Unicode properties\p{…}, and any(?…other than(?:(?=(?!cannot be used: they are a compile error, because VBA raises run-time error 5017 on them while the JavaScript of a debug run accepts them). A literal is written on one line. - How
/is read: A/at a position where an expression starts (at the start of a statement, after an operator,(,[,,,=,:,return, etc., or afterfor (const m of) starts a regular expression literal. A/after a value (after a name, a literal,),], or}) is division. If there is no closing/on the same line, it is also read as division. To start a statement with a regular expression literal right after a}, enclose it in parentheses. - Not distinguishing half-width from full-width (
w):VBScript.RegExphas no such feature, so the pattern is rewritten at compile time so that each character also matches the character of the other width. It does not remain on the object as a flag (it has no effect on a pattern assigned later topattern).- Characters covered: Alphanumerics and symbols (
!to~and!to~), whitespace (half-width space and full-width space),¥and¥, and katakana and punctuation (アandア,。「」、・ーand。「」、・ー). For katakana with a voiced or semi-voiced sound mark, two half-width characters and one full-width character match (ガandガ). Hiragana and kanji are left as they are. - Characters:
abecomes[aa], andガandガbecome(?:ガ|ガ). For katakana that can take a voiced or semi-voiced mark, it is also checked that the half-width character is not followed by a mark (カbecomes(?:カ|カ(?!゙));ガisガ, notカ). The same applies to symbols with\such as\.and to symbols written full-width (.) ([..]). \d,\w,\s: They also match full-width digits ([0-90-9]), full-width alphanumerics and_, and full-width whitespace.\D,\W, and\Sare their negations.- Character classes
[…]: The other width is added to each character and range ([a-z]becomes[a-za-z],[^0-9]becomes[^0-90-9], and[ア-ン]gets the half-width katakana added one character at a time). A character class containing katakana involving voiced or semi-voiced marks is rewritten as an alternation so thatガis treated as one character ([ガ]becomes(?:ガ|[ガ]),[カ]becomes(?:カ(?!゙)|[カ]), and[^ガ]means "one character other thanガandガ(a two-character pair likeガcounts as one character)").VBScript.RegExphas no lookbehind, so when a negated character class[^…]is rewritten in this form, it does not match only a half-width voiced or semi-voiced mark (゙,゚) (so that it does not match only the mark ofガ; as a result, it also does not match a standalone゙that does not follow katakana). Also, a゙or゚written in the pattern itself (/゙/w) also matches the mark ofガ.\D,\W, and\Sinside a character class are not rewritten. - Left as is: Characters written by code such as
\x41andA, backreferences (\1),\b, quantifiers ({2,3}), and(?:,(?=,(?!. - Combination with
i: Case distinction is removed withi. When written together withw, alphabetic characters also gain the full-width upper- and lowercase characters of the other width (theaof/abc/iwbecomes[aaA]and also matchesABC).
- Characters covered: Alphanumerics and symbols (
- Debug execution: Creates the same object as
new VBScript.RegExp()(§14.10.5). - Editor (§16.2): The pattern is colored as a regular expression.
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.
- Syntax: you can write a
byref(orbyval) modifier before an argument name. When omitted, the argument isByVal. - What you can pass to
byref: a variable (including a field or an array element). Literals and expressions cannot be passed (E0406). As an exception, abyrefargument of typeany(VBA'sByRef … As Variant) also accepts an expression (as in VBA, a temporary value is passed and any write to it is discarded). This is the form VBA code uses to pass a large array to a function without copying it, and import (§14.7.1) leavesVariantand array arguments that have noByValasbyref. - Visibility:
export function→Public; withoutexport→Private. - Return value:
return expr;is converted tofunctionName = exprplusExit Function(theExitis omitted for a trailingreturn). An object-typed return value becomesSet functionName = expr. voidfunctions: emitted as aSub.- Variadic arguments: writing the last argument as
...rest: any[]receives the extra arguments as an array (VBA'sParamArray; §3.5).
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;
}
- Within the body,
thisrefers to the received object (the receiver). - Writing
byref this: Tpasses the receiver by reference (for examplefunction inc(byref this: int) { this++; }→counter.inc()). In this case the receiver must be an lvalue, and passing a literal or an expression is an error (same as §6 rule 5). - Generics: type parameters can be used, as in
function first<T>(this: T[]): T(§2.4).
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&)
- An extension method call is converted to an ordinary function call qualified with the defining module (the receiver becomes the first argument). The run-time cost is the same as an ordinary function call, and extension methods are also subject to the inline expansion and automatic in-loop expansion of §8 (
inline function f(this: T)is also allowed). - The receiver expression is evaluated once, before the other arguments.
3.2.3 Resolution rules
- 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.
- Scope: candidates are the extension methods defined in the same module and the
exported extension methods ofimported modules. - 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). - 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.
- 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. nullreceiver: even when an object-typed receiver isNothing, the call is made (same as C#). Inside the extension method you can testthis == null.
3.2.4 Standard library
- Array methods such as
map/filter/forEach/reduce, string methods (trim,padLeft,startsWith, etc.), and the RangetoArray/fromArray(§9.4) are defined as extension methods of the standard library. They are resolved by the same mechanism as user-defined extension methods, and the loop fusion of §4 is performed as a compiler built-in optimization for them. - The standard library's extension methods are imported implicitly. If a user-defined extension method with the same name and signature is in scope, the user-defined one takes precedence (with a warning).
- RAS standard library (written in RAS): the extension methods for Range, sheets and workbooks (§9.5) and for strings and arrays (§15.4.1, §15.4.2) are written in RAS modules bundled with the compiler (
ras_range/ras_sheet/ras_book/ras_text/ras_array, in files such ascrates/ras-compiler/stdlib/ras_range.ras). Anexported extension method can be used in any module without an import.- Priority: type members (such as Excel's
Range.Find) take highest priority, then the module's own and imported extension methods, and finally the extension methods of the RAS standard library. If the project has an extension method of the same name (such aslastRow(this: Excel.Worksheet)), that one is called without a warning. - Output: only the functions that are used (and the functions they call) are emitted, into one module per library (
RAS_Range,RAS_Sheet,RAS_Book,RAS_Text,RAS_Array;Option Private Module). The VBA procedure name isRAS_followed by the name with its first letter capitalized (ws.findAll(…)→RAS_Sheet.RAS_FindAll(ws, …)). This is so that no procedure is created with the same spelling as an Excel member (Find), which would make the VBE rewrite the case of.Findthroughout the project.path/fs/csv/json/xml(§15.4.3 to §15.4.7) are modules of the RAS standard library that you use viaimport, and they are emitted intoRAS_Path,RAS_Fs,RAS_Csv,RAS_JsonandRAS_Xml. To distinguish functions of the same name in two libraries, the procedure names ofcsv/json/xmlinclude the library name (csv.parse→RAS_Csv.RAS_CsvParse,json.parse→RAS_Json.RAS_JsonParse). TheXmlNodeofxmlbecomes the class moduleXmlNode. - Debug run (§14.10): the same RAS code is converted to JavaScript and run. In a debug run without Excel, it works on the members of the Excel stand-in (§14.10.8).
- Priority: type members (such as Excel's
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.
- Syntax: write
name: exprinside the argument list. It can be mixed with unnamed (positional) arguments, but a positional argument cannot follow a named one (f(1, c: "z")is allowed;f(a: 1, 2)is not). Named arguments may appear in any order among themselves. - Calls where it can be used: declared functions, methods, constructors (
new), extension methods, Excel / VBA members and global functions (the argument names in.d.ras), and default members. Write the argument name exactly as declared (case-sensitive; Excel / VBA argument names are also camelCase:lookAt,matchCase). - Late binding: it can also be written in a member call on a value of type
any/object(sheet.select(replace: false)). Since there is no declaration, no reordering is done; it is emitted as a VBA named argument (sheet.select replace:=False), and VBA looks up the argument by name at run time (a wrong name causes run-time error 448). Do not write a positional argument after a named one. In the compatibility layer ofras run/ras test, the arguments are passed as positional arguments in the order written. - Calls where it cannot be used: values of function type (lambdas), built-in methods such as those of arrays and strings, and
new Error/new Map/new Array. - Extension methods: the
thisargument is passed as the receiver, so it cannot be specified by name. - Conversion: at compile time the arguments are reordered into declaration order, and arguments that were not specified are treated as
undefined(the same as omitting an argument in §3.4). For a RAS function the default value is filled in; for an Excel / VBA member the argument is left blank (VBA's,,). - Evaluation order: argument expressions are evaluated in declaration order, not in the order written. Be careful when passing several expressions with side effects.
- Errors: a nonexistent argument name (E0412; if only the case differs, the correct name is shown), specifying the same argument twice or a positional argument after a named one (E0413), a missing required argument (E0414), and a call that cannot use named arguments (E0411). A
...variadic argument cannot be specified by name (E0412).
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).
- Declaration: it can be written only as the last argument of a function (including extension methods), a class method, or a constructor (including a form's
constructor). The type isany[].byref,?and default values cannot be attached. It cannot be written in arrow functions, interface members, properties (get/set) ordeclarefunctions (allE0152). - Inside the function: it is used as an ordinary 0-based
any[](rest.length,for...of, indexing,push, passing it to other functions). If no extra arguments were passed, it is an empty array (length == 0). It is a copy of the caller's variables, so modifying the elements does not affect the caller. - Call: any number of extra arguments can be passed, each passed as
any(nullbecomesEmpty). If you pass an array, the array becomes a single element (it is not expanded; there is no call-site spreadf(...xs)). It cannot be specified with named arguments (§3.3) (E0412). If required arguments are missing, it isE0402("at least 1 required"). - Output: the last argument becomes
ParamArray name() As Variant. VBA cannot pass aParamArrayby reference to other procedures ("Invalid use of ParamArray"), and RAS's array operations pass arrays to the runtime by reference, so at the start of the procedure it is copied to an ordinary variable (ras_name; anany[]is aVariant), and the body uses that. In VBA,ParamArrayandOptionalcannot be combined, so the arguments of a function with variadic arguments are never madeOptional(calls from RAS fill in the default values; §3.3). For a constructor, the factory function (New_Foo) receives the arguments withParamArrayand passes the copied array toRAS_Init. - Inline expansion: functions with variadic arguments are not expanded (§8).
- Debug run (§14.10): it becomes a JavaScript rest parameter (
...rest).
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.
- Inside a class: a property of an instance of that class (or of the class itself, if
staticis added).private/protectedcan also be added. - At the top level of a file: a property of that module (§3.6.1). With
exportit isPublic; without it,Private.
The rules are common to both.
- getter: returns a value. If the return type annotation is omitted, it is inferred from the body, as for functions.
- setter: receives the assigned value in the last argument (which cannot be made optional). A return type cannot be written. If the value's type is an object type (a class,
object, an Excel object, etc.),Property Setis emitted; otherwiseProperty Letis emitted, and the assigning side uses or omitsSetaccordingly. If the value's type isany(cellValue, or a union of a value and an object), it can become eitherLetorSetdepending on the assigned value (§2.3), so both aProperty Letand aProperty Setwith the same body are emitted. - Read-only and write-only: a property with only a getter cannot be assigned to (
E0323). A property with only a setter cannot be read (E0326;+=and++also read, so they cannot be used). - Getter and setter must agree: the getter's type and the setter's value type must be the same. For a property with arguments (§3.6.2), the setter's arguments are the getter's arguments plus one value argument (the number, types and optionality must match; the argument names may differ). VBA cannot compile a mismatched
Property Get/Let, so RAS reports an error (E0155). - Things that cannot be written: type parameters,
byrefarguments, thethisargument of an extension method, and@macro,@on,@init,@udf,@ribbon(E0155). Accessors are not inline-expanded (§8). They cannot be written in type definitions (.d.ras); there a property is written asname: T, and a property with arguments asname(index: K): T(§15.3). - Doc comments: they can be written on both the getter and the setter, but a VBA property has a single description (
VB_Description), so the getter's is emitted (or the setter's if there is no getter).
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).
- Files in
src/(standard modules): within the file it is read and written like a variable (total,total = 3,total += 1). From other files, either import theexported one withimport { total } from "src/settings", or refer to it with the module name (Settings.total; §12.1.2). If only the getter isexported, it is read-only from other files. - Files of sheets and
ThisWorkbook(objects/<code name>.ras; §12.2) and form code-behind (forms/<name>.ras; §14.11.2): it becomes a property of that sheet, workbook or form. The rules are the same as for functions in these files: within the file it is referred to by name alone (count), and anexported one can also be referred to asthis.count. From other files, anexported one is referred to through the sheet's code name, the form's name, or a form instance (Sheet1.count,Sheet1.count = 3,frmInput.count,new frmInput().count). Each form instance has its own value. - Names: as with functions, a property with the same name as a VBA function gets a trailing
_in the generated VBA (§13.6). A name that is the same as a sheet or workbook member, or as a control on a sheet, cannot be used (E0651). - Macro and test generation: an accessor does not enter the macro list (§12.4) or the debug-run entry points (§14.10), even if it has no arguments. It is also not a target of "Generate tests" (§14.12.10).
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).
- Reading: call it like a function (
obj.item("k"),item("k"),Sheet1.item("k")). You cannot writeobj.itemwithout the arguments (E0382). - Assignment: assign to the call form (
obj.item("k") = v). Compound assignments such as+=and++/--can also be used (read with the getter, written with the setter; the receiver and argument expressions are evaluated once). The arguments are checked against the setter's arguments (excluding the value), and the value against the type of the setter's last argument. - Optional arguments: as with functions, you can write
key?: stringor a default value. In VBA it becomesOptional, and in aProperty Letit is placed before the value argument. In calls from RAS, the default value is embedded for an omitted argument (same as §3.3). Named arguments can also be used. - What can be assigned to in call form: properties declared here, and those in §3.6.3. The return value of a function or method cannot be assigned to (
E0325).d[key] = valueon aScripting.Dictionary/Mapcan be used as before.
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.
- Members of
object/any(late binding): you can writeo.prop(i) = vand, for the default member,o(i) = v. VBA looks up the property at run time. Any value can be assigned, and whetherSetis used is decided by the value's type, as for other assignments (if the value isany, it is decided at run time; §2.3). - Host members that have type definitions: the bundled type definitions (
.d.ras) write both properties with arguments and methods asName(args): T, so they cannot be told apart from the syntax. Only members marked@propertyin their doc comment can be assigned to (§16.1.2). Assigning to a call of an unmarked member isE0325(so that assignments to a method's return value are not overlooked). In the bundled type definitions, the following are marked.- MSForms:
list(index, column)andcolumn(column, index)ofListBox/ComboBox, andselected(index)ofListBox. The value is checked against the type of that property (booleanforselected,anyforlist). A form with all arguments omitted can also be assigned to (this.lstItems.list = rows). Scripting.Dictionary:d.item(key) = vand the default memberd(key) = v(the same asd[key] = v).- Excel:
range(...),cells(...),rows(...)andcolumns(...), which return a cell range (those ofApplication,WorksheetandRange, and the unqualified globals), anditem(...),offset(...),resize(...)and the default member (rng(1, 2)) ofRange.ws.range(top, left, bottom, right), written with row and column numbers (§9.4.2), is the same.
- MSForms:
- Assigning to a property that returns a cell range: as in VBA,
ws.cells(1, 2) = vis an assignment to the default member (Value) of the returned cell range (the same result asws.cells(1, 2).value = v). The value is checked against the type ofvalue(cellValue), andws.Cells(1, 2) = vis emitted to VBA as is, always withoutSet. A value of an object type cannot be assigned (E0325; VBA would needSet, but this property cannot beSet).+=and++can also be used (ws.cells(1, 2) += 1). The bulk transfer of cell values (§9) applies only to reads and writes written with.value, so inside loops it is better to write.value. - A call to a property that returns an object other than a cell range (such as
workbooks.item(1)) cannot be assigned to (write the member you assign to). - Project type definitions: host members written in the project's own
.d.rascan be assigned to in the same way if you write@propertyin their doc comment.
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.
Syntax: an arrow function
(x) => x * 2or(x: double) => { return x * 2; }.Capture restrictions (important):
- The only variables of the outer scope that an anonymous function can refer to are immutable ones (
constor read-only variables). - Modifying an outer variable inside an anonymous function is a compile error.
- Exception: inside an event handler passed to
on/addEventListener(§12.2.3), module variables (including variables of form and sheet files) can be modified. Event handlers normally hold state, and module variables are referred to as the variable itself rather than as a copy made at creation. Local variables of the enclosing function cannot be modified even in an event handler.
- The only variables of the outer scope that an anonymous function can refer to are immutable ones (
How
sort/indexOf/includescompare:sort()/sort((a, b) => …)is a stable sort (as in JavaScript, equal elements keep their order). The runtimeRAS_Sort/RAS_SortByis a merge sort, which never reads outside the array even when the comparison function is inconsistent (() => -1). Debug runs sort by the same steps, so such a comparison gives the same order there too.indexOf(x, from)/includes(x, from)compare elements as==on a union (RAS_UnionEq, §2.6.2): values of different kinds are not equal (nullis not equal to0or""), and an error value (#N/Aand the like) does not raise a run-time error. A negativefromcounts from the end, as in JavaScript.
Empty arrays of
any[]: Anany[]lives in aVariant(§9.2.1).[]and a declaration without an initial value become an empty array (Array()), becauseReDim PreserveofpushonEmptyis run-time error 13.
4.1 Transpilation specification
Lambda expressions are converted with the following priority.
- 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(theiinarr.filter(f).map((x, i) => ...), or the result ofarr.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 eachfilter.
- 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
- 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),thisrepresents that form (sheet or workbook) (the form that created the class is held inCaptured_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 asPublic(aprivatemethod of a class called asthis.helper()from an arrow function is emitted asPublictoo). VBA cannot placePublicarray 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.Invokecannot be used because it collides with the member name ofIDispatchand 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
- Targets: host types that have a default member (
(index: any): T) andcount. This is the same set that can be enumerated withfor...of, and the element type is the default member's return typeT. - Available methods:
map/filter/forEach/reduce/some/every/find/findIndex, andtoArray(), which copies the members into an array. The callback's second argument is a 0-based running number (after afilter, the number among the members that passed the filter; §4.1). - The result is an array: the result of
map/filter/toArrayisT[](not a collection). From there on you can use array methods (length/join/sort/slice, etc.) as they are. - Type members take precedence: if the host type has a member of the same name, that one is used (
range.find(...)is Excel'sRange.Find, andrange.sort(...)isRange.Sort). - Element types:
worksheets/book.worksheetsisExcel.Sheets<Excel.Worksheet>andchartsisExcel.Sheets<Excel.Chart>, so the sheet's members are completed for the callback's argument.sheets, which also includes chart sheets, isExcel.Sheets(the elements areobject), and its members use late binding. - Transpilation specification: the loop fusion of §4.1 is performed over
For Each. No array is created (except for the results ofmap/filter/toArray). A collection obtained through a chain of properties (book.worksheets) is evaluated only once. The running number is counted only when the callback receives it. - Modification during enumeration: because the enumeration is done directly with
For Each, you must not modify the collection being enumerated (adding or deleting sheets, etc.) inside the callback. If you need to modify it, copy it withtoArray()first and then process it (worksheets.toArray().forEach(ws => ws.delete())).
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])
^n(position from the end):xs[^n]isxs[xs.length - n].^1is the last element, and^0is the position after the end (meaningful only as the end of a range). It can be written as an array or string index and as the ends of a range. Assignment (xs[^1] = v,xs[^1] += 1) is also possible. For a 2-D array it can be written for either the row or the column (a[^1][0],a[r][^1]). Pointing outside the array causes run-time error 9, like other indexes (for strings, error 5, as withMid$).- Negative indexes do not count from the end:
xs[-1]is outside the array as before (run-time error 9). To count from the end, write it with^. a..b(range): fromaup to just beforeb(bis not included). Either end can be omitted (..bis from the start,a..is to the end, and..is everything). The ends can be written with^n.- Index ranges:
xs[a..b]returns a new array, ands[a..b]returns a string. The original array is unchanged (a value-type copy; struct elements are copied too). The range is clamped to the array (as with JavaScript'ssliceand VBA'sLeft$, the excess is ignored, and ifa >= bthe result is empty). A negativea/bis treated as 0 (unlikeslice, it does not count from the end). It can be used only with 1-D arrays and strings, and not for cutting rows out of a 2-D array or withMap, tuples, or host collections (E0386). A range cannot be assigned to. - Ranges in
for...of:for (const i of a..b)becomesFor i = a To b - 1. Ifais omitted it is 0. The end cannot be omitted, and^cannot be used.bis evaluated once at the start. The loop variable's type isint(longif an end islong). If the loop variable is assigned to in the body (let), the variable becomes a copy of a hidden counter, and the assignment does not affect the next iteration (same as JavaScript). - Where it can be written: a range can be written only inside an index and as the target of
for...of. It cannot be put into a variable or passed as an argument (E0386). - Precedence:
..is weaker than all operators.xs[0..n - 1]is0..(n - 1), andxs[c ? 1 : 2..]is(c ? 1 : 2)... As in C#,^binds with the strength of a unary operator, so an expression needs parentheses (xs[^(i + 1)];xs[^i + 1]is(^i) + 1and is an error).
- Index ranges:
step(n): a new array that collects everynth element from the start (Python'sxs[::n]).nmust be 1 or more (a constant of 0 or less isE0386; at run time, error 5). Combined with a range it isxs[1..].step(2), and for reverse orderxs.toReversed().step(2)(Python'sxs[::-2]).toReversed(): a new array in reverse order. As in JavaScript,reverse()sorts the array itself (the return value isvoid). Ranges,step,sliceandtoReversedall return a new array and do not change the original.transpose()(2-D arrays): returns a new 2-D array with rows and columns swapped (ifmhasrrows andccolumns, the result hascrows andrcolumns, andt[j][i]ism[i][j]; the same as Excel'sTRANSPOSE). The original array is unchanged. The type is the sameT[][]as the original (cellValue[][]fromtoArray()stayscellValue[][]). For an empty array (0 columns), the result is an empty array. UnlikeApplication.Transpose(WorksheetFunction.Transpose), there is no limit on the number of elements (65,536), no conversion to 1-D, and no conversion to aVariantarray.- Row-wise methods of 2-D arrays:
map,filter,forEach,reduce,some,every,findandfindIndexof a 2-D array (T[][]) pass the callback one row at a time (a copy,T[]).filterreturns a 2-D array of the rows that pass,finda row (an empty array when none does).for...ofand an index of a row alone (m[i]) still cannot be used (E0304,E0321).const rows = lines.map(s => s.split("\t")); // map that gives arrays: a 2-D array const errors = rows.filter(r => r[1] == "Error"); // a row at a time const names = rows.map(r => r[0]); // a 1-D arraymapthat gives arrays: amapwhose callback returns an array a row gives a 2-D array. It has as many columns as the longest row; the rest of the short rows is the type's default value ("",0and so on). When every row is empty, the result is an empty array. A callback that returns a 2-D array is an error (E0370).- Transpilation specification: in the loop, each row is copied into a 1-D temporary array before the callback gets it. When the result is a 2-D array, the rows are first gathered in a
Variantarray, then copied afterReDim m(0 To rows - 1, 0 To columns - 1)with the length of the longest row. A 2-D array literal ([[1, 2], [3, 4]]) becomesReDimand an assignment to each cell (when its rows are not literals, the rows are gathered and copied as above).
- Transpilation specification: ranges,
stepandtoReversedare expanded, likeslice, into a copy usingReDimandFor(not into a function call; they can also be used on arrays of structs).transpose()is expanded intoReDim t(0 To columns - 1, 0 To rows - 1)and a doubleForcopy (t(j, i) = m(i, j)) (rows isRAS_Len, columns isRAS_Len2; if columns is 0,Erase). In variable initialization and assignment, it is created directly in the variable. The ends are computed withRAS_ClampRange(clamped to 0 through the length). A string range uses the runtime'sRAS_StrRange,xs[^n]becomesxs(RAS_Len(xs) - n), ands[^n]becomesMid$(s, Len(s) - n + 1, 1).
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
- Multiple indexes
v[i, j]: write the indexes separated by commas (v[i, j],v[i, j, k]). This becomes VBA'sv(i, j). It can be used for reads, assignments and compound assignments (v[i, j] = x,v[i, j] += 1). The indexes are passed as written (no adjustment to 0-based, the same asv[i]onany). The indexes of a compound assignment are evaluated only once.- It can be used only on types whose index can be referenced through late binding (
any,cellValue,object). The result type isany(an element ofcellValueiscellValue). - Writing comma-separated indexes on a typed array, tuple,
Mapor string is an error (E0417). An element of a 2-D arrayT[][]is writtena[r][c].
- It can be used only on types whose index can be referenced through late binding (
redim(a, lower, upper, …):ReDim a(lower To upper, …). Puts intoaa new array (Variant()) with indexes in that range. The elements areEmpty(nullin RAS;a[i] == null). Write the lower and upper bounds (both inclusive;int) two per dimension (1 to 60 dimensions). Whatever valueaheld before is discarded.redimPreserve(a, lower, upper, …):ReDim Preserve a(…). Changes the size while keeping the elements. As in VBA, only the range of the last dimension can be changed, and the number of dimensions cannot be changed (run-time error 9). The elements are kept in order from the start (changing the lower bound shifts the indexes). It can also be used on arrays fromarray(...)andsplit(...), and on a multi-cellrange.value. It cannot be used on a variable that does not hold an array (such asEmpty) (run-time error 13).erase(a):Erase a. Discards the array's elements and index ranges.isArray(a)staystrue,lBound/uBoundand index references cause run-time error 9, andfor...ofcauses run-time error 92 (it can be used again once youredimit). It cannot be used on a variable that does not hold an array (run-time error 13).- First argument: a variable of type
anythat can be assigned to: a local variable, an argument (includingbyref), a module variable, or a class field (this.f). Aconstvariable is not allowed (E0323). Expressions, array elements, properties and host members are not allowed (E0418). A typed array (T[]) is also not allowed (E0418; extend it withpushor recreate it withnew Array<T>(n), and empty it withclear()). An odd number or zero of bounds is alsoE0418. - Used as statements: none of the three returns a value (
void). Using one as a value is an error (E0370). - Built-in functions:
lBound(a)/uBound(a, 2)(dimensions start at 1),isArray(a)andtypeName(a)("Variant()") can be used as they are.for (const x of a)becomesFor Each, and visits the elements of all dimensions in the order in which the first index advances first (a[1, 1],a[2, 1], …,a[1, 2], …). - Arrays as values: a VBA array is a value. Assignment to an
anyvariable (const b = a), ananyargument (ByVal … As Variant), and a function return value become a copy of the array (theRAS_Assignin the generated code doesSetfor an object and an assignment = copy otherwise). To receive the result of modifications made in the callee, use abyrefargument. Objects placed in elements remain references. - Fields of other objects:
obj.grid[i, j] = x(assignment to an element of an array held in a field of an object other thanthis) does not change the original array, because VBA writes to a copy of the field's value. Modify it inside a method of that class (this.grid[i, j] = x), or take it out into a variable, modify it, and put it back. - Cell values: a multi-cell
range.value(cellValue) is a 1-based 2-D array in VBA. Afterconst v: any = Excel.errorToNull(ws.range("A1:C10").value), you can writev[1, 1],lBound(v, 2)(= 1) anduBound(v, 1).range.toArray()is a 0-based RAS array (§9.2.1), and even when put intoanyit stays 0-based (a[0, 0]). An array created withredimcan be written withrange.value = a(a 2-D array as rows and columns, a 1-D array as one row). - Debug run (JavaScript runtime, §14.10): an array created with
redimbehaves as a value that has a lower and upper bound for each dimension (there is no limit on the number of dimensions). Index references,lBound/uBound,isArray,typeName,for...of, copying through assignment or ananyargument,Excel.errorToNull, writing torange.value, andtoEqualin tests are supported. The run-time error numbers (9, 13, 92) also match VBA. A multi-cellrange.value/value2/formulain the Excel stand-in (and when connected to Excel) can be used as a 1-based 2-D array withv[i, j],lBound/uBound,for...ofandredimPreserve. Differences from VBA:- Passing an array created with
redimto host members other thanrange.value(and the arguments of formulas andWorksheetFunction), such as thelistof a list box, is not supported. - VBA keeps the array from
split(...)(String()) asString()even afterredim/redimPreserve. In a debug run the element type is not distinguished, and new elements arenull(""in VBA). - Putting a typed 2-D array (
T[][]) intoanyand then callingredimPreserveon it is not supported (it is treated as 1-D).
- Passing an array created with
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.
eis of typeRAS_Error(withcode,description,source,rasFileandrasLine). The contents ofErrare copied on entering the catch.- Leaving the handler correctly (avoiding a trap): in VBA, if processing continues from within an error handler without a
Resume, the "handler running" state remains and later errors are not caught. After the catch body runs, the compiler always releases the handler state withResume RAS_EndTry_Nbefore rejoining the subsequent processing. - Multiple
trys and nesting within one procedure: VBA has only one valid handler per procedure, so one procedure-wide handlerRAS_Handler:is generated and dispatches on the current try identifierras_tryIdwith aSelect Case. On leaving an inner try, it returns to the outer try's identifier. throw:throw new Error("msg")becomesErr.Raise vbObjectError + 513, <source>, "msg".throw e;(rethrow) callsErr.Raisewith the saved number and description.
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.
- Linter constraint: it is an error if there are other statements inside
catch { resume; }. - Transpilation specification:
On Error Resume Nextat the start of thetry, and alwaysOn Error GoTo 0at the end (if there is an outer try, the outer handler is set again).
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
finallyis converted usingGoTo RAS_Finally_Nand an "exit reason" variable on each exit path, so that it runs on every path: normal completion of thetry,return, leaving the block viabreak/continue, and an uncaught error. After the finally runs, depending on the exit reason, it performsExit Function, rethrowing to the outer handler, etc.using x = expr;(the Explicit Resource Management syntax of TS 5.2) is adopted. It is syntactic sugar for atry/finallythat callsx.dispose()at the end of the scope. It is mainly used for the application state control of §10.
6. Main validation rules of the linter (static analysis)
It validates in real time in the editor and emits Diagnostics.
- Syntax errors
- Reassignment to
constis forbidden - Lambda capture violations
- Purity check of
resumeblocks - Passing a literal to
byrefis forbidden - (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
fooandFoois an error (§13.6). - (Added) Collision with VBA reserved words and built-in names: a warning that it will be renamed automatically (§13.6).
- (Added) Recursive or non-expandable
inlinefunctions: a directly or indirectly recursiveinlinefunction is an error. - (Added) Dependence on unqualified
range/cells/activeSheet: a warning (§13.4). - (Added) Use of
.select()/.activate()/selection: information (performance and stability). - (Added) Characters that cannot be represented in the code page: information that they were escaped automatically (§13.7).
- (Added) Predicted violation of VBA structural limits: the 64 KB procedure limit, the 24 line-continuation limit, etc. (§13.8).
- (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).
- ** 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, andras check --fixand the quick fix rewrite them to camelCase (§15.3.1). - **
typeofcomparison:** comparing with a JavaScript type name, as intypeof x == "string", gives a warning (W0312).typeofreturns the same name as VBA'sTypeName(§2.6.4). - (Added) Use of a cell value (
cellValue): using acellValuevalue, 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 thancellValuewithout narrowing it withisError()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
- Implemented in Rust (decided). Reasons:
- A single binary with no runtime dependency is easy to produce (Windows x64 / arm64, and Linux / macOS built from the same source for CI).
- The Win32 APIs needed for sync (
CreateFileMappingW, event objects) and COM (obtaining Excel through the ROT,IDispatchcalls) can be handled directly with thewindowscrate. - Responsiveness of the LSP, which assumes incremental analysis.
- Parser: a hand-written recursive descent parser (emphasizing error recovery and, for the LSP, position information and subtree reuse).
- Libraries adopted and reference implementations: see §17.
- Platforms: distribution targets Windows (x64 / arm64). Live sync (§14.1 to 14.8) is Windows-only. Build, check, LSP and offline writing (§14.9) depend on neither Excel nor Win32, so they also run on Linux for CI.
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)
- It only launches the binary given by the
ras.pathsetting (searched for on PATH when unset) and connects to it as an LSP client. - All commands are delegated to the LSP's
workspace/executeCommand: "Show generated VBA", "Sync with workbook", "Add sheet", "Copy sheet", "Delete sheet", "Rename sheet" (§14.16), "Open in Excel", "Run macro", "Run form in Excel". - The status bar shows the sync state (target workbook, number of unsynced items, drift warnings).
- IntelliSense (member lists, quick info, parameter info, etc.) is all provided by the LSP server side (
ras lsp), and the extension has no implementation of its own (§16).
7.5 Output layout (build artifacts)
- One module per
.rasfile (§12.1.1). Files insrc/become standard modules (.bas), and files inobjects/(§12.2) become the code of sheet andThisWorkbookmodules (build/<code name>.doccls) - A
.clsfor eachclassdeclaration - The initialization calls added to
ThisWorkbook(§12.3) - The
RAS_Lambda_XXX.clsfiles for escaped lambdas - The runtime library
RAS_Runtime.bas(only the functions actually used are emitted, via tree shaking) - Source maps
build/*.rasmap
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);
}
- Every call to an
inlinefunction is expanded into the caller. It is always expanded regardless of the optimization level (except at-O0, where debuggability takes priority and a normal call is made). - For
export inline function, a normal function definition is also emitted so that it can be called from other modules and from the macro list. A non-exported inline function does not have its definition emitted at all (all calls are already expanded). - Direct or indirect recursion is a compile error.
noinline functionsuppresses automatic expansion (§8.2).
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.
- The callee is a RAS function in the same project and its source is available
- It is not recursive and not
noinline - The cost of its body (number of HIR nodes) is at or below the threshold (
-O1: 40,-O2: 120; configurable inras.toml) - The callee contains no
On Error Resume Next-style try, noStatic-equivalent state, and nousing(if it did, the error state of the expanded code would leak into the caller) - The callee does not reference a
Privatemodule variable or function of another module (it would not be visible from the expansion site) - The expansion does not bring the calling procedure close to VBA's 64KB limit (§13.8; if it would, expansion is stopped and a Hint is shown)
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.
- By-value arguments: The actual argument is evaluated exactly once and assigned to a temporary variable. However, if the actual argument is a "simple variable or literal without side effects" and the formal parameter is not reassigned in the body, it is substituted directly and the temporary variable is omitted.
byrefarguments: Substituted with the actual argument's lvalue. If the lvalue's subscripts contain expressions (such asa(f(i))), the subscripts are first evaluated into temporary variables and fixed.- Local variables: Renamed to
ras_inl{N}_{name}, their declarations are hoisted to the top of the calling procedure, and they are explicitly initialized at the expansion site (§13.1). - Early
return: Areturnthat is not at the end of the body is converted into an assignment to the result variable plus aGoToto a labelRAS_InlEnd_{N}that is unique per expansion. - Calls within expressions: When a call to be expanded appears inside an expression, the compiler converts that statement to A-normal form (ANF) and expands it into a sequence of statements while preserving the evaluation timing of short-circuit evaluation (
&&,||), the ternary operator, and loop conditions. A call inside a loop condition is converted to the formDo ... If Not cond Then Exit Do ... Loop.
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
- Converting
fortoFor...Next:for (let i = a; i < b; i++)is converted toFor i = a To b - 1wheniandbare not modified in the body and the step is constant (VBA'sForevaluates the upper bound only once, so the compiler verifies the conditions under which this matches JS's per-iteration evaluation). When the conditions are not met, it is converted toDo While. - Loop-invariant hoisting:
arr.length,obj.count, and property chains on the same object (such asws.range("A1").font) that can be determined to be invariant inside the loop are saved to temporary variables before the loop. A COM object's properties are considered invariant only when there is no write, method call, or unknown function call on that object inside the loop. Withblocks: Consecutive member accesses on the same object expression are converted toWith.- String concatenation:
s += ...inside a loop is automatically converted to the runtime's string buffer (a scheme that reserves space withSpace$and writes into it withMid$) (-O2). - Functions with
$:Left,Mid,Trim, etc. are emitted as the$versions that return aStringtype (Left$, etc.).
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)
- All RAS arrays are 0-based (§13.3), and 2D arrays derived from a Range are no exception. For both the automatic conversion (§9.1, §9.2) and the explicit API (§9.4), the subscripts visible to RAS code are 0-based
[row - first row][column - first column]. - Zero-copy rebasing: The array returned by
Range.Valueis 1-based. Copying the elements again would carry a non-negligible cost for large ranges, soRAS_Read2Ddoes not copy the array body; it directly rewrites theSAFEARRAYdescriptor'srgsabound[].lLboundto 0 (usingRtlMoveMemory. Obtaining theSAFEARRAY*inside aVariantand the 32-bit / 64-bit difference in offsets within the descriptor are emitted for both, following the rules in §11).- The rewrite is done only when
cLocks = 0,cDims = 2, and neitherFADF_STATICnorFADF_FIXEDSIZEis set infFeatures. When the conditions are not met, it falls back to copying the elements. - In the write direction no conversion is needed, because assigning to
Range.Valueaccepts a lower-bound-0 array as is.
- The rewrite is done only when
- Single row / single column: A one-column Range is also treated as a 2D array (
n × 1). When you want a 1D array, userange.toColumn()/range.toRow()(these involve a copy).
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).
- The target sheet expression is invariant within the loop (a
constvariable, a code name, or an object fixed outside the loop). - The subscripts are linear expressions of the induction variable (the forms
r + k,c - k, wherekis loop-invariant), and the rectangular region is statically determined from the loop range (before the loop starts). - The property accessed is one of
value/value2/formula/formulaR1C1, and the same property is used before and after the conversion (.Valueis never silently changed to.Value2, because dates and currency values would change). - 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). - For writes, every cell in the rectangle is written unconditionally (no conditional writes,
continue, orbreak). Bulk-writing partial writes would overwrite the formulas of the cells that are not written with values. - 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).
- There is no early exit by
break/return/ exception (for writes; reads may exit early).
9.4 Explicit control
- Attaching
@bulkto a loop converts it while ignoring, at the user's responsibility, some of conditions 4–6 (those that the side-effect analysis conservatively judged unacceptable). If condition 5 is not met, use the approach of first reading the existing contents with.Formulaand then writing them back. @nobulksuppresses the conversion.- Explicit APIs are also provided:
range.toArray(): any[][]— always a 0-based 2D array (§9.2.1)range.fromArray(arr)— resizes the Range to the array size and assigns in bulk (the array's lower bound does not matter)sheet.usedTable(): any[][]— fetches the used range in bulk
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)
- Arguments: All can be omitted, and an omitted side is 0 (not extended). Each takes an
intand can be passed either by named argument (up/down/left/right) or by position. A nonexistent argument name isE0412, and 5 or more arguments isE0402. - The original range: Not changed (a new
Rangeis returned). The number of rows and columns is counted on the first area (same asResize). - Out of bounds: If the result goes past the edge of the sheet or the number of rows or columns becomes 0 or less, it is run-time error 1004 (same as Excel's
Offset/Resize). It is not clipped at the edge. - Transpilation: Calls the runtime's
RAS_RangeExtend(rng, up, down, left, right)(rng.Offset(-up, -left).Resize(rng.Rows.Count + up + down, rng.Columns.Count + left + right)). The range expression is evaluated only once. - Editor: Completion, hover, and parameter info show the signature and a description of each argument, and the named-argument names (such as
up:) are completed.
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)
- Arguments: All four are
int(none can be omitted). Calls with 1 or 2 arguments work as before (range("A1"),range("A1", "B2")), and 3 arguments is an error (E0402). - Out of bounds: A number of 0 or less, or beyond the number of rows or columns of the sheet, is run-time error 1004 (same as
Cells). Even if top/bottom or left/right are reversed, the result is the range containing the two cells (same asRange(Cell1, Cell2)). - Transpilation: Emits
ws.Range(ws.Cells(top, left), ws.Cells(bottom, right)). The sheet expression is evaluated only once (if it is not a variable or code name, it is put in a temporary variable). - Editor: Hover and completion details show
range(top: int, left: int, bottom: int, right: int): Excel.Rangeas the other way to call it (parameter info is in §16.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
- Multiple areas: The bottom-right cell of the first area (counted on the first area, like
Rows.Count/Columns.Count). For a single cell, the cell itself. - Misuse: Calling it with
()(lastCell()) isE0382, and assigning to it isE0325. Properties of the returned cell can be assigned to (lastCell.value = 1). - Transpilation: Calls the runtime's
RAS_LastCell(rng)(rng.Cells(rng.Rows.Count, rng.Columns.Count)). The range expression is evaluated only once. - Editor: Shown as a property in completion and hover.
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
- Cells searched: Cells that have a value (for a sheet, its used range; for a range, the used range within it). A merged cell is found only once, as its top-left cell (because the cells other than the top-left one have empty values). Cells with error values are not found. A range made of multiple areas is searched in area order.
what: A string is compared with the cell's text (for a number or date cell, both the value converted to text ("1200") and the displayed text ("1,200")). A regular expression (VBScript.RegExp, §2.8) is applied to the cell's text. A number or date is compared by value (CDbl), and a boolean with the value of a boolean cell.match:"whole"(default; the whole cell) or"partial"(part of the cell). Any other string is an exception.strict: Withfalse(default), strings are compared after converting full-width to half-width, upper case to lower case, and removing whitespace (full-width spaces, tabs, line breaks) (StrConv(…, vbNarrow); katakana also becomes half-width). A regular expression is applied to the original text, and if it does not match, also to the text with full-width converted to half-width. Withtrue, they are compared as is.visibleOnly: Iftrue, cells whose row or column is hidden (including rows hidden by a filter) are excluded. The default isfalse.order:"rows"(default; row by row, from the left) or"columns"(column by column, from the top).findByHeaders(column, row): In the range (sheet), searches for the headingcolumnin row-by-row order and the headingrowin column-by-column order, and returns the cell where the column ofcolumnand the row ofrowintersect.nullif either is missing.findon a Range: Because Excel hasRange.Find, searching within a range is done withfindAll(the first one isfindAll(…)[0], or Excel'sfind).
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
- How it counts: A merged cell is counted as one cell (if
A1:B1is merged, one column to the right of A1 is C1), and if the cell reached is a merged cell, its top-left cell is returned. Passing through a merged cell keeps the column (row) moved along (down from column B through mergedA2:B2to B3, not to column A of the merged cell's top-left; one row down from G1 ofF1:G1is G2). WithvisibleOnly(defaulttrue), hidden rows and columns are skipped without being counted. UnlikeOffset/Resize, this lets you move as things look on screen even in forms with merged cells and hidden rows and columns. stepOffset(rows, columns): Moves one step at a time, columns first and then rows. If the range has multiple cells, the result is the range combining each moved cell (Union). Going outside the sheet is run-time error 1004.stepResize(rows, columns): The range combining the cells reached by movingcolumnscells to the right androwscells down from the range's top-left cell (or the top-left of it, if merged). Skipped rows and columns are not included (the result becomes multiple areas). WithwithinBorders, it extends only while the border frame continues: for cells to the right, while the top and bottom borders are the same as the first cell's and the left border is the same as the first cell's right border; for rows below, while the top border is the same as the first cell's bottom border and the left-edge and right-edge borders are the same as the first row's (color, line style, and weight are compared).
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 ""
- Cells counted: Cells that have a value or formula (
Find("*", LookIn:=xlFormulas, SearchDirection:=xlPrevious); formulas that result in""are also counted). UnlikeEnd(xlUp), hidden rows and rows hidden by a filter are also counted, and a column with nothing returns 0 (not 1). A merged cell with a value is counted up to the last row (column) of the merge. Cells with formatting only are not counted. skipBlank: Does not count cells whose value is empty or only whitespace (including full-width spaces) (including formulas that result in"").- Range: Counted within the used range inside the range. A sheet's
lastRow()isusedRange.lastRow().
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"]);
- The table: The heading row runs from this cell (the top-left cell, for a range) to the right, up to just before the first empty cell. The data runs from the row below the headings to the last row (
lastRow) of the table's columns. If there is no table, an array with 0 rows. pick: The columns to read (write) and their order. A heading string (likefindwithstrict: false, it ignores differences between full-width and half-width, upper and lower case, and whitespace), a regular expression, a position from the left edge of the table (int; from 0), ornull(an empty column when reading, skipped when writing). A heading that is not found is an exception (the message lists the table's headings). If omitted, all the table's columns.untilBlank: Treats a row in which all the table's columns are empty as the end of the table, and does not read what is below it (totals, notes).writeTable(values, pick): Writes columnjofvaluesto the columnpick[j], starting immediately below the heading (one write per column). Ifpickis omitted,valuesis written as is from the left edge of the table (fromArray).valuesis a typed 2D array (T[][]).
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
book.sheet(name): A string is the worksheet with the same name. If there is none, compares ignoring differences between full-width and half-width, upper and lower case, and whitespace, and if exactly one matches, that sheet. A regular expression is applied to the name (and to the name converted from full-width to half-width), and the first matching sheet is returned.nullif none. Chart sheets are not targeted.book.copySheet(sheet, name, before, after): Copies withWorksheet.Copyand returns the copied sheet (notActiveSheet, but the sheet at the position where it was placed). Ifbefore/afterare omitted, the copy goes right after the source sheet for the same workbook, or at the end for another workbook. Whennamecannot be set (a sheet with the same name exists, or it contains unusable characters), the copied sheet is deleted without confirmation and that error is thrown.workbooks.opened(path): Among the open workbooks, the one whose name (Workbook.Name) is the same as the last part ofpath(case-insensitive). Because Excel cannot open two workbooks with the same name, it is determined by name.workbooks.ensureOpen(path, readOnly, updateLinks): Returnsopened(path)if there is one, otherwise the workbook opened withworkbooks.open(path, updateLinks:, readOnly:)(an exception ifpathis empty).
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
- Nesting support: A depth counter is kept for each item. The original state is saved and the item is stopped only when the depth goes 0→1, and the saved state is restored only when it goes 1→0. Even if a function that uses
fastModecalls another function that usesfastMode, screen updating is not resumed when the inner one ends. - Saves and restores the original state: It does not always restore to
True/xlCalculationAutomatic; it restores to the value before stopping. - Avoiding the calculation-mode trap: Setting
Application.Calculationwhile no workbook is open causes an error, so the runtime guards against it. - Guaranteed restoration on error:
usingalways restores viafinally. In addition, the top-level handler at the macro entry (§12.3) resets all counters to 0 and restores the state, so an uncaught error cannot leaveEnableEvents = Falsebehind.
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.
while/do-while/ an infinite loop (for (;;))- A
for/for-ofwhose iteration count is not determined until run time - A
forwhose iteration count is known at compile time and is at or above the threshold (default 10,000) - A loop whose body contains a COM call, file I/O, or a call to a function that contains a loop
Handling of nested loops:
- In principle it goes in the innermost target loop.
- However, if the innermost loop's iteration count is a small constant (such as
for (let c = 0; c < 5; c++)), it goes in the next loop out. - Only one place is used per nest of 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.
- Counter check (expanded inside the loop): A check consisting only of one addition and a bit operation. The call to
RAS_Yieldis limited to once every N iterations. - Time / input check (inside
RAS_Yield):DoEventsis called only when a certain time (default 100ms) has passed since the previousDoEvents, or whenGetInputState()reports pending input (mouse or keyboard).RAS_Yieldlooks 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
GetTickCountreturns aLong, so subtracting directly would overflow (error 6) at wraparound. The runtime converts it todoubleand corrects for the wraparound.- The
Declares ofGetInputState/GetTickCountare emitted for both 32-bit / 64-bit following the rules in §11.
10.4.3 Where it is not inserted
- Worksheet functions (UDFs,
@udf) and functions that can be called from them: CallingDoEventsduring cell calculation causes recalculation inconsistencies or abnormal termination. This is determined with the call graph. - Event handlers (
@on) and functions that can be called from them: To prevent reentry during event processing. It is inserted if@doeventsis attached. @init, and a class'sClass_Terminate- Loops converted to the bulk transfer of §9: After conversion they consist only of array operations and are often fast enough. If the iteration count is at or above the threshold, it is inserted following the rules of §10.4.1.
10.4.4 Explicit control
@nodoevents: Attach to a function or loop to suppress insertion.@doevents: Attach to a function or loop to force insertion.yieldNow(): CallsRAS_Yieldright there.- The
[doevents]section ofras.tomlsets whether it is enabled overall, the interval, and the count threshold (§15.2). - The LSP shows the inserted places with CodeLens.
10.4.5 Reentry and interruption during DoEvents
During DoEvents, user operations and events are processed, so the runtime automatically takes the following measures.
- Preventing macro reentry: A running flag
RAS_Busyis kept. If another macro entry (§12.4) is called from a button or the ribbon while running, it is not executed, and "Busy" is shown (処理中です on Japanese projects) in the status bar. Macros marked@reentrantare excluded. - Events: If events are stopped by
eventsoffastMode, no events occur. If they are not stopped, handlers of events that occur duringDoEventsrun as usual. However, reentry into a handler that is itself running is ignored by the reentry prevention of §12.2. - Interruption with the Esc key:
Application.EnableCancelKey = xlErrorHandleris set at the macro entry. If Esc is pressed duringDoEvents, it reaches the top-level handler as error 18, which restores the application state, shows "Cancelled by the user" (ユーザーにより中断されました on Japanese projects), and ends.using/finallyalso run on interruption. Interruption can be disabled with@nocancel. - Conflict with cell edit mode: If the user starts editing a cell during
DoEvents, later sheet operations may fail. SpecifyingfastMode({ interactive: false })(Application.Interactive = False) accepts no user input and only avoids redraw problems and "Not Responding".
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
- Declarations that contain
longare emitted only inside#If Win64 Then, and if called in a 32-bit environment they become a run-time error (or the alternative implementation specified with@fallback). The linter warns if one is called outside anif (Platform.is64bit)guard. - A
Dimof aptr-typed variable in user code also emitsLongPtr/Longseparately with#If VBA7when VBA6 compatibility is enabled. target.vba6 = falseinras.tomlomits the VBA6 output (default istrue).- For structures (
declare struct), the compiler takes the alignment difference on 64-bit into account and prepares both computations, at compile time, for things such asLenBthat depend on the pointer size. - Frequently used APIs (
Sleep,GetTickCount,CopyMemory, etc.) are provided by the standard library asimport { Sleep } from "win32";, and only the ones used are emitted.
12. Automatic boilerplate generation
12.1 Common to all modules
The following is added to every module automatically. Users do not write it.
Attribute VB_Name = "..."(generated from the file name)Option ExplicitOption Compare Binary(explicit, so comparison behavior does not depend on the module)Option Private Module(for modules that have neither@macronorexport; keeps the macro list clean)- Attributes such as a class's
VB_PredeclaredId(generated from decorators such as@predeclared)
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 |
- A file's code is written only to its corresponding module. Code written in one file is never written into another file's module.
- A module's code is generated only from its corresponding file. The whole module is generated from that file; RAS does not manage just part of the code in a workbook. The RAS-managed region of document modules has been abolished (§14.6). The only exception is boilerplate code that the compiler adds (the initialization call added to
ThisWorkbook(§12.3), and a form'sRAS_FormInit(§14.11.5)). - Module name: Determined from the file name (without directory and extension). The first character, and the character after each
_/-/./ space, is capitalized, and these separators are removed (report.ras→Report,mod_util.ras→ModUtil). A name that starts with a digit getsModprepended, and names are limited to 31 characters. A name that equals a VBA reserved word gets a trailing_. If the file declares a class with the same name (class EquipmentinEquipment.ras), the class module takes that name, so the standard module gets a trailing_(Equipment_). Files inobjects/keep their names: the file name (without extension) is the sheet's code name as is (ThisWorkbook). If a name determined this way collides, ignoring case, with the name of another file, sheet or form, it is an error (src/Sheet1.rasis an error because it collides with the sheet whose code name isSheet1; write the sheet's code inobjects/Sheet1.ras). - Modules without a file: The following modules are generated by the compiler and have no corresponding
.rasfile.- A class module (
<class name>.cls) for eachclassdeclaration. One file can contain several classes. For generics, one per type argument (§2.4) RAS_StructMap__…(§2.5.6),RAS_Lambda_…(§4.1),RAS_On_…andRAS_Events(§12.2.3),RAS_Runtime(§7.5)
- A class module (
- Names of interface members: A class that
implementsan interface emitsPrivate Function <interface>_<member>for each interface member. VBA cannot implement a member whose name contains_(in real Excel this gives the compile error "Object module needs to implement '…' for interface '…'"), so it is an error (E0342) toimplementsan interface that has a member containing_, or a member whose name equals a VBA reserved word and so gets a trailing_(print→print_). A_in the interface's own name is fine. - Sync and
ras packconvert workbook code that has no place in this correspondence (hand-written standard modules, hand-written code in sheet modules, and so on) into RAS files and import it, keeping the correspondence (§14.7.1).
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
}
- What can be referenced: Only what the module
exports (including variables and constants such asMain.hits, enums and classes). Things that are not exported cannot be referenced. - Name: Written with the same spelling as the VBA module name (
main.rasisMain,mod_util.rasisModUtil,util/b.rasisB). RAS is case-sensitive, so you cannot writemain.hoge(). - Precedence: Names declared or imported in the file take precedence over module names (aliases such as
import * as U from "src/util"can also be used). A module whose name is the same as an Excel / VBA global refers to the global. When a local variable in a function would be the same as a module name in VBA, which is case-insensitive (mainandMain), the local variable is renamed in the VBA output (main_2). - Mutual references: Modules may reference each other (this also holds for mutual references via
import). - Unqualified calls and extension methods: An unqualified
hoge()and that module's extension methods (§3.2) are available only when youimportthem. The module name alone does not bring that module's extension methods into scope (so that you can tell which extension methods are called from the file'simports). - The forms in
forms/, sheet code names, andthisWorkbookare global to begin with (§12.2, §14.11). Files intest/(§14.12) do not become workbook modules, so they cannot be referenced by module name (test files can referencesrc/modules by module name).
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
- A path containing
/refers to a project file, and a name without/("validation","win32") refers to a module of the RAS standard library. When a pathless name such as"main"is the name of asrc/file, theE0121message shows"src/main". - Files that can be
imported: Files insrc/. Test-side files (§14.12) can beimported only from the test side (E0701). Sheet andThisWorkbookfiles (objects/) cannot beimported, and form files (forms/) can beimported only from tests (E0124; both can be used by name from anywhere:Sheet1.clearInput(),frmInput.show()). - Relative paths (deprecated): A path starting with
.//../is still read as relative to the file and works, but gives warningW0121.ras check --fixand the editor's quick fix rewrite it to a path from the project folder ("../src/main"inobjects/Sheet1.ras→"src/main"). The earlier resolution that treatedobjects//forms/files as if they were insrc/("../main") is likewise read through with a warning. importthat brings in no names:import "validation";(import {} from "validation") brings in no names and so does nothing (a RAS module has no code that runs onimport; there is nothing equivalent to TypeScript's side-effectimport). It is treated as a forgotten part and gives warningW0122, which shows the formsimport * as validation from "validation"/import { … } from "validation". For asrc/module, it shows that the module can be called by module name withoutimport(§12.1.2).- The
imports written by the editor's completion (§16.2.7), test generation (§14.12.10) and conversion from VBA (§14.7.1) also use this path form.
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 sheetin §14.16 are implemented. The VBA generated foronin §12.2.3 (the listener class,off(), the name set inOnAction, cancelling by returningfalse),ras sheetagainst 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) { ... }
Target files: A file directly under
objects/becomes the module of the worksheet whose code name is the file name (without extension) (case-insensitive).ThisWorkbook.rasbecomes the workbook module. You cannot create subdirectories inobjects/.- The code name is the name shown in the VBE project (such as
Sheet1), not the name on the sheet tab. A file for which the workbook ofproject.workbookinras.tomlhas no worksheet with that code name is an error (E0610). When you change a sheet's code name, change the file name too (ras sheet renamechanges both together; §14.16). While the workbook is open in Excel and sync is connected, the check is made against the sheets of the open workbook instead of the saved file (a sheet just added in Excel is not in the file until saved). - In a project that does not specify a workbook, the existence of a file in
objects/is taken to mean that a sheet with that name exists (nodeclare const Sheet1: Excel.Worksheet;is needed intypes/). ThisWorkbook.rascorresponds to the workbook module even if the workbook's code name has been changed in the VBE.- Chart sheets are not supported.
- The code name is the name shown in the VBE project (such as
this: Inside functions,thisrepresents that sheet (inThisWorkbook.ras, the workbook) (VBA'sMe). Its type isExcel.Worksheet(Excel.Workbook) plus theexport functions of that file. Unlike a VBA sheet module, an unqualifiedrange(...)/cells(...)does not refer to that sheet (a warning, as in other files; §13.4). Writethis.range(...)for the cells of that sheet.Events: In a sheet file, a function marked
@on("Worksheet.<event>"), and inThisWorkbook.rasa function marked@on("Workbook.<event>"), receives the event. The compiler generates in that module an event procedure with the same declaration as the VBE's (such asPrivate Sub Worksheet_Change(ByVal Target As Range)) and calls the handler from it.- You can write several handlers for the same event (called in declaration order).
- Event handlers automatically prevent re-entry (events that the handler itself fires while it runs are ignored). Use
@on("...", { reentrant: true })to turn this off. Errors not caught by the handler are shown in RAS's error dialog. - Handler arguments receive the event's arguments in order from the first, and can be omitted. To rewrite a
ByRefargument such asCancel, declare it asbyref cancel: boolean. Each argument's type must be one the event's argument can be given to (as withon:Integerisshort,RangeisExcel.Range); abyrefone must be of the event argument's type (orany, andobjectfor an object). VBA cannot compile a declaration that does not fit (aByRefargument type mismatch, for example), so it is an error (E0301). @oncan be written only in the file of the thing that raises the event. The following are errors (E0610):@onon a function in asrc/file,@on("Workbook.…")written in a sheet file, and@on("Worksheet.…")written inThisWorkbook.ras. The pre-v0.9@on("Sheet1.Change")(the form that writes the code name) is alsoE0610, and the message tells you to move it to@on("Worksheet.Change")inobjects/Sheet1.ras.- Other errors are shared with forms: a nonexistent event (
E0611), too many arguments (E0612), an argument of a type that does not fit (E0301), and a function name equal to the generated event procedure name (Worksheet_Change) (E0614). - Events of ActiveX controls on a sheet are received with
@on("<control name>.<event>")(§12.2.1), and events received withWithEventswith@on("<variable name>.<event>")(§12.2.2). - With
@on, which event is received is decided at compile time. When it must be decided at run time (attaching the same handling to many controls, attaching and detaching depending on conditions), useon/addEventListener(§12.2.3).
Variables: Top-level
let/constbecome variables and constants (Private) of that module. Their initial values are set at the same point as variables of a standard module. Aconstwritten with literals and previously declared constants, using integer addition, subtraction and multiplication and string concatenation (const first = header + 1), becomes a VBAConstand can be used without waiting for initialization (the same as constants in standard modules).Visibility: An
export functionbecomes aPublicmember of that sheet (workbook) and is called from other modules asSheet1.clearInput()/thisWorkbook.refresh()(the same as aPublicprocedure in a VBA sheet module). A sheet's code name andthisWorkbookare globals that can be referenced from anywhere, so noimportis needed (a sheet orThisWorkbookfile cannot beimported). To use asrc/module from this file, either qualify it with the module name (Main.hoge(); §12.1.2) orimportit (import { hoge } from "src/main"; §12.1.3). A function that is notexported isPrivate.- An
export functionthat can be called with no arguments, and a function marked@macro, become macro entry points just as in standard modules (wrapped as in §12.4). From Excel they are called by the nameSheet1.clearInput(for example when assigned to a button).
- An
Things that cannot be written (
E0650): Things that VBA cannot put in a document module, and things that work only in a standard module, are errors. Put what you want to share in asrc/standard module and use it viaimport.Cannot be written Reason exported variables and constants (export let/export const)VBA cannot put a Public Const, or aPublicarray, fixed-length string or struct variable, in an object module. Variables are treated as something that cannot be published wholesale; publish them through functionsexported enums and type aliases, structs (struct), classes and interfacesVBA cannot put a Public Typein an object module. Other files cannotimportthis file, so they cannot reference the typesdeclare module(declaring DLL functions)A Public Declarecallable from other modules cannot be put in an object moduleTop-level statements Main(§12.4) belongs to the standard module@udfExcel can call from a cell formula only functions in standard modules @ribbonRibbon callbacks are not called unless they are in a standard module @init, extension methodsThey are used project-wide, so put them in a standard module Same name as a sheet (workbook) member (
E0651): You cannot declare a function or variable with the same name (case-insensitive) as a member the sheet (workbook) has (name,range,activate,calculate, etc.; this includes the names of controls on the sheet (§12.2.1)). Otherwise it would be undecided which oneSheet1.nameorthis.namerefers to.Top of the module: As in other modules,
' RAS-GENERATED hash=<CRC32>(§14.7),Option ExplicitandOption Compare Binaryare emitted.Option Private Modulecannot be written in an object module, so it is not emitted.Files with no code: A file with only comments (as left when created in §14.7.2) and a sheet with no file are treated as "modules with no code" (§12.1).
In debug runs (§14.10) and tests (§14.12) too,
thisrepresents that sheet (workbook). A debug run without Excel calls handlers in response to the program's operations (§14.10.8).
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();
}
- List of controls: The compiler reads the name and kind (ProgID) of each sheet's controls from the workbook file given by
project.workbookinras.toml. A control added in Excel becomes usable once you save the workbook. - Inserting controls: Besides Excel, you can also place Microsoft Forms 2.0 controls (command button, combo box, check box, list box, text box, scroll bar, spin button, option button, label, toggle button) on a sheet from "ActiveX Controls" under "Insert" in the Developer ribbon of the sheet preview (§14.14) (
activeXofras book edit). Names are like Excel's, such asCommandButton1. If you place one in the project's workbook, you can immediately write@on("CommandButton1.Click")in the sheet's file, and add an event handler from "View Code" on the right-click menu or the Shape Format tab. - Reference: A control is referenced as
this.<control name>. From other modules,Sheet1.<control name>. Write the name exactly as it is in the workbook; it is emitted as is (§15.3.1). The type is the same as for forms, such asMSForms.CommandButton, for Microsoft Forms 2.0 controls (those with a ProgID such asForms.CommandButton.1) (§14.11.2), andobjectfor other controls. A control that is not on the sheet is an error (E0202). - Events: A function marked
@on("<control name>.<event>")receives the event. The compiler generates in that sheet's module an event procedure with the same argument declarations as the VBE's, named with the event name starting in lowercase to match RAS naming (Private Sub CommandButton1_click(),TextBox1_keyDown; VBA is case-insensitive), and calls the handler from it. Multiple handlers, re-entry prevention, error display and how arguments are received are the same as for sheet events (§12.2).- The usable events are the form control events (§14.11.2), excluding
Enter/Exit/BeforeUpdate/AfterUpdate, which the form raises, and addingGotFocus/LostFocus, which the sheet raises. - Errors: a control not on the sheet (
E0613), an event the control does not have (E0611), too many arguments (E0612), an argument of a type that does not fit (E0301), and a function name equal to the generated event procedure name (CommandButton1_click) (E0614). - Events of controls other than Microsoft Forms 2.0 (of unknown kind) are not checked. Write the handler's arguments exactly as in the event procedure declaration the VBE would create (including
byref). The event procedure is generated with that argument declaration. - In a project that does not specify a workbook there is no list of controls, so if the
<name>in@on("<name>.<event>")is neitherWorksheetnor a variable (§12.2.2), it is treated as a control, the same as "of unknown kind" above. Declarethis.<control name>intypes/.
- The usable events are the form control events (§14.11.2), excluding
- Form controls and shapes: Buttons and shapes that are not ActiveX call a registered macro (
OnAction) instead of raising an event. In the sheet's file, a function marked@on("<shape name>.Click")is called from that macro (you may also register anexport functiondirectly (§12.2, §12.4)).// objects/Sheet1.ras @on("Button 1.Click") function button1Click() { this.range("A1").value = now(); }- The compiler generates in that sheet's module a
Public Subnamed after the name Excel gives a new macro (the name's letters, digits and_, plus_click;Button 1→Button1_click; if it does not start with a letter,Shapeis prepended;_clickstarts in lowercase to match RAS naming), and calls the handler from it. Multiple handlers, re-entry prevention and error display are the same as for sheet events. This macro (Sheet1.Button1_click) is what gets registered on the shape (adding an event in the sheet preview registers it). - If the name is not an ActiveX control of the sheet and the event is
Click, it is treated as a shape (the list of shapes is not read from the workbook). List and combo boxes (selection) and spin buttons and scroll bars (change) are alsoClick. A name that is not a valid VBA name (Button 1) is treated as a shape even in a project that does not specify a workbook. The handler receives no arguments (E0612).
- The compiler generates in that sheet's module a
- Debug runs: In a debug run connected to Excel (§14.10.3),
this.<control name>operates the actual control. Events raised by Excel cannot be received (§14.10.5). In a debug run without Excel (§14.10.8) and in tests, controls cannot be used (referencing one gives error 438; it is subject to the warning in §14.15).
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); }
}
- Where it can be written: VBA can place
WithEventsonly in object modules, so it is limited to the following variables.- Top-level variables in sheet and
ThisWorkbookfiles (§12.2) and in a form's code-behind (§14.11.2) - Class fields (attach the handler to a method of that class)
- It cannot be written on top-level variables of
src/files (variables of a standard module) or on variables inside functions (E0610; the message tells you to move it to a class or anobjects/file).
- Top-level variables in sheet and
- Conditions on the variable (
E0615): These follow the restrictions of VBA'sWithEvents.- Write exactly one type, a class type that has events (
Excel.Application,Excel.Workbook,Excel.Worksheet,Excel.Chart,Excel.QueryTable, and controls such asMSForms.CommandButton).object,any, union types, arrays andMapare not allowed. Types emitted with late binding (Scripting,VBScript, and types generated byras typegen; §15.3) are not allowed either (in VBA they becomeObjectand cannot receive events). constis not allowed (because receiving starts by assignment).exportis not allowed.- For RAS classes, only classes that declare an
event(see "Class events" below) are eligible. Generic classes are not allowed.
- Write exactly one type, a class type that has events (
- Output: The variable is declared as
Private WithEvents app As Excel.Application, and for each handler an event procedure with the same declaration as the VBE's (Private Sub app_SheetChange(ByVal Sh As Object, ByVal Target As Range)) is generated and the handler is called from it. A variable named in@onis excluded from renaming (§13.6). - List of events: The compiler has the events (names and arguments) of
Excel.Application,Excel.Workbook,Excel.Worksheet,Excel.Chart,Excel.QueryTableand Microsoft Forms controls. For Microsoft Forms controls,Enter/Exit/BeforeUpdate/AfterUpdate, which the form raises, cannot be received. Events of other classes (such asOfficeclasses) are not checked; write the handler's arguments exactly as in the event procedure declaration the VBE would create (the same as "of unknown kind" in §12.2.1). - Multiple handlers, re-entry prevention, error display and how arguments are received are the same as for sheet events (§12.2). Errors: neither a variable nor a control with that name (
E0613), an event the type does not have (E0611), too many arguments (E0612), an argument of a type that does not fit (E0301), and a function name equal to the generated event procedure name (app_SheetChange) (E0614). - Name collisions: The
<name>in@on("<name>.<event>")is looked up in this order:Worksheet/Workbook/UserForm(the sheet, workbook or form of that file), control names, variable names. You cannot declare a variable with the same name as any of these (E0651). - Debug runs: In a debug run connected to Excel, events raised by Excel cannot be received (§14.10.5). In a debug run without Excel and in tests, when a variable (class field) refers to the project's workbook, its sheets or
Application, handlers are called for the events in the table in §14.10.8.- For a variable referring to a sheet, the sheet's events (
Change, etc.) are raised; for a variable referring to a workbook, the workbook's events (SheetChange,BeforeSave, etc.). - For a variable referring to
Application, the project workbook's events are raised. The workbook'sSheet…events are raised under the same name (SheetChange), and the workbook's own events under a name withWorkbookprepended, with the workbook as the first argument (BeforeSave→WorkbookBeforeSave(wb, saveAsUI, cancel)). - The calling order is the sheet and workbook handlers written in the files, followed by the variable handlers (in registration order). Assigning
nullto the variable stops them being called. Handlers of instances of classes that are no longer used are no longer called. - Handlers of variables that refer to controls (
MSForms) are not called.
- For a variable referring to a sheet, the sheet's events (
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; }
- Declaration: No body is written. A return value,
static, type parameters, optional arguments, rest arguments andprivate/protectedcannot be written (E0619).byrefarguments can be used by the handler to return values. - Raising: Besides
this.Rang(...), callingdoorBell.Rang(...)from outside the class also raises it. The handlers are called synchronously, once for each variable that holds that object at that moment. If there is no receiving variable, nothing happens. - Output: The class module gets
Public Event Rang(ByVal times As Long, ByRef heard As Long)and a procedure that raises the event,Public Sub RAS_Raise_Rang(…)(whose body isRaiseEvent Rang(…)). A call becomes a call toRAS_Raise_Rang. The receiving variable becomesPrivate WithEvents doorBell As Bell, and the event procedure's arguments follow the event's declaration. - Running without Excel:
ras run/ras testcall handlers by the same rules. - Importing VBA (§14.7.1):
Public Event …in a class module becomesevent …;, andRaiseEvent name(…)becomesthis.name(…). A class'sPrivate WithEvents x As …andx_eventprocedures become a field and a method with@on("x.event").
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();
}
Syntax:
<object>.on("<event>", <handler>).addEventListeneris an alias ofonand behaves the same.- The event name is written as a string literal (case-insensitive). A class is generated for each event, so a name decided at run time cannot be used (
E0616). - The handler is one of an arrow function, a variable of function type, or a function name (
btn.on("Click", ok);onhandlers are the only place where a function name can be written as a value). - For a host type whose type definitions have a member of the same name (
on/addEventListener), that member is used.
- The event name is written as a string literal (case-insensitive). A class is generated for each event, so a name decided at run time cannot be used (
Targets (objects that have events): Values of types that can be made
WithEventswith@on("<variable name>.<event>")(§12.2.2).- Controls such as
MSForms.CommandButton(controls of a form, ActiveX controls on a sheet (§12.2.1)),Excel.Application,Excel.Workbook,Excel.Worksheet,Excel.Chart,Excel.QueryTable.thisWorkbook, sheet code names (Sheet1), and thethisof sheet andThisWorkbookfiles are also targets. - The usable events are the same as the "List of events" in §12.2.2. For controls,
Enter/Exit/BeforeUpdate/AfterUpdate, which the form raises, andGotFocus/LostFocus, which the sheet raises, cannot be received (receive them with@on("<control name>.<event>")). A nonexistent event isE0611. - It can also be attached to
MSForms.Control(the elements ofthis.controls). The kind of control is decided at run time, so it attaches only to controls of kinds that have that event; for kinds that do not (such asChangeon aLabel) it does nothing and returnsnull. The usable events are those that some control has. The arguments the handler can receive are limited to the leading part common to all kinds that have the event (Clicktakes no arguments, since onlyMultiPage/TabStrippassindex). - The form's own events are received with
@on("UserForm.<event>"). It cannot be attached to classes whose events are unknown (Excel.Range,Officeclasses, etc.) (E0616).on(…)on anobjectoranyvalue is a late-bound call like other members, and attaches no event handler (write a type on the variable, or narrow withinstanceof).
- Controls such as
Targets (arrays and collections): Arrays of objects of the above types (
MSForms.TextBox[],Excel.Worksheet[],MSForms.Control[]) and host collections that have them as elements (this.controls,book.worksheets,ws.shapes). It is attached to all members (forMSForms.Controlmembers, only those that have the event).- The handler receives the member as its first argument, followed by the event's arguments (
this.controls.on("KeyDown", (c, keyCode, shift) => …)). Either can be omitted from the end. AnOnActionmacro receives no arguments. - There is no return value (
void). To detach individually, callonfor each member withfor...ofand keep the return values. Handlers attached in a form's code-behind are detached when the form closes. - It is attached to the members at the time of the call. Controls or sheets added later are not covered.
- The handler receives the member as its first argument, followed by the event's arguments (
Targets (objects that have
OnAction): Values of types that have anonActionproperty, such asExcel.Shape(shapes, Form Control buttons). The only event isClick, and the handler is written as the name of a function that can be a macro (anexport functionin asrc/orobjects/file with no arguments and no return value, or a function marked@macro; §12.4). Arrow functions, variables of function type and form functions cannot be written (E0617), because Excel stores the macro's name in the workbook. There is no return value (void). To detach it, assignonAction = "".Handler arguments: They receive the event's arguments in order from the first, and can be omitted (the same as
@on). The types of an arrow function's arguments are determined from the event's arguments (Integerisshort,RangeisExcel.Range,MSForms.ReturnBooleanstays as is). Too many arguments is an error (E0612).byrefarguments cannot be written.Cancelling: For events that receive
Cancel As BooleanasByRef(Excel events such asWorkbook.BeforeCloseandWorksheet.BeforeDoubleClick), the event is cancelled if the handler returnsfalse(Cancel = True; the same as jQuery). If it returns any value other thanfalse, or returns no value, nothing happens. For events that receiveMSForms.ReturnBoolean(such as a control'sDblClick), cancel withcancel.value = true, as with@on.Return value: A
RAS_Listenerrepresenting the attached handler.off()detaches it (it is not called afterwards; calling it any number of times is fine).How long it is called:
- Handlers attached in a form's code-behind (even if the target is not a control of that form) are detached when that form closes (
Terminate). The next time the form is loaded,Initializeis called again, so attach them again there. - Handlers attached anywhere else are called until you call
off()or the state of the VBA project is reset (just as variables vanish on a reset, the attached handlers vanish too). To receive events for as long as the workbook is open, attach them in a@on("Workbook.Open")handler or an@initfunction (§12.3). - Any number of handlers can be attached to the same event of the same object. Attaching the same handler twice calls it twice.
OnActionis saved in the workbook, so it remains after the workbook is reopened.
- Handlers attached in a form's code-behind (even if the target is not a control of that form) are detached when that form closes (
Order, re-entry, errors: In debug runs and tests, handlers attached with
onare called after the@onhandlers, in the order they were attached. In Excel, the order is decided by the object that raises the event (normally the order of connection, but not guaranteed). While a handler is running, the same event raised by that handler itself is ignored (per attached handler). Errors that are not caught are shown in RAS's error dialog, as with@on.Choosing between this and
@on: Write events of fixed controls of forms and sheets with@on(it is a declaration, so there is no forgetting to attach or detach, and no class is generated). Useonwhen the target or the event is decided at run time.Output: For each used pair of "class and event", one class module
RAS_On_<class>_<event>is generated (a name longer than 31 characters has its tail replaced with a hash). The handler is passed as an object of the same class as an escaping arrow function (§4.3) (RAS_Lambda_…, methodApply) (when a function name is written, a class that just calls that function is generated; the "slow because converted to a class" hintI0641is not emitted). The runtime (RAS_Listen) keeps the attached handlers alive in aCollection. Handlers attached in form code are detached byRAS_UnlistenOwner Mein theUserForm_Terminatethat the compiler adds.' init in forms/frmEdit.ras (excerpt) Set ras_t1 = New RAS_Lambda_001 Set ras_t1.Captured_Me = Me RAS_Listen New RAS_On_CommandButton_Click, Me.btnOK, ras_t1, 0&, Me' RAS_On_CommandButton_Click.cls Private WithEvents ras_target As MSForms.CommandButton Private ras_handler As Object Private ras_argc As Long Private ras_busy As Boolean Public RAS_Owner As Object Public Sub RAS_Bind(ByVal target As Object, ByVal handler As Object, ByVal argc As Long, ByVal owner As Object) Set ras_target = target Set ras_handler = handler ras_argc = argc Set RAS_Owner = owner End Sub Public Sub Off() Set ras_target = Nothing Set ras_handler = Nothing Set RAS_Owner = Nothing RAS_Unlisten Me End Sub Private Sub ras_target_Click() If ras_busy Or ras_handler Is Nothing Then Exit Sub On Error GoTo RAS_OnError ras_busy = True ras_handler.Apply ras_busy = False Exit Sub RAS_OnError: ras_busy = False RAS_EventError "CommandButton.Click", Err.Number, Err.Source, Err.Description End SubWhen handlers that take different numbers of arguments exist for the same "class and event", the event procedure dispatches among them with
Select Case ras_argc.For events that receive
CancelasByRef, the call isIf RAS_Cancels(ras_handler.Apply(…)) Then Cancel = True.For
MSForms.Controland arrays and collections, the target class is decided at run time. For each event,RAS_OnAny_<event>, which chooses the listener class byTypeName, andRAS_OnEach_<event>, which enumerates the members and calls it, are generated in the standard moduleRAS_Events(TypeOf … Isis not used:CheckBox,OptionButtonandToggleButtonshare an interface and cannot be told apart). Handlers that receive the member are distinguished by adding 256 toras_argc, and are called likeras_handler.Apply ras_target, KeyCode.' form: RAS_OnEach_KeyDown Me.Controls, ras_t1, 257&, Me Public Function RAS_OnAny_KeyDown(ByVal target As Object, ByVal handler As Object, ByVal argc As Long, ByVal owner As Object) As Object Select Case TypeName(target) Case "CheckBox" Set RAS_OnAny_KeyDown = RAS_Listen(New RAS_On_CheckBox_KeyDown, target, handler, argc, owner) Case "ComboBox" … End Select End Function Public Sub RAS_OnEach_KeyDown(ByRef targets As Variant, ByVal handler As Object, ByVal argc As Long, ByVal owner As Object) Dim t As Variant If IsArray(targets) Then If RAS_Len(targets) = 0& Then Exit Sub End If For Each t In targets RAS_OnAny_KeyDown t, handler, argc, owner Next t End SubOnActionis emitted asshape.OnAction = RAS_MacroName("Report.reload")(for arrays and collections,RAS_OnActionEach shapes, RAS_MacroName(…)).RAS_MacroNamereturns a name with the workbook name attached ('Book.xlsm'!Report.reload) so that it can be called whichever workbook is active.
Debug runs and tests: In a form's debug run (§14.10.7), handlers attached to the form's controls are called on the same triggers as
@onhandlers. In a debug run without Excel (§14.10.8) and in tests, handlers attached to the project's workbook, its sheets andApplicationare called by the same rules as the variable handlers in §12.2.2. In a debug run connected to Excel, events raised by Excel cannot be received (§14.10.5).OnActionis set to a name without the workbook name (Report.reload).
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:
- Environment and timing differences when the workbook is opened with macros disabled or in Protected View and the user later presses "Enable Content" / "Enable Editing" (for example, the window is not ready so
ActiveWindowand the like cannot be used) Application.EnableEvents = Falseis left over because of an error in another macro- The workbook was opened while holding Shift, or opened with
Workbooks.Openfrom another workbook's VBA (Auto_Openis not called) - A state reset from editing code in the VBE, an uncaught error, or
Endcleared global variables (such as the ribbon'sIRibbonUIreference)
RAS calls RAS_EnsureInit from all of the following paths, and limits it to once with an initialized flag.
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 nextWorkbook_Activate/Workbook_WindowActivate. This is becauseWorkbook_Openat that moment occurs before the Protected View workbook closes, and object model calls (such asRange.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 withApplication.ProtectedViewWindows). Deferring withApplication.OnTimeis 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 closingAuto_OpenWorkbook_Activate/Workbook_WindowActivate(the handlers deferred in 1 are also called here)- The beginning of every macro entry point (
@macro/ argument-lessexported Subs, button and ribbon callbacks) - The ribbon's
onLoadcallback
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).
- A
RAS_EnsureInitcall - Re-entry prevention (
RAS_Busy, §10.4.5) and settingApplication.EnableCancelKey = xlErrorHandler - A top-level error handler: restores application state (§10.2), then shows an error dialog with the RAS source location (suppressed with
@silent, replaced with@onError(handler))
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
Diminside a loop is not reinitialized: VBA'sDimis initialized only once per procedure. RAS hoists all declarations to the top of the procedure and explicitly assigns an initial value (0,"",Nothing,Erase, etc.) at the declaration position in the RAS source.- In
Dim a, b As Long,abecomesVariant: One variable per line is emitted. - Auto-instantiation with
Dim x As New Foo: Not used.new Foo()is always converted toSet x = New Foo. - Block scope: If RAS block-scoped variables have duplicate names, they are renamed on output (
x,x_2).
13.2 Operations and evaluation
And/Ordo not short-circuit:&&/||are converted to nestedIfs and temporary variables.IIfevaluates both sides: The ternary operator is converted to anIfstatement, andIIfis not used.- Type of integer literals: VBA regards small integer literals as
Integer, so300 * 200overflows. Type suffixes are always added to numeric literals (§2.2). Operations betweenshorts are promoted toint(§2.3). True = -1: Converting a boolean to a number, such asb as int, is converted to-CLng(b)so that it gives1/0(the same value as C#'sb ? 1 : 0).Modrounds real numbers before computing:%becomesModif the operands are integer types, and otherwise the runtimeRAS_FMod(§2.3).Rounduses banker's rounding:Math.roundis converted to a runtime function that rounds half away from zero (equivalent toMidpointRounding.AwayFromZero).Math.bankersRoundlets you choose VBA-compatible (round half to even) rounding./and\:/between integers is converted to\, otherwise to/(§2.3). VBA's\rounds real operands with banker's rounding before dividing, so integer division involving reals is not emitted.==/===:Isfor objects,=otherwise. Comparison withnull/undefinedisIs Nothingfor object types, andRAS_IsNullishforany(which testsIsEmpty,IsNullandIs Nothing).- Implicit calls of default members: When
rngis used as a value,.Valueis explicitly emitted.
13.3 Strings, arrays and collections
- Strings are 0-based in RAS:
s.substring(i, j),s[i]ands.indexOf(x)are automatically adjusted to the 1-basedMid$andInStr. - Arrays are always 0-based: So as not to depend on
Option Base, array creation always states the lower bound explicitly (ReDim a(0 To n - 1)). The exceptions are only arrays held inanyso that they can be handled with the same subscripts as hand-written VBA (arrays created withredim(a, 1, n), and the multi-cellrange.value), whose subscripts stay as in VBA (§4.6). UBoundon an empty array is an error:arr.lengthis converted to the runtimeRAS_Len(which returns 0 even for unallocated orErased arrays). A length-0 guard is added when convertingFor.ReDim Preserveis O(n²):pushinside a loop is converted to a capacity-doubling scheme (it keeps a private capacity variable and trims to the real size after the loop).Collectionis 1-based: The RASCollectionwrapper is 0-based and adjusts subscripts.Scripting.Dictionary: Created with late binding (CreateObject) so it does not depend on a reference setting. Provided as theMap<K, V>type.WorksheetFunction.Matchand the like raise a run-time error when nothing is found: RAS'sExcel.match()and the like useApplication.Matchand return error values converted tonull.- Comparing cell error values raises a run-time error: If you compare an error value such as
#N/A(aVariantofvbError) with=or<, or perform arithmetic or type conversion on it, VBA raises run-time error 13 (Type mismatch). It occurs only when the value is an error value, so it is hard to find in tests. RAS represents such values with the typecellValue, and warns about places that use one without checking (W0313, §2.6.6).Excel.errorToNull(v)(runtimeRAS_ErrorToNull) returns an error value asnull(Empty) and returns other values as they are. For an array (including 2D arrays and arrays of arrays), it returns a copy with error-value elements set tonull(Excel.errorToNull(ws.range("A1:C9").toArray())). For assignment to a variable (const rows = Excel.errorToNull(...),x = Excel.errorToNull(...)), it rewrites the copy made by the assignment in place (RAS_ErrorToNullInPlace rowsafterrows = RAS_Read2D(...)), so no extra array copy is made. Add a default with??(Excel.errorToNull(v) ?? ""). The return type is the argument's type withcellValuereplaced byany(cellValue→any,cellValue[][]→any[][]).==on union types (RAS_UnionEq) treats error values as a different kind of value, and compares error values with each other by error number (§2.6.2). Range.Findcarries settings over: Thefind()wrapper explicitly specifies all arguments (LookAt,LookIn,MatchCase, etc.) every time.
13.4 References to sheets and Ranges
- Unqualified
cells/range: In VBA'sws.Range(Cells(1, 1), Cells(2, 2)), the innerCellsrefers to the ActiveSheet and causes an error. In RAS, unqualifiedcells/rangeinside the arguments ofws.range(...)are automatically qualified withws. Other unqualified uses give a warning. - References to sheets: Code names are recommended over name strings (
worksheets("Sheet1")), and code names are completed with types. The result ofworksheets(...)is treated asExcel.Worksheet(it isObjectin the type library; §4.4). - Inside a sheet file: In a VBA sheet module, an unqualified
Rangerefers to that sheet, but in RAS an unqualifiedrange/cellsgives a warning even insideobjects/Sheet1.ras; writethis.range(...)(§12.2). Importing hand-written VBA (§14.7.1) converts it withthis.added. - Partial matches of sheet names (
W0316): A place that looks for a sheet's name (thenameof aWorksheet/Chart, or a local variable initialized with it) with a string literal throughinStr/inStrRev,includes/indexOf/lastIndexOf/startsWith/endsWith, alikepattern that starts or ends with*, or a regular expression literal not enclosed in^…$(test/execute; also a local variable initialized with the literal) is warned about: it also matches another sheet whose name contains the same text ("Light control" for "Light"), and which one it takes depends on the order of the sheets. The message shows the comparison of the whole name (ws.name == "Light"). When the names of the workbook's sheets are known (theworkbookofras.tomlcould be read) and the pattern matches two or more sheets, it names them (for a regular expression, only one without special characters). No warnings are issued in test files. Range.findwithoutlookAt(W0317): WithoutlookAt, the search uses the setting of the last search (a partial match,xlPart, by default), so "Qty" also finds a cell "Qty unit". ARange.findwhose value is a string literal without*and which giveslookAtneither by name nor as the fourth argument is warned about. The message showslookAt: xlWhole, andws.find("…")(§9.4) to find a heading.
13.5 Control flow
- There is no
continue: Converted toGoTo RAS_Continue_N. break labelin nested loops:Exit Forcan leave only one level, so it is converted toGoTo.switchfall-through: Converted toSelect Case, andcases with fall-through are expressed withGoTo.casecomparison has===semantics.
13.6 Identifiers
- Case insensitivity: VBA does not distinguish case, and the VBE rewrites all modules to the case used at declaration (if you name a variable
Value, every.valueis rewritten, and so on). RAS makes identifiers that differ only in case an error. In addition, when a local variable name collides with a VBA built-in member name (Value,Name,Count,Item, etc.) or a global of the bundled type definitions (Range,Workbooks,Left, etc.), it is renamed automatically (value→value_,const range = ws.range("A1")→range_). - Spelling of host names: RAS source uses camelCase (
ws.cells), and the generated VBA uses the type library's spelling (ws.Cells) (§15.3.1). - Collisions with reserved words and built-in function names: Identifiers with the same name as
Date,Name,Type,Error,Len, etc. are renamed automatically. When a module's function or variable has the same name as a VBA function (Left,Trim,Format,Replace, etc.), a trailing_is added too (function left()→left_; the macro name also becomesleft_). Otherwise the VBA function would be hidden across the whole project, and a call such asLeft$(s, 1)would be a compile error. Class members are excluded. A module's function or variable whose name starts withRAS_also gets a trailing_(function RAS_Len()→RAS_Len_): with the same name as a public procedure of the runtime, every call of it would be an ambiguous-name compile error. - Collisions of public names: When several modules have
Publicfunctions with the same name, calls are always emitted qualified asmodule name.function name. - Names hiding a module: The
ModuleofModule.functionmeans a member, variable or parameter of the same name (case does not count) where it is written (Text.splitByin a class with a fieldtextissplitByoftext, a compile error). Then the function is written without the qualifier. When the function's name is hidden there too, or another module has the same name so it is not decided, it is an error (E0644). - Names specified as strings: Handler names generated for
Application.Run "name",OnTime, ribbon callbacks and@onare checked for existence, and excluded from renaming and inline removal.
13.7 Character encoding
- VBE code modules are saved in the system code page (CP932 on Japanese systems). Characters that cannot be represented in the code page turn into
?. RAS automatically converts unrepresentable characters in string literals to concatenations ofChrW(&H...), and unrepresentable characters in comments to\u{...}notation. Characters that CP932 stores as other ones (−U+2212 as-U+FF0D,〜U+301C as~U+FF5E,‖as∥,¢£¬as their full-width forms) are written as Excel reads them back (so that the drift check of §14.7 matches the stored code). - The output's target code page is specified by
target.codepageinras.toml(default932). - The
.bas/.clsfiles inbuild/are output in the target code page with CRLF. The VBE's "Import File" reads a file in the ANSI code page of the running Windows (GetACP()) and does not look at theVBA project's code page, so importing manually on a PC whose locale differs fromtarget.codepagegarbles the text. Also, a.clswith LF-only line endings is imported by the VBE as a standard module, not a class. Useras packinstead of manual import (offline writing explicitly specifies the project's code page, so this problem does not occur).
13.8 Structural limits of VBA
- 64 KB limit per procedure: The output size is estimated, and inline expansion is cut off if it would exceed the limit. If it still exceeds, it is an error.
- Limit of 24
_line continuations: Long expressions are split into temporary variables. - 1023-character limit per line: Long string literals are split into concatenations.
- Check of the generated VBA:
ras build(and every command that generates VBA:check,pack…) checks the generated modules under the conditions of 32-bit and 64-bit Office (VBA7true,Win64false and true;#If/#ElseIf/#Elseare resolved). It checks that the blocks (Sub/Function/Property,If,For,Do,While,Select Case,With,Type,Enum) match, that no name is declared twice in a module or a procedure (aProperty Getand itsLet/Setshare a name), that string literals and parentheses match on each line, that everyDeclareisPtrSafeon 64-bit, and the 1023 characters per line and 24 line continuations; a problem is a defect of the compiler and is reported as the errorE0904(at most 5 per module). The grammar of expressions itself is not checked. - Limit on local variables: Temporary variables added by hoisting and expansion are reused per type (those whose lifetimes do not overlap).
- Public array fields of classes: A VBA class module cannot make an array
Public, and a public field looks like a property from outside, so changes made throughobj.itemsare made to a copy (ReDim Preserve obj.items(…)is a compile error,obj.items(0) = 1changes nothing, and a field passed to abyrefargument is not written back). RAS keeps a public array field (any[]too) in a private variablef_<name>and generates the following properties:<name>for the whole array (Get / Let;Variant),RAS_<name>(i[, j])for an element (Get / Let / Set), andRAS_Len_<name>for the length. Usage from outside the class is emitted as follows (inside the class,f_<name>is used directly).- Reading and writing elements (
b.items[0] = 1,b.items[i]) and the length (b.items.length): the element and length properties (b.RAS_items(0) = 1&,b.RAS_Len_items). - Operations that change the array (the
ReDim Preserveofpush/pop, theEraseofclear()) and passing the array to a procedure (RAS_Sortofb.items.sort(),byrefarguments, typed array arguments): done on a local copy and written back at the end (t = b.items…b.items = t). As a result, callingpushfrom outside the class inside a loop takes time proportional to the number of elements every time. When adding many, add them with a class method (no copy is made inside a method). - Elements and public fields passed to a
byrefargument (inc(b.items[0]),inc(b.count)): passed in a local variable and written back after the call. - Anything else (
const xs = b.items,for (const x of b.items)): the whole-array property (a copy).
- Reading and writing elements (
14. Excel sync (live sync / offline writing)
14.1 Purpose and approach
- Even while Excel is running, a
.rassave is reflected in the target workbook's VBA project within a few hundred milliseconds. - The conventional "export to a file →
VBComponents.Import" approach is slow because of disk I/O and one COM call per module. Instead, we use bulk transfer through shared memory (a memory-mapped file), with an add-in inside Excel rewriting the code modules directly from the VBA side.
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.
ras watch(or the sync thread inside the LSP server): Detects changes, builds incrementally, and writes the diff to shared memory.- RASBridge.xlam: An Excel add-in installed by
ras setup(written and built with RAS itself). It reads shared memory, rewrites theVBProject, and writes the result back to shared memory. - Prerequisite: "Trust access to the VBA project object model" must be enabled.
ras setupsets it with the user's consent.
14.3 Connection
- Find the workbook given in the
workbookkey ofras.toml(full path) by enumerating the running Excel instances from the COM ROT (Running Object Table). Multiple instances are supported. - If it is found, create the shared memory
Local\RAS.<workspaceId>(workspaceIdis generated from the workbook's full path and a random session token) and callApplication.Run "RASBridge.xlam!RAS_Connect", <name>, <token>through COM. - If the workbook is not open:
ras watchwaits and connects when the workbook is opened (notified from RASBridge'sApplication.WorkbookOpenevent).ras packwrites 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
- The default size is 64 MB (changeable in
ras.toml). - The payload is UTF-16LE. On the VBA side it is copied with
OpenFileMappingW/MapViewOfFile/RtlMoveMemorydirectly into theStrPtrarea of aStringallocated withSpace$(n), so the string conversion cost is almost zero. - The payload is a sequence of per-module records:
{operation (create/update/delete), module kind, module name, content hash, body}.
14.5 Notification
- Push (primary): After writing, ras calls
Application.Run "RASBridge.xlam!RAS_Pull"through COM. If the call is rejected because Excel is in cell-edit mode or showing a modal dialog (RPC_E_CALL_REJECTED, etc.), it is retried with exponential backoff. - Polling (secondary): The Bridge checks only the sequence number every second with
Application.OnTime, so nothing is missed even if pushes keep failing. - Only a short notification is sent through COM; the code itself is always passed through shared memory.
- The macro name passed to
Application.Runmust always carry the workbook name, in the form'<workbook name>'!<procedure>(a'in the workbook name is doubled to''). Without it, error 1004 occurs when another workbook is active. Application.Rundoes not return while a modal dialog is displayed. The caller must always combine it with the dialog monitoring of §14.10.6 and report the contents of the dialog.
14.6 Application by the Bridge
- Standard modules and existing class modules:
CodeModule.DeleteLines 1, CountOfLines→CodeModule.AddFromString body. Do not useVBComponents.Remove→Import(Removeis deferred until the macro ends, so re-creating a module with the same name leads to the trap of getting a different name such asModule11). - Always delete all lines before writing, even for new modules: On PCs where the VBE option "Require Variable Declaration" is enabled, a module created with
VBComponents.Addalready contains oneOption Explicitline (it is empty on PCs where the option is disabled). CallingAddFromStringas is would duplicate theOption Explicitof the generated code and cause a compile error. So, whether the module is new or existing, ifCountOfLines > 0, callDeleteLinesbefore writing. This does not depend on the user's VBE settings. - New classes and classes involving attribute changes:
AddFromStringcannot setAttributelines (VB_PredeclaredId, etc.), so only in this case the module isImported through a temporary file. The temporary file is written with CRLF and the ANSI code page of the running Windows (GetACP(), nottarget.codepage). A.clswith LF only is imported as a standard module, and a different code page garbles the text (§13.7). - Check the result of
Import/Remove: If the component name afterImportdiffers from the requested name (for example because a component with the same name remained and the new one becameFoo1), delete the imported component and treat it as a failure. IfRemovefails, do not proceed toImport. - Document modules (
ThisWorkbook, sheets): As with standard modules, delete all lines of the code module, then write the code generated from the corresponding file (§12.2). (Attributelines do not appear in theCodeModule, so they stay unchanged.) The RAS-managed region that rewrote only part of a module ('--- RAS BEGIN ---/'--- RAS END ---) has been removed.- Files without code: A module with a
RAS-GENERATEDline (one RAS generated earlier) has all its lines deleted and becomes empty. - Sheets without a file: Among modules with a
RAS-GENERATEDline, one that this project's sync wrote earlier (build/sync/<code name>.vbaexists; §14.7.3) is regarded as having had its file deleted, and all its lines are deleted so it becomes empty. Any other is regarded as belonging to a duplicated sheet (Worksheet.Copyalso duplicates the module's code), and the source file is duplicated (§14.7.2). If the source cannot be determined, the module is left as is without writing, and shown in the sync result (the code is never deleted). The warning tells the possible origins apart: a copy of the sheet whose module holds the same code, if the workbook has one; for the module ofThisWorkbook(which a sheet copy cannot produce), code another RAS project wrote into the workbook, or that this project wrote beforebuild/sync/was deleted (if the modules that code calls are not in the workbook, VBA reports a compile error); for a sheet that is neither, both possibilities.--overwriteremoves code this project does not use. - Modules with hand-written code remaining: A module with no
RAS-GENERATEDline that has code other thanOptionstatements and comments first becomes a candidate for import (§14.7.1). If import is disabled, or the corresponding file already has code so it cannot be imported, it is an error just like a hand-written standard module with the same name, and nothing is written (specifying overwrite replaces it; §14.9.3). A module whose corresponding file has no code and which has no boilerplate to add (§12.3) is left as is. - Modules written by RAS v0.9 or earlier: The managed region (
'--- RAS BEGIN ---to'--- RAS END ---) is removed together with its contents, and then the rules above are applied (if code remains outside the region it is hand-written code; if not, it is a module without code).
- Files without code: A module with a
- Differential application: A module whose content hash equals the current hash on the Excel side (computed and cached by the Bridge with
RtlComputeCrc32) is skipped. - Atomicity: When one sync updates multiple modules, the Bridge keeps the bodies from before the application and restores them if it fails midway.
- Not applied while running or in break mode: Rewriting code during macro execution or break mode causes a state reset or abnormal termination, so the Bridge defers application until Excel is idle and returns the status "pending".
- Compile check after application (optional): If
sync.compileCheck = trueinras.toml, the Bridge runs the VBE's "Compile VBAProject"; if there are errors, it converts the locations to RAS-side positions with the source map and shows them in VS Code as diagnostics.- The compile command is looked up in the VBE menu bar with
FindControl(Id:=578)(it is not necessarily on the "Debug" toolbar). A control that is disabled (Enabled = False) means "already compiled", not a failure. - A compile error appears as a modal dialog in the VBE, so run it under the dialog monitoring of §14.10.6. Before closing the dialog, read the module and line from the VBE selection (
ActiveCodePane.GetSelection). Even if they cannot be read, the closing of the dialog and the classification of the result do not change.
- The compile command is looked up in the VBE menu bar with
- Notification of state reset: The status shows that rewriting the code resets the VBA state (global variables).
@init(§12.3) reinitializes it at the next macro entry.
14.7 Excel → local direction (--pull / automatic)
- RAS-managed modules: One direction only (RAS → Excel). A
' RAS-GENERATED hash=<CRC32>line is recorded at the top of the generated code. If it is edited in the VBE (hash mismatch), procedures and declarations added in the VBE are imported into the RAS files (§14.7.3), and other edits (rewriting or deleting generated code) are warned about as drift, letting the user choose among "overwrite with RAS", "show diff", and "save the VBE-side edits as.vba.patch". Generated code is not reverse-transpiled. Document modules (§12.2) are treated the same way: when a sheet module that RAS generated is edited in the VBE, added code is imported and everything else becomes drift. - Unmanaged modules (hand-written VBA, user forms): Synchronized in both directions. They are saved in the
vba/directory as.bas/.cls/.frm+.frx. The Bridge computes each module's CRC32 every 1 to 2 seconds and sends back only the changed ones through shared memory (the user form designer information.frxis binary, so it isExported through a temporary file only when a change is detected). It also syncs when the workbook is saved (Application.WorkbookBeforeSave). - Referencing unmanaged modules from RAS: The public signatures of the VBA modules in
vba/are analyzed so that they can be called from RAS with types (import { Foo } from "vba:Module1";).
Implementation note (current version): Two-way sync of unmanaged modules (saving to
vba/and detecting changes) and thevba: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 |
- Class modules: Module variables become fields (
Privatebecomesprivate), procedures become methods,Propertybecomes accessors (§3.6), andClass_Initializebecomesconstructor(). Unqualified references inside the class getthis.. Constants and enums are placed before the class (at the top level of the file). Because the file name equals the class name, the name of that file's standard module becomesEquipment_(§12.1.1). Custom events (Event/RaiseEvent) become aneventdeclaration and its invocations (§12.2.2).Class_TerminateandImplementsare not supported (// TODO(VBA):). - What stays VBA: What cannot be written in RAS (
Declare, declarations and procedures enclosed in#If … #End If, procedures containing statements that cannot be converted, and procedures that do not compile even after conversion) is not left as// TODO(VBA):but imported as is, as avbablock (§14.7.4). - Conversion: The same VBA → RAS conversion as
ras form pull(§14.11.6) is used. In standard modules,Public(or omitted) procedures, variables, constants, and enums areexported, andPrivateones stay inside that module. For references among the modules being imported, unqualified calls becomeimports (Total(1)→import { Total } from "src/Module1"). Calls qualified with the module name (Module1.Total(1)) are used as is without animport(§12.1.2). - Sheets and
ThisWorkbook: Converted into the module's file (§12.2). They are not moved to standard modules, so calls toSheet1.Foofrom other modules and macro names registered on buttons (Sheet1.Foo) keep working as they are.- Event procedures (
Worksheet_Change,Workbook_Open, etc.) become functions with@on("Worksheet.Change")/@on("Workbook.Open"). Mebecomesthis. Members of the sheet (workbook) used without qualification (Range("A1"),Cells(1, 1),Name) getthis.(this.range("A1"); in VBA,Rangeinside a sheet module refers to that sheet).Publicprocedures becomeexport function.- Event procedures of ActiveX controls on a sheet (
CommandButton1_Click) become functions with@on("CommandButton1.Click"), and references to the control (Me.CommandButton1, unqualifiedCommandButton1) becomethis.CommandButton1(§12.2.1). Private WithEvents app As Applicationbecomes the variablelet app: Excel.Application;, and its event procedures (app_SheetChange) become functions with@on("app.SheetChange")(§12.2.2).- Things treated as not convertible (TODO): events that
@ondoes not handle (Workbook_SheetPivotTableUpdate, etc.), and things that cannot be written in a document module file, such asPublicvariables and constants (E0650in §12.2).
- Event procedures (
- Code written later in the VBE: If code is written in the VBE in a sheet that had no RAS code (a sheet with no file, or with a file without code), it is imported at the next sync according to the rules above. Code added in the VBE to a module that has RAS-generated code is imported by §14.7.3.
- Module names: The VBA name of an imported module is determined by the file name (§12.1.1). A name containing
_such asmod_UtilbecomesModUtil, and the workbook'smod_Utilis deleted when replaced. If a name collides with another module or sheet, it is not imported (a message is shown). The modules of sheets andThisWorkbookare imported into a file named after the code name, without renaming (Sheet_Data→objects/Sheet_Data.ras). - Original VBA: The code at the time of import is saved to
vba/<name>.bas(.clsfor sheets,.frmfor forms) as UTF-8 with LF (excluding the RAS-managed region of v0.9 or earlier). - Form design: Live sync reads the
.frm/.frxwritten out withVBComponent.Export(including changes Excel has not saved).ras packreads from the workbook file.
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" |
- If replacement happened with lines that could not be converted (§14.11.6) remaining, that processing would be lost from the workbook, so no replacement is made while
// TODO(VBA):lines remain. Fix them and delete the// TODO(VBA):lines, and the next sync replaces the code. - When replacement succeeds, the marker line is rewritten as a normal comment (
// ブックの VBA(<name>)から変換したファイルです。…— "This file was converted from the workbook's VBA (). …"). From then on it is treated as a normal RAS module. The number of lines does not change (so that the generated code with line numbers does not change). - Imported files are included in the project build. If the conversion result has a compile error, sync does not happen, as with any other build error (the workbook does not change).
- If there is no marker and a project module and a hand-written workbook module collide on the same name, it is an error as before (specifying overwrite replaces it; §14.9.3).
ras packdoes not import when the workbook is open in Excel (when an owner file exists) or when--outputis specified.
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")
// }
- The created file contains only comments, so the workbook's module does not change until you write code (a file without code in §12.2).
- Duplicated sheets: If the module of a sheet with no file has a
RAS-GENERATEDline, it is regarded as a sheet duplicated together with its code by duplication in Excel (right-click the tab → "Move or Copy",Worksheet.Copy), and instead of a comment-only file, a copy of the source file is created. The generated code is not converted back into RAS; the RAS file that generated the same code is copied.- How the source is determined: The module's code is compared with the code last written to each sheet (
build/sync/<code name>.vba; if absent, the code generated from the current file), and the sheet that matches is the source. The comparison is the same as in §14.7.3 (differences in whitespace, letter case, and line numbers are ignored). Sheets whoseRAS-GENERATEDline has the same hash are checked first. - Duplication:
objects/<source code name>.rasis copied asobjects/<target code name>.raswithout changing its content. The sheet itself is written asthis, so the copied file works as the code of the target sheet. Places that write the source's code name (Sheet1.range(...)) are not rewritten (they continue to point to the source sheet). - Code added in the VBE after duplication: If something was added compared with the source's code, it is imported into the copied file by the rules of §14.7.3. If something from the source's code was rewritten or deleted, the file is copied and then the module is treated as drift (§14.7).
- Source unknown: A module that matches no sheet's code (a sheet duplicated from another workbook, a sheet whose source file has been deleted, etc.) gets no file created, the module is left as is, and it is shown in the sync result.
- With
sheet-files = false, no duplication is done either. The module is left as is and shown in the result. - A sheet duplicated by a macro at run time does not go through sync, so it runs with the duplicated code as is (
thispoints to that sheet). If you sync after saving that workbook, the file is created by the rules above.
- How the source is determined: The module's code is compared with the code last written to each sheet (
- A file is not created in these cases: a file with the same name exists; or
objects/has a file that corresponds to no sheet (it is regarded as a sheet whose code name was changed, so nothing is created, and theE0610message points out that the file name should be changed). - Chart sheets are not covered.
- A file deleted while its sheet remains is re-created at the next sync (a comment-only file; generated code remaining in the module is removed by the rule of §14.6). If it is not wanted, set
sheet-files = false. To delete a sheet itself, useras sheet remove(§14.16). ras packcreates them by the same rules (not when the workbook is open in Excel or when--outputis specified).
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.
Targets: Standard modules, and the modules of sheets and
ThisWorkbook. Class modules and forms (§14.11.7) are not covered. It runs in live sync andras pack(same conditions as §14.7.1), and is disabled by[sync] pull-unmanaged = false.What it is compared with: The previously written code. Sync and
ras packsave the code written to a module inbuild/sync/<module name>.vba. If it does not exist (synced on another PC,build/was deleted), the comparison is with the code generated from the current source.How it is compared: The module is divided into the statements of the declaration section (before the first procedure) and procedures (
Sub/Function/Property, including the comment right before). The VBE keeps code in a formatted form, so differences in whitespace and letter case and the presence of line numbers (forErl) are ignored.What is in the current module Treatment A procedure whose name is not in the previous code Added. Converted to RAS and imported A declaration-section statement not in the previous code (variable, constant, Declare, etc.)Added. Converted to RAS and imported A procedure or declaration identical to the previous code Stays as generated A procedure with the same name as in the previous code but different contents, or a procedure or declaration that has disappeared Drift. Not imported (the warning and choices of §14.7) Import: The added items are converted to RAS by the same conversion as §14.7.1 and appended to the end of that module's file with the comment
// VBE で追加されたコードを取り込みました(<hash>): <name>("Imported code added in the VBE (): "). The hash is of the added code and serves as a marker to avoid appending the same thing twice (the same comparison is made at every sync, even while a // TODO(VBA):remains and is waiting for replacement). The original added VBA is saved tovba/<name>.bas(.clsfor sheets).- An event procedure added to the module of a sheet or
ThisWorkbookbecomes an@onhandler (Worksheet_Activate→@on("Worksheet.Activate"),CommandButton2_Click→@on("CommandButton2.Click")). If that file already has a handler for the same event, this counts as a "procedure with the same name but different contents" (drift), because two procedures with the same name cannot be written in the VBE. - While the appended code has a
// TODO(VBA):line, as in §14.7.1, nothing is written to that module (the workbook's code is kept). - If the appended file gets a compile error (it collides with a name in the file, it calls a hand-written procedure that is not in the project, etc.), the file is restored to its content before the append and treated as drift.
- An event procedure added to the module of a sheet or
Writing: The module is rewritten with the code generated from the file after the import (no overwrite option needed). For a module in which drift remains, only the added items are imported and nothing is written to the module (it waits for the drift choice; choosing "overwrite with RAS" rewrites it with the code generated from the file after the import).
The sync result shows the names of the imported procedures and the files they were appended to.
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
}
- Where it can be written: At the top level of modules in
src/, files inobjects/, and form code-behind. It cannot be written in type definition files (.d.ras) or inside a class. - Contents: Output exactly as written. Escapes (
\n) and${…}are not interpreted.`cannot be written. Line numbers (forErl) are not added. - Output position: Blocks that contain procedures (
Sub/Function/Property) are output after the procedures generated in that module, and blocks that do not (Declare, variables, declarations enclosed in#If) are output in the declaration section. - Calling from RAS: Procedures inside a block are not visible to RAS. To call one, write
declare function name(arguments): return type;in the same file (voidfor aSub; addexportif other modules also use it). The declared name is output as is (even if it has the same name as a VBA function such asTrim, no_is added). A name declared withexport declare functionin a sheet or form file becomes a member of that sheet or form, just likeexport function(Foo(...)/this.Foo(...)from inside the file,Sheet1.Foo(...)from other modules). When you write an event procedure (Worksheet_Change, etc.) in a block, do not write a declaration (Excel calls it).Workbook_OpenofThisWorkbookcannot be written in a block because the compiler generates it (§12.3) (to keep it as VBA in an import, rename it toWorkbook_Open_VBA, place it in a block, and call it from an@on("Workbook.Open")handler). - When calling RAS code from inside a block: Use the generated VBA names. An enum member is
Enum_Member(Level_lvHigh), and a function or variable with the same name as a VBA function gets a trailing_(Trim_). - Module visibility: A module with a
vbablock does not getOption Private Module. - Running without Excel (
ras run/ras test): Blocks are not executed. Calling a declared function causes a run-time error.
Handling in import (§14.7.1): After conversion (VBA → RAS), import finishes in the following order.
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!ninteger ~n(VBA'sNotis a bitwise operation)a && b,a || binteger (one side may be any)a & b,a | bA Rangeused as a value (comparison, assignment, embedding in a string, condition)Excel.RangeAdd .value(default member)f(…) = v(the function returns aRange)Excel.Rangef(…).value = vAssignment among numbers, strings, dates, and booleans — cStr(x),cLng(x),x as int, etc. Boolean → number is(x ? -1 : 0), number → boolean isx != 0Comparison of a number with a string or boolean — cDbl(x)for a string,-1/0fortrue/falseletValue(x)(the right side of an assignment withoutSet)x.valueforRange,xfor numbers, strings, etc.Where the type is unknown ( any,object), it remainsletValue(x)The mechanical fixes of
ras check --fix(spelling of Excel / VBA members, etc.) are also applied at the same time.Procedures that do not compile: A procedure in which errors remain after step 1 is replaced, for that procedure only, with a
vbablock (and adeclare 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 likeTrim_) are rewritten to the generated VBA names. Class methods andPropertycannot be madevbablocks, so they remain as errors.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
- The correspondence between each statement of the generated VBA and the RAS source position is saved in
build/*.rasmap. - With the
--erloption (default for debug builds), line numbers are added to the generated VBA, and the RAS source position is restored and shown from theErlof a run-time error. - In the VS Code extension's "Show generated VBA", the VBA line corresponding to the cursor position is highlighted.
- Debugging with breakpoints is done on the JavaScript runtime, not in VBA (§14.10). The
debugger;statement (§14.10.9) that stops inside the source also outputs nothing in a VBA build.
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].
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).VBA/_VBA_PROJECTstream: 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).VBA/dirstream (compressed):PROJECTCODEPAGEand the module records (name, Unicode name, stream name, kind,MODULEOFFSET,MODULEPRIVATE, etc.) are regenerated to match additions, deletions, and renames.PROJECTstream: TheModule=/Class=/Document=/BaseClass=lines and the[Workspace]section are regenerated. Existing values such asID,CMG/DPB/GC(protection information), andHelpFileare preserved.PROJECTwmstream: The MBCS / Unicode name mapping table of the module names is regenerated.- Class attributes:
Attributelines such asVB_PredeclaredIdare stored at the beginning of the source (the constraint that requiredImportin live sync does not exist offline). - Document modules:
ThisWorkbookand sheet modules are rewritten only if they correspond toworkbookPr/@codeNameinxl/workbook.xmlandsheetPr/@codeNameof each sheet. The whole module source is replaced with code generated from the corresponding file (§12.2) (the leadingAttributelines are left as they were. Handling of modules with hand-written code remaining, etc., is the same as §14.6).ras packand sync do not create or delete sheets (adding, duplicating, and deleting sheets isras sheet; §14.16). If the workbook has no sheet corresponding to a file inobjects/, it is an error (E0610; §12.2). - User forms and other storages: Unmanaged forms (designer storage) are reconstructed from
.frm/.frxinvba/. For forms informs/, the designer storage is generated from the FormSpec and written (§14.11). Storages with no changes are preserved byte for byte. - OPC package: The
vbaProject.binpart, 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
- Atomic writing: Written to a temporary file in the same directory and swapped in after verification (described below). The file from before the replacement is kept in
build/backup/(the number of generations is specified inras.toml). - Lock detection: If the target workbook is open in Excel (the file is locked, or it exists in the ROT), offline writing is not performed and it switches to live sync (§14.1 to 14.8). There is no
--force-offline. - Verification after writing: The written
vbaProject.binis read again by ras itself, and it is confirmed that the sources of all modules match. - Digital signature: If the VBA project is signed, rewriting invalidates the signature. ras shows a warning and then deletes the signature part (
vbaProjectSignature*.bin). If a signing certificate is specified withpack.signinras.toml, it re-signs. - Password-protected projects: If the project is protected (
DPB), both writing and reading are errors. - Leftover owner files: Lock detection also looks for the owner file (
~$Book.xlsm). If Excel terminates abnormally, this file remains and the workbook keeps being judged "open" even though it is not, so the error message points out the file to delete. - Never silently replace hand-written modules: If the workbook has a standard module, class, or form with the same name that RAS did not generate (it has no
RAS-GENERATEDline), or if the module of a sheet orThisWorkbookwhose file has code contains hand-written code (§14.6), it is an error and nothing is written (name comparison is case-insensitive).--overwriteallows the replacement. - Detect in advance compile errors that only the VBE would find: Offline writing does not compile, so kinds of mistakes that would only be found in a VBE dialog after opening the workbook are checked before writing.
Optionstatements of document modules: Because the whole module is generated,Option Explicit/Option Compare Binaryare output at the beginning, as with other modules (§12.2).
14.9.4 Offline reading (ras unpack)
- The source part of the
VBA/<module>stream is decompressed and extracted, converted from the code page to UTF-8. Unmanaged modules and forms go tovba/, and RAS-managed modules are used only for drift detection (the sameRAS-GENERATED hashas §14.7). - If a file in a "VBA stomping" state, where the source part does not match the P-code, is detected, a warning is shown (the source side is taken as authoritative).
- Files in
vba/are saved as UTF-8 with LF (to make diffs easy). This is not the VBE export format (ANSI code page, CRLF), so they cannot be used with the VBE's "Import File".
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
- No custom debugger: The output is CommonJS modules and Source Maps (v3), and the debugger itself is VS Code's built-in JavaScript debugger (js-debug), used as is.
- Runs as written: Inline expansion, loop fusion, bulk transfer, and automatic
DoEventsinsertion (§8 to §10.4) are not applied. One RAS statement corresponds to one JavaScript statement, and local variable names are kept as they are. - Not a replacement for the VBA build: The semantics match the VBA build (§14.10.4), but execution timing, post-optimization behavior, and calls initiated by Excel are not reproduced (§14.10.5). The location of an error that occurred on a real machine is still identified with
Erland the source map (§14.8), as before.
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
- The runtime calls
IDispatchwith late binding through the Node addonras_com.node(crates/ras-com, Windows only). The generated code explicitly distinguishes property get, property set, and method call, as in$rt.get(obj, "Value")/$rt.put(...)/$rt.call(obj, "Cells", [r, 3]). - The target is decided by the same rules as §14.3: it looks up
workbookfromras.tomlin the ROT and connects to the Excel instance that has it open. If it is not open, it is opened in a running Excel. If Excel is not running, the workbook is opened the same way as a double-click (ShellExecute), and it waits up to 60 seconds for it to appear in the ROT. An automation Excel started withCreateObject("Excel.Application")is not used (access to the VBA project and the like differs from a normal launch, and an instance left over after a run cannot be synced or used with "Run in Excel"). Ifworkbookis not specified, the active workbook is used. - Some ways of opening do not register in the ROT (an
.xlamloaded as an add-in, and a workbook in a OneDrive / SharePoint sync folder whoseFullNameis a URL). So beforeWorkbooks.Open, it looks upWorkbooks(<file name>)directly in the connected Excel, and uses it if it is the same workbook (the full path matches, orFullNameis a URL). If a different workbook with the same name is open, it fails with an error rather than waiting for an Excel dialog. ThisWorkbookresolves to that workbook, a sheet code name (such asSheet1) to the sheet whoseCodeNamematches, and other globals (activeSheet,range(...), and so on) to members ofApplication. Members are called with the spelling in the type library (COM name resolution is case-insensitive).- If Excel rejects a call because it is editing a cell or showing a modal dialog (
RPC_E_CALL_REJECTEDand the like), it retries with backoff for up to 60 seconds. Notification while waiting is described in §14.10.6. - If the Excel process is gone (
RPC_S_SERVER_UNAVAILABLE/RPC_E_DISCONNECTEDand the like), it raises an error saying the connection was lost. - Value mapping:
Empty/Null/Nothing→null; dates → a date object (retaining the serial value); cell error values → an error value object; the 2-dimensional array ofRange.Value→ an array of rows, 0-based. - The VS Code extension starts the runtime bundled with VS Code in Node mode (
ELECTRON_RUN_AS_NODE), so Node.js does not need to be installed separately. The built-in debugger'slaunchstrips this environment variable, so the extension starts the process and the debugger connects withattach.
14.10.4 Semantics matched to the VBA build
- Integer arithmetic overflow (error 6), division by zero (error 11), and out-of-range array access (error 9) become run-time errors. Integer division and conversion with
astruncate toward zero. - Assigning from
any(Variant) to a typed variable converts (an empty cell →0/"", a numeric string → a number, error 13 if it cannot be converted, and conversion to an integer uses banker's rounding). - Arrays and structs (
struct, anonymous object types, tuples) are value types (copied on assignment, passed by reference to functions). Abyrefargument rewrites the caller's variable. - Floating-point numbers are converted to strings with 15 significant digits (
0.1 + 0.2is0.3).Math.roundrounds half away from zero, andtrimremoves only half-width spaces. try { } catch { resume; }ignores errors statement by statement and proceeds to the next statement. Theeincatch (e)hascode/description/source/rasFile/rasLine.- Dates are held as the same value as VBA's
Date(days since 1899-12-30). Them/q/yyyyintervals ofdateAddclamp to the end of the month (one month after 1/31 is 2/28; it does not carry over to 3/3 as JavaScript'ssetMonthdoes), whiled/hand the like carry across months and years. If the result is outside the years 100 to 9999, it is error 5.dateSerialcarries out-of-range months and days, and reads years 0 to 29 as 2000s and 30 to 99 as 1900s. For date-times before 1899-12-30, the time is held as a fraction with the same sign as the day (1899-12-29 6:00 is-1.25). A string for a nonexistent date (2026/13/40) gives a type mismatch incDate/isDate. @fastandfastMode/suspend*/statuschange the state of the realApplicationand restore it on exit (including abnormal termination).sleep(ms)/waitUntil(...)wait 20 ms at a time and callDoEventsin between, as in the VBA build (§10.4.1). A modeless form on display (§14.10.7; for example, a progress bar's cancel button) responds to input while waiting, and the condition ofwaitUntilcan read values changed by form events.yieldNow()callsDoEventson the spot. AdeclaredSleepandApplication.Waitstop without processing anything, as in Excel. In the playground, when the page is not cross-origin isolated, the wait is done with an empty loop.
14.10.5 What is not reproduced, and limitations
- Calls initiated by Excel:
@onevent handlers (workbook, sheet, controls on a sheet,WithEventsvariables),@udf, ribbon callbacks, and the path that calls a RAS function from hand-written VBA cannot be started (calling hand-written VBA from RAS is possible viaApplication.Run). Events raised by Excel also cannot be received by RAS handlers. In debug execution without Excel (§14.10.8), the runtime raises the workbook and sheet events caused by the program's operations and calls the@onhandlers. User forms are displayed and run in VS Code, not in Excel (§14.10.7). The events of what the user does can be raised withras run --event(§14.13) andsimulatein tests (§14.12.4), and functions with parameters and@udffunctions can be called withras run --arg. typeoffor numbers: JavaScript numbers do not distinguishLongfromDouble.typeofreturns the type name when the static type contains only one numeric type (such asdoubleorstring | double); otherwise it returns"Long"for integers and"Double"for everything else. So narrowing a union type that contains several numeric types, such asint | double, withtypeofcan give a different result from the VBA build.- Numeric type precision:
long,currency, anddecimalare represented as double-precision floating-point numbers (longbecomes inexact above 2^53, and0.1m + 0.2m == 0.3mdoes not hold fordecimal).floatis computed in double precision. - Hints (
I0520): The places where these differences may change the result from VBA are shown as hints of the language server and byras check --target stand-in: a date made text without a format (cStr(d),format(d),${d}in a template literal),typeofof a union of several numeric types,longmultiplication and powers, and==/!=ofcurrency/decimal. The VBA itself is right, so they are not warnings. - VBA standard functions: The commonly used ones (strings, conversion, dates, math,
MsgBox,CreateObject, and the typicalFormatformats) are implemented in JavaScript. An unsupported function raises an error when it is called. UnsupportedFormatformats are delegated to Excel'sTEXTfunction. Locale-dependent notation (such as the default date format) may not match VBA. CreateObject/new(COM objects): On Windows with the COM addon (ras_com.node), real COM objects are created (even without Excel). In debug execution without COM (Mac, Linux, and Windows whereras.debug.excelisstandIn),Scripting.FileSystemObject,Scripting.Dictionary,VBScript.RegExp, andADODB.Streamare created with the runtime's JavaScript implementation (ras-scripting.js). Any other ProgID (ADODB.Connection,WScript.Shell,MSXML2.XMLHTTP, and so on) is error 429. The JavaScript implementation follows the behavior of Japanese Windows. ThecharsetofADODB.Streamisutf-8,unicode(UTF-16 LE),unicodeFFFE(UTF-16 BE),shift_jis,euc-jp,iso-2022-jp, and their aliases (such aswindows-31j); anything else is a character encoding that Node'sTextDecoderknows (for writing, only single-byte encodings). As in ADO, a BOM is added to UTF-8 and UTF-16 text written at the start of the stream, and the BOM is removed from text read from the start. Errors also use ADO's numbers (3001 invalid argument, 3002 cannot open the file, 3004 cannot write, 3219 operation not allowed, 3704 closed).- Files:
FileSystemObjectfile and folder operations (copy, move, and delete accept wildcards),File/Folder/Files/Folders, andTextStreamreading and writing. Drives (drives/getDrive) are not supported. Errors use VBA's numbers (53 file not found, 76 path not found, 58 already exists, 62 end of file, 70 cannot write). - Character encoding: Text files are read and written in ANSI (Shift_JIS, code page 932), as on Windows. Specifying
unicode/tristateTruegives UTF-16 (with a BOM). Reading a UTF-8 file as ANSI produces garbled text, as on Windows. - Paths: On Mac and Linux,
\is treated as a path separator in addition to/(code written likefolder + "\\data.txt"works as is). Methods that handle only the path string, such asgetParentFolderName, accept either separator. - Dictionary: Key order,
compareMode, the behavior that reading a missing key adds it with an empty value, and the error numbers (457, 32811) are the same as the real one. - Regular expressions: The pattern is interpreted as a JavaScript regular expression (VBScript regular expression syntax is a subset of it).
global/ignoreCase/multiline,test/execute/replace($1,$&). A pattern error is error 5017.
- Files:
- File operations using file numbers:
fileOpen/printLine/lineInput/fileGetand the like, and VBA standard functions such asdir/kill, read and write real files with the runtime's JavaScript implementation (§15.3.2). declare(DLL functions): Onlykernel32'sSleep/GetTickCount/GetTickCount64/GetCurrentProcessId/QueryPerformanceCounter/QueryPerformanceFrequencyhave substitute implementations. Anything else raises warningW1410and raises an error when called.- Speed: Access to Excel is an inter-process COM call, so a loop that reads and writes cells one at a time is much slower than the VBA build.
- The running Excel: The state is not that of a running macro, so the user can operate Excel both while stopped and while running.
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.
- A hand-written
Worksheet_Changeor similar, triggered by writing to a cell, caused a run-time error (the "Run-time error" dialog) - Hand-written VBA has a compile error, and an event or
Application.Runcaused the VBE to show a dialog MsgBox/InputBoxin hand-written VBA- Excel's own confirmations (deleting a sheet, overwriting on save, updating links, whether to open read-only, and so on)
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).
- Detection: Among the windows of the target process (the owner of
Application.Hwnd), those whose class is#32770(standard dialog),NUIDialog, orbosa_sdm_*(Office's own dialogs) and that are enabled. Visibility (IsWindowVisible) is not a condition: when Excel is in the background, a run-time error dialog may be created but not drawn (a#32770that has an owner and buttons is a target even when hidden). - Reading the contents: The title, the text of
Staticcontrols, and the captions, control IDs, and enabled state ofButtoncontrols are read with Win32. For Office's own dialogs that have no child windows, the text and button names are read with UI Automation (if they cannot be read, only the title is reported). - The kind is not determined from caption text: Buttons are identified by control ID (
IDOK/IDCANCEL…) and access key (&E, or終了(E)in the Japanese edition). A#32770with 3 to 4 buttons that have the access keys C, E, and D is a VBA run-time error. - Notification: A dialog that is found is written to standard error exactly once, as a single line starting with
[ras] Excel …(title, text, buttons). The VS Code extension shows this line as a notification. If Excel keeps rejecting calls but no dialog is found (for example, while a cell is being edited), a message to that effect is written once after 3 seconds. When it fails with the 60-second timeout, the open dialogs are included in the error message.
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.
- Starting: Start by displaying the form from the "Debug" CodeLens at the top of the form's code-behind, the button in the designer's title bar, or
<form name>.showin the list of runnable functions. It can also be displayed from a function in another module withfrmInput.show(). - Instances: The instance is created when the form name (the default instance) is first referenced; the module variables are initialized and
Initializeis raised. Referencing it afterunloadcreates a new instance (the same as VBA). Each instance created withnew <form name>(...)(§14.11.9) has its own module variables. The code-behind's JavaScript has only one set of module variables, so each time the runtime calls an event handler, a published function, or a handler attached withon, it swaps in that instance's values for the call and restores the originals afterward. - Display:
show()displays modally (the default for the generated form'sShowModal), andshow(vbModeless)displays modelessly. Modal display does not return until the form is closed (hide/unload). Modeless display returns immediately, and even after the function that started it finishes, the process does not end until all displayed forms are closed. - Connection to the host: For each debug execution, the VS Code extension listens on a TCP port on
127.0.0.1and passes the port number to the process in the environment variableRAS_FORM_HOST. The runtime connects when it first displays a form. The generated code runs synchronously, so while waiting for user operations a worker thread handles the socket and the main thread waits at short intervals withAtomics.wait(the debugger's pause still works meanwhile). Communication is one JSON per line: the runtime sends the form's state (show/update/hide/unload), and the extension returns user operations (focus moves, input, clicks, selection, tab switches, and the close button). IfRAS_FORM_HOSTis absent (run outside VS Code), displaying a form is error 429.- In the playground (
web/), the page is the host. The Web Worker that runs the program sends the form's state to the page, and the page draws the form over the page in the same form panel as the VS Code extension. User operations are returned to the worker through aSharedArrayBuffer(the worker waits withAtomics.wait). It is passed to the runtime ashooks.formHost(send/receive) instead of a socket. In a browser where the page is not cross-origin isolated (SharedArrayBufferis unavailable), displaying a form is error 429.
- In the playground (
- The runtime holds the state: The runtime holds control values, focus, and visibility, and the panel only draws them. Typed characters are passed to the runtime and then
Changeis raised, and the values rewritten by the handler are returned to the panel. Characters typed in succession while a handler is running (including while stopped at a breakpoint) are not lost (the panel does not overwrite an input field with an older value until the runtime has processed the last input). - Events: The following events are raised in the same order as VBA. The handler calling conventions (declaration order, ignoring re-entry,
byrefarguments) are the same as §14.11.2.
| 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.
- Errors: An error not caught by a handler does not stop execution, as with the VBA build's RAS error dialog (
RAS_EventError). The error and the RAS location are shown in the debug console and the form's panel, and it waits for the next operation. To stop on an error, enable "Caught Exceptions" in VS Code's breakpoints. - MSForms objects: The main properties and methods of the form (
caption,width/height,backColor,font,controls,activeControl,show/hide) and of the built-in controls (§14.11.1) are implemented in JavaScript (text/value,caption,enabled/visible/locked, position and size, color and font,ComboBox/ListBoxaddItem/removeItem/clear/list/column/listIndex/listCount/selected/multiSelect,MultiPagepages/selectedItem,TabStriptabs,picture/mouseIconofImageand the like, andloadPicture). Initial values are read from.form.json(includinglist/selectedIndex). An unimplemented member is error 438, and an unsupported operation such ascontrols.addis error 445. - Appearance: The panel draws the form with Windows' default colors (system colors) and fonts. Coordinates and sizes are in points, and the layout is roughly the same as an Excel form, but control rendering (border shapes, list row heights, the
ComboBoxdrop-down, and so on) is the browser's and does not match Excel. - What is not reproduced: Modality between Excel and VS Code (while a modal form is displayed, other parts of Excel and VS Code can still be operated; other forms of the debug execution cannot),
StartUpPosition, user resizing of the form, and custom controls. A form'szoomis shown as scaling of the controls, andscrollBars/keepScrollBarsVisible/scrollWidth/scrollHeight/scrollLeft/scrollTopas scrolling within the panel. - Linking with cells: A
ComboBox/ListBoxwithrowSourcereads its items from that cell range in Excel when the form is loaded. A control withcontrolSourceshows that cell's value when the form is loaded (beforeInitialize), and writes the value changed by the user to the cell when it is committed (afterBeforeUpdate, beforeAfterUpdate). If reading or writing fails, it is shown in the debug console and execution continues.
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).
Structure: The Node addon
ras_book.node(crates/ras-book) holds the workbook. Reading and writing the workbook uses umya-spreadsheet (the same fork and the same branchexcel-compatas xljs; the reading and writing shared by xljs and RAS is gathered there: the fork'sFORK.md), and calculation is done by GridCraft, with that part incrates/ras-workbook. The Excel object model (Application,Workbooks,Workbook,Worksheets,Worksheet,Range,Names,WorksheetFunction) is implemented in JavaScript byras-excel.js. The generated code calls it with the same$rt.get/$rt.put/$rt.callas for COM, so the build output does not change.Conditions for use: The runtime receives the addon in the environment variable
RAS_BOOK_ADDON, and uses the stand-in when there is no COM addon (RAS_COM_ADDON), or when there is a COM addon but Excel is not installed (theExcel.ApplicationProgID is not registered). If the VS Code extension settingras.debug.excel(excelinlaunch.json) isauto(the default), Excel is used on Windows and the stand-in elsewhere;standInuses the stand-in even on Windows;exceluses only Excel. The workbook is loaded when the program first uses an Excel object, and this is shown in the debug console. Ifworkbookis not specified, it runs with an empty workbook (one sheet).Calculation: As with Excel's automatic calculation, when a cell is rewritten, the formulas that depend on that cell are recalculated before the next value is read. When a workbook is opened, the saved calculation results are used, and only formulas with no saved result and formulas that change every time, such as
NOW/RAND, are calculated. Formulas that contain functions the engine does not have (hand-written VBA user-defined functions, add-in functions), references to other workbooks, or data tables are not calculated, and their saved values are used as is (the same treatment as xljs'sbook.calculate(); xljs'sdocs/design/calc-design.md).Manual calculation: Setting
Application.Calculationto manual (xlCalculationManual) stops calculation, as in Excel. Rewriting a cell does not recalculate formulas; they are calculated whenCalculateis called (Application/Workbook/Worksheet/Range; each calculates all pending formulas) and when it is set back to automatic.CalculateFullrecalculates all formulas. Even in manual mode, a formula entered into a cell is calculated once at the time it is entered (formulas that reference it are not calculated). The same applies duringfastMode()/suspendCalc()(§10). If a workbook saved with manual calculation is loaded as the project's workbook, it starts in manual mode, as when Excel first opens that workbook, and this is shown in the debug console. The calculation mode is written to the saved workbook, and in manual mode, ifCalculateBeforeSaveisTrue(the default), calculation is performed before saving.Values: The same mapping as for COM (§14.10.3). If the cell's number format is a date,
Valueis a date andValue2is a number. A string assigned toValueis interpreted as when entered into the cell in Excel ("123"becomes a number,"2026/3/4"becomes a date with the number formatyyyy/m/dapplied,"=A1*2"is a formula, and a leading'makes it a string). A cell whose number format is text (@) stays a string. As in Excel, a date number format is applied to a cell into which a date was entered, and to a cell into which a formula that referencesTODAY()or a date cell (=A1+1) was entered. Cell error values useCVErrnumbers (#N/Ais 2042).Formulas:
Formulais written as an Excel formula without dynamic arrays (where a range is used as a single value, implicit intersection applies).Formula2spills as a dynamic array formula. When one formula is entered into multiple cells, relative references are shifted per cell. Reading and writingFormulaR1C1and moving a formula's relative references withRange.Copy Destination:=are also supported.Supported members:
Range:Value/Value2/Formula/Formula2/FormulaR1C1/Text/NumberFormat/HasFormula,Cells/Item/Rows/Columns/Range/Offset/Resize/End/CurrentRegion/EntireRow/EntireColumn/Areas/Address/Count/Row/Column,Left/Top/Width/Height(position and size; below),ClearContents/Clear/ClearFormats/Copy/Cut/PasteSpecial/Insert/Delete/FillDown/FillRight/Sort/RemoveDuplicates/AutoFilter/AdvancedFilter/SpecialCells/Find(including the wildcards*/?/~) /FindNext/FindPrevious/Select/Activate,For Each, and formatting (below).Worksheet:PageSetup(PrintAreareads and writes the workbook's print area, the name_xlnm.Print_Area; the other settings only remember their values) /Name/CodeName/Index/Visible/Cells/Range/Rows/Columns/UsedRange/Activate/Delete/Move/Copy(within the same workbook) /Paste/Sort/AutoFilter/AutoFilterMode/FilterMode/ShowAllData/Evaluate.Worksheets.Add,Workbooks.Add/Open,Workbook.Save/SaveAs/Close,Names.Add, andApplication.Intersect/Union/Evaluate/ActiveSheet/ActiveCell/Selection/Calculation/Calculate/CutCopyMode.WorksheetFunctioncan call every function the engine has (about 490). When the result is an error value,WorksheetFunction.Xraises error 1004 andApplication.Xreturns the error value.Multiple areas:
Union,SpecialCells, andRange("A1:B2,D4")return a range made of multiple areas.Areas,Count,Address,For Each,EntireRow/EntireColumn,Offset, writing values, formulas, and formats,Clear,Delete, andCopy(for areas with aligned rows or columns) apply to all areas. Reading values andRows/Columns/Resizeand the like look only at the first area, as in Excel.Inserting and deleting cells:
Range.Insert/Range.Deletesupport whole rows, whole columns, and cell-level shifts (xlShiftDown/xlShiftToRight/xlShiftUp/xlShiftToLeft; if omitted, it is decided by the shape of the range, as in Excel). As in Excel, formats, merged cells, filters, the ranges of data validation and conditional formatting, and tables move together with the cells, and the references in formulas and names across the whole workbook are updated (a reference to a deleted cell becomes#REF!). Inserted cells inherit the format of the cell above or to the left (below or to the right ifCopyOriginisxlFormatFromRightOrBelow). Operations that Excel rejects (pushing non-empty cells off the sheet, splitting an array formula, merged cells, or a table) are error 1004. ARangeheld in a variable does not follow insertions and deletions, unlike Excel (even afterrows(1).insert(), therinconst r = ws.range("A5")stays at A5).Clipboard: Only cutting, copying, and pasting within Excel are supported (nothing is exchanged with other applications).
Range.Copy/Range.Cut(with or without a destination),Worksheet.Paste,Range.PasteSpecial(xlPasteAll/xlPasteValues/xlPasteFormulas/xlPasteFormats/xlPasteValuesAndNumberFormats/xlPasteFormulasAndNumberFormats/xlPasteAllExceptBorders/xlPasteColumnWidths/xlPasteValidation,Operation,SkipBlanks,Transpose), andApplication.CutCopyMode.- As in Excel, the copy source is remembered as the range itself, and the contents at the time of pasting are pasted together with formats and merged cells. Copied formulas have their relative references shifted. The formulas in cut cells keep their references, and references to the cut cells (including those from other sheets) follow them to the destination.
- If the paste destination is an integer multiple of the size of the copy source, it is pasted repeatedly; otherwise it is pasted once from the top-left cell. Rows hidden by a filter are not copied. The pasted range becomes the selection.
Range.Insertduring a copy or cut becomes "insert copied cells", as in Excel (inserting cut rows or columns within the same arrangement closes up the original location).- As in Excel, changing a cell's value or format cancels the copy or cut (
CutCopyModereturns to 0, and a laterPasteSpecial/Pasteis error 1004). Pasting what was copied does not cancel it. What was cut is canceled after being pasted once. - To another workbook, only values or formulas and number formats are pasted (other formats do not carry over;
Operation/Transposeare errors). Pasting only comments (xlPasteComments) is error 1004. Pasting only data validation (xlPasteValidation) replaces the validation of the destination with that of the copied range (within one workbook).Range.Cleartakes the validation away too (ClearContents/ClearFormatskeep it, as in Excel).
Sorting and filtering:
Range.Sort(up to 3 keys,Header,MatchCase,Orientation) andWorksheet.Sort(SortFields.Add/Add2/Clear,SetRange,Header,Apply). The order is the same as Excel (numbers, text,FALSE,TRUE, error values; empty cells come last in both ascending and descending order). Formulas have their relative references shifted, and formats move with the cells. Hidden rows are not moved. Strings are compared by the characters themselves, not by phonetic readings (furigana). Sorting by color or icon is not supported.Range.AutoFilter: comparisons ("=Tokyo",">=10","<>", the wildcards*?) and theirxlAnd/xlOr, value lists (xlFilterValues), and top and bottom (xlTop10Items/xlBottom10Items/xlTop10Percent/xlBottom10Percent). As in Excel, equality is compared with the cell's displayed text and magnitude with the value.Worksheet.AutoFilterMode/FilterMode/ShowAllData/AutoFilter(Range,Filters(i).On). Filter conditions are saved in the workbook. Filtering by color or icon is not supported.Range.AdvancedFilter: a criteria range (each row below the headings is an OR, and within a row is an AND; strings are prefix matches),xlFilterInPlace/xlFilterCopy(the columns can be chosen with the headings of the extract range), andUnique. Conditions by formula are not supported.Range.RemoveDuplicates,Hiddenof rows and columns, andRange.SpecialCells(xlCellTypeVisible/xlCellTypeConstants/xlCellTypeFormulas/xlCellTypeBlanks/xlCellTypeLastCell; if nothing is found, error 1004, as in Excel).SUBTOTAL/AGGREGATEcalculate excluding rows hidden by a filter (and, depending on the function number, rows hidden manually).
Hyperlinks:
Worksheet.Hyperlinks/Range.Hyperlinks(Count,Item,For Each,Add,Delete),Hyperlink(Address,SubAddress,ScreenTip,TextToDisplay,Name,EmailSubject,Range,Type,Follow,Delete),Range.ClearHyperlinks, andWorkbook.FollowHyperlink. As in the file, hyperlinks are held on the cell (and saved in the workbook), and move together with cells when cells are inserted or deleted.Hyperlinks.Add: Replaces the link of theAnchorcell (the top-left cell if it is a range). If there isTextToDisplay, it is entered into the cell; if not, the address is entered only into an empty cell (Changeis raised). An underline and a color (#0563C1) are applied, as with Excel's "Hyperlink" style. Hyperlinks on shapes cannot be created.Follow: For a location within the workbook (SubAddress; no address, or the file is this workbook), it selects that range (the sheet switch andSelectionChangeoccur). Other addresses (URLs, other files) are not opened, and a message saying it would open them is shown in the debug console. ThenFollowHyperlinkof the sheet with the link andSheetFollowHyperlinkof the workbook are raised (the table below).Workbook.FollowHyperlinkonly moves to the location and raises no events.Hyperlinks.Delete/Hyperlink.Deleteremove the link and the underline and color, andClearHyperlinksremoves only the link (the appearance stays).Clearalso removes the link, andClearContentskeeps it.- Hyperlinks do not move with sorting, cutting, or copying (and are not copied). A link that has both an address and a location (such as a link to a cell in another workbook) keeps both (
AddressandSubAddress).
Notes (comments):
Range.AddComment,Range.Comment(the note of the top-left cell of the range, orNothing),Range.ClearComments,Worksheet.Comments(Count,Item,For Each; by rows), andComment(Text,Author,Visible,Delete,Next,Previous,Parent). As in the file, notes are held on the sheet (Excel's "notes", the legacy comments:comments1.xmland their VML boxes) and go into the saved workbook, soras book view(the red triangle of the cell and the note) andras book dump("Note:" in the outline of the sheet) show them. They move together with cells when cells are inserted or deleted.AddComment(text): Adds a note to the top-left cell, byApplication.UserName. A cell that has a note cannot get another (error 1004, as in Excel).Comment.Text(text, start, overwrite): Without arguments, returns the text of the note. Withtextonly, replaces the whole text; withstart, inserts it at that character (overwriting whenoverwriteistrue).Visibleis whether the note is always shown, and is saved in the workbook.- The position, size and formatting of a note's box (
Comment.Shape) and threaded comments (CommentsThreaded) are not handled. Notes do not move with sorting, cutting, or copying (and are not copied).
Formatting: The following formats are held in the workbook and saved. They move together with the cells when cells are inserted or deleted, copied or cut, or sorted.
Font(Name/Size/Bold/Italic/Underline/Strikethrough/Color/ColorIndex/Superscript/Subscript),Interior(Color/ColorIndex/Pattern/PatternColor),Borders(LineStyle/Weight/Color/ColorIndex; each edge such asBorders(xlEdgeBottom),Borderswithout an edge, andBorderAround),HorizontalAlignment/VerticalAlignment/WrapText/ShrinkToFit/IndentLevel/Orientation,Locked/FormulaHidden,ColumnWidth/RowHeight,Hidden(whole rows and columns),Merge/UnMerge/MergeCells/MergeArea, the number formatNumberFormat, and the sheet tab color (Tab.Color). Reading from a range whose cells have different values returnsnull, the equivalent of VBA'sNull. A format set on a whole row or column also applies to cells later written in that row or column. There is no screen, so nothing is rendered (AutoFitdoes nothing). Other formatting properties (ThemeColor,TintAndShade,Style, and so on) accept any value and return the value that was set when read from the same range, but are not saved.Events: The
@onhandlers of the project's workbook and its sheets (objects/ThisWorkbook.rasand the sheet files; §12.2) are called in response to the program's operations. The order matches the order in which Excel raises them, and has been checked against a real Excel 2021 withtools/standin-check. Handlers ofWithEventsvariables that point to the project's workbook, its sheets, orApplication(§12.2.2) are also called according to the same table. Events of controls on a sheet (§12.2.1) are raised when the program changes a control's value (see "Controls" below) and by operations in the sheet preview's run mode (§14.10.10).Controls: The sheet's ActiveX controls and form controls are loaded from the project's workbook file (
Book.controlsofras_book), and their state is held while the program runs.- An ActiveX control can be referenced as a member of the sheet (
Sheet1.CheckBox1,this.TextBox1), withOLEObjects(name | number)(.Objectis the control), and withShapes(name).OLEFormat.Object. It hasValue,Text,Caption,Enabled,Visible,LinkedCell,ListFillRange,GroupName,Min,Max,SmallChange,LargeChange, and, for list and combo boxes,ListIndex,ListCount,List(i),AddItem,RemoveItem, andClear. If there is a linked cell (LinkedCell), the value reads and writes that cell (writing to the cell does not raise the sheet'sChange; the same as Excel). The items of a list or combo box are those from the cells ofListFillRangeor added withAddItem. Appearance settings such asBackColorandLockedonly remember the value. Position and size (Left,Top,Width,Height) cannot be handled (error 445). - Changing a value raises the control's events, as in Excel (it is not stopped by
Application.EnableEvents): check boxes, option buttons, and toggle buttons raiseChangeandClick(turning on an option button turns off the other option buttons with the sameGroupName); text boxes raiseChange; list and combo boxes raiseChange(andClickas well if the selected item changes); spin buttons and scroll bars raiseChange(clamped toMintoMax). Assigning the same value raises nothing. - Shapes, pictures, text boxes, lines, groups and charts are in
Shapes, in the workbook's drawing order (the controls after them). They haveName,Type(msoPictureand so on),Left,Top,Width,Height,TopLeftCell,BottomRightCell,IncrementLeft,IncrementTop,Fill.Type(msoFillPicturefor a shape filled with a picture),OnAction,Visible,TextFrame.Characters().Text,GroupItems(the shapes of a group) andDelete.- Position and size: As Excel does, the drawing anchor (two cells and the offsets in them, one cell and a size, or a position on the sheet and a size) is laid on the column widths and row heights as they are at that moment, in points (at 100%, a pixel is 0.75 pt; column widths become pixels from the digit width of the default font, as in Excel). When the program changes
RowHeight,ColumnWidthorHidden, shapes move and stretch with the cells. A shape in a group is placed from its position in the group's box (the transforms in the file).Range'sLeft,Top,WidthandHeightare computed the same way. TopLeftCellandBottomRightCellare the first and last cells of the anchor (as in Excel, the next cell when the shape ends on a cell border). For an anchor without cells, a shape in a group, or a shape the program moved, they are the cells at the corners.- Assignments to
Leftand the others (moving and resizing), and changes of the name, visibility and macro, are kept while the program runs and are not saved. A shape the program placed stays there: later changes of row heights and column widths do not move it. Inserting or deleting cells does not move a shape's anchor (Excel does). The position and size of form controls and ActiveX controls are not handled.
- Position and size: As Excel does, the drawing anchor (two cells and the offsets in them, one cell and a size, or a position on the sheet and a size) is laid on the column widths and row heights as they are at that moment, in points (at 100%, a pixel is 0.75 pt; column widths become pixels from the digit width of the default font, as in Excel). When the program changes
- A form control can be referenced with
Shapes(name)(Name,Visible,OnAction,FormControlType,ControlFormat).ControlFormathasValue(for check boxes and option buttonsxlOn/xlOff/xlMixed; for lists and drop-downs the number of the selected item; for spin buttons and scroll bars the value),LinkedCell,ListFillRange,ListIndex,ListCount,List,AddItem,RemoveItem,RemoveAllItems,Min,Max,SmallChange,LargeChange, andEnabled. The option buttons on a sheet are treated as one group, and the number of the selected button is written to the linked cell. Changing a form control's value does not run a macro (the same as Excel). - In
ras test, the control state is also restored to what the workbook file has, for each test.
Program operation Events (sheet, then workbook) Writing a cell's value or formula, Clear/ClearContents, paste or cut, inserting or deleting cells, sorting,RemoveDuplicates,FillDown/FillRightChange/SheetChange(targetis the changed range)A formula was recalculated by one of the above operations, a filter, hiding rows, or CalculateCalculate/SheetCalculateof that sheet (beforeChange)Range.Select,Application.GotoSelectionChange/SheetSelectionChangeWorksheet.Activate/Select(when the active sheet changes)Deactivate/SheetDeactivateof the previous sheet,Activate/SheetActivateof the next sheetWorksheets.AddNewSheet, followed by the sheet switch above (Worksheet.Copydoes not raiseNewSheet, as in Excel)Worksheet.DeleteBeforeDeleteof that sheetWorkbook.Save/SaveAsBeforeSave(settingcanceltotrueprevents saving),AfterSaveWorkbook.CloseBeforeClose(settingcanceltotrueprevents closing)Hyperlink.FollowAfter SelectionChangeand the like from selecting the link target,FollowHyperlink/SheetFollowHyperlink(targetis thatHyperlink)Workbook.Activatebetween other workbooksDeactivate/Activate- Events are not raised while
Application.EnableEventsisFalse(including duringfastMode()/suspendEvents()). Handler re-entry prevention (§12.2) is the same as the VBA build, and a write inside a handler does not call that handler again (except withreentrant: true). - An error not caught by a handler does not stop execution, as with the VBA build's RAS error dialog (
RAS_EventError). The error and the RAS location are shown in the debug console, and the original statement continues. To stop on an error, enable "Caught Exceptions" in VS Code's breakpoints. Calculateis raised for the sheet where a formula was written and for sheets that have formulas depending on the rewritten cells (not for a sheet that has only volatile functions such asNOW). When there is aCalculate/SheetCalculatehandler, calculation is performed on the spot each time a cell is rewritten.- Raising
FollowHyperlinkfromHyperlink.Follow(Excel's documentation describes it for clicking a link, and says it occurs after moving to the link target) has not been checked against a real Excel (events.linksintools/standin-check). Workbook.Open, events caused by user operations (BeforeDoubleClick/BeforeRightClick,FollowHyperlinkby a click), window events, and events of other workbooks opened withWorkbooks.Openare not raised.
- An ActiveX control can be referenced as a member of the sheet (
Files and regular expressions:
Scripting.FileSystemObject,Scripting.Dictionary,VBScript.RegExp, andADODB.Streamuse the runtime's JavaScript implementation (§14.10.5). Other COM objects cannot be created (error 429).What requires Excel: Hand-written VBA (
Application.Run), exchanging the clipboard with other applications, copying and moving sheets to another workbook or a new workbook, dialogs (GetOpenFilenameand the like), andApplication.OnTimegive error 445, saying Excel is required. An unimplemented member is error 438.Saving: The project's workbook and files opened with
Workbooks.Openare not overwritten. A workbook the program changed is saved tobuild/debug/workbooks/<workbook name>at exit (and onSave/SaveAsto an opened file), and this is shown in the debug console. Saving is done with umya-spreadsheet. The VBA project (including its signature), ActiveX controls, form controls, charts, SmartArt, PivotTables, slicers, and the like are kept, but what umya-spreadsheet does not have (the VML of form controls; "What is missing" in the fork'sFORK.md) is dropped. A workbook without macros is saved as.xlsx.Input:
InputBoxreturns the default value (or cancel if there is no default value) and shows this in the debug console.MsgBoxshows in the debug console and returnsvbOK, as when COM is unavailable.
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;
}
}
- Syntax:
debuggeris a keyword and cannot be used as an identifier (the member namex.debuggercan be used). It can be written only as a statement, and the trailing;can be omitted like any other statement. One written at the top level of a module becomes a statement ofMain(§12.4), like other top-level statements. - Debug execution (
ras build --target js): The JavaScriptdebugger;is emitted as is (the source map correspondence is the same as for other statements). In VS Code debug execution (js-debug) and the playground's developer tools (§14.10.10), it pauses at that line. In runs where no debugger is attached (ras run,ras test, the playground without the developer tools open), it does nothing. - Pause at the entry point: Each function the debug run can start (§14.10) gets
if ($rt.breakOnEntry) { $rt.breakOnEntry = false; debugger; }before the first statement of its body. The source map maps it to the line of that first statement (the function's declaration when the body is empty), so the debugger shows the pause at that line of the.rasfile.$rt.breakOnEntryis set only while the runtime'srun(entry, { breakOnEntry: true })(environment variableRAS_BREAK_ON_ENTRY=1forras-main.js) calls the entry point, and is cleared where it is first passed, so the run pauses only once, at its entry (not on recursive calls or calls from other functions). The playground's debug run (§14.10.10) andstopOnEntry: truein VS Code'slaunch.jsonuse it. - VBA build: Nothing is emitted (and no line number for
Erlis assigned). VBA'sStopis not emitted. This is so that the VBE does not open and stop in the user's Excel, leaving no effect on the distributed workbook. It also does not affect the conditions for applying loop fusion and bulk transfer (§8 to §9). - Conversion from VBA (
ras vba2ras): VBA'sStopis still not supported, as before (an error saying it is not converted).
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).
- Loading modules: The runtime (
web/src/runtime/node.ts) evaluates each module with//# sourceURL=/project/build/debug/<module>.jsattached. If the source map were resolved relative to the page's URL it would point to a nonexistent location, and the developer tools cannot read files inside the browser (the in-memoryfs), so the//# sourceMappingURL=<module>.js.mapat the end of the module is removed, and a map rewritten as follows is attached again as adata:URL (application/json, base64).sourcesis made intoras://URLs of the paths insidefs(../../src/main.ras→ras://project/src/main.ras, and the standard libraryras://stdlib/ras_collections.ras). This is to make them absolute URLs that do not depend on the page's URL.sourcesContentgets the contents of the.rasfile at that moment (for the standard library, the text in the map is used as is).mappingsand the rest are not changed. When the runtime converts an exception's location to.ras(Error.prepareStackTrace), it still reads the.mapinfs, as before.
- How to use: In the developer tools' "Sources" panel, the
.rasfiles appear underras://project/…below the worker that runs the program (worker.js). You can click a line number to set a breakpoint, step, inspect variables, and evaluate expressions in the console. The worker is recreated on every run, but breakpoints are remembered by the file's URL and remain effective in the next run. However, the worker goes away when the run ends, so the.rasfiles are shown only while a run is going on. To set breakpoints, pause the run with the "Debug Run" below, or writedebugger;(§14.10.9) and run, and it stops at that position. - Debug Run: "Debug Run (Developer Tools)" in the menu next to the Run button shows a dialog asking to open the developer tools, and runs the selected function on OK. With the developer tools open, the run pauses at the first line of that function in its
.rasfile, after the modules are initialized (the pause at the entry point, §14.10.9). While paused, set breakpoints in the.rasfiles and resume (F8). Without the developer tools open, it is the same as a plain run. The debug run passes the environment variableRAS_BREAK_ON_ENTRY=1toras-main.js. - While paused: Only the worker stops, and the page (the editor and the workbook view) can still be operated. The worker can be terminated with "Stop".
- What is shown: Local variable names are as in RAS (§14.10.1), but values are JavaScript values (the mapping of §14.10.3), and Excel objects appear as objects of the Excel stand-in (§14.10.8).
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.
When run mode is entered, the extension builds the project (
ras build --target js) and starts the program on the Excel stand-in (§14.10.8) (node ras-main.js --serve <dir>).Workbook.Openis raised at startup. The program keeps running until the mode is left, and module variables persist across operations.Operations on the sheet and the events raised (in the same order as Excel; the workbook's
Sheet…events are raised too):Operation Events Clicking a sheet tab Deactivateof the previous sheet,Activateof the selected sheetSelecting a cell, row, or column (for a drag, when released) SelectionChange(not raised for the same selection)Entering into a cell (Enter, Tab, Ctrl+Enter), deleting with Delete Calculate(the sheet where a formula was recalculated),Change. The input is treated the same as an assignment toRange.FormulaDouble-clicking a cell BeforeDoubleClick. Unless the handler setscanceltotrue, cell editing beginsRight-clicking a cell BeforeRightClick. Unless canceled, the menu opensClicking an ActiveX control GotFocus(when the focus moves),MouseDown,MouseUp(button= 1,shift, and the position within the control in points),Click. When the focus moves to another control or a cell,LostFocusClicking a shape or form control The @on("<name>.Click")handler. If there is none, the function of the registered macro (OnAction)A click also changes the control's state (see "Controls" in §14.10.8; that change raises
ChangeandClick): check boxes and toggle buttons switch on and off, and option buttons are turned on. A spin button changes the value toward the side that was pressed (up and right increase;SpinUpandSpinDownare also raised), and a scroll bar changes the value bySmallChangewith the arrows at the ends and byLargeChangebefore and after the thumb. A list box selects the clicked item. A text box or combo box shows an input field below it (and, for a combo box, the list of items too), and Enter puts the entry intoText(Change) or makes it the selected item. Form control check boxes, option buttons, lists, drop-downs, spin buttons, and scroll bars also change the value and then run the macro. A disabled control (Enabledisfalse) does nothing.Control and shape handlers are registered in the sheet module's
controlsin the JavaScript output.After every operation, the program writes out the state of the workbook and controls (
controls.json), and when cells, control states, or the active sheet change, the sheet preview is redrawn with that content (control values, captions, items, and visibility;ras book view --controls). The workbook file is not changed (a workbook the program changed is saved tobuild/debug/workbooks/when the mode is left). Returning to edit mode shows the contents of the workbook file.In run mode, only entering into and deleting cells, selection, switching sheets, and clicking objects are possible. Edits such as formatting, insertion, deletion, and undo are done by switching to edit mode. Shapes and controls are targets of clicks, and cannot be selected or moved.
The output of
debug.printis shown in the "Output" panel (RAS Debug), andmsgBoxin a notification (the stand-in responds with OK). An error not caught by a handler is shown in a notification, and the program continues. Form display is shown in the panel, as in debug execution.When the program's source is changed, toggling the mode again rebuilds it.
The playground's workbook tab also has the same switch (on the project's workbook, in its pre-run view). The program runs the same
ras-main.js --servein a Web Worker (the Excel stand-in is the wasmBook), the output is shown in the "Run output" tab, and handler errors are shown on the workbook screen. Dialogs such asmsgBoxand forms are shown on screen as in a normal run (default responses when not cross-origin isolated). A workbook the program changed is discarded when the mode is left. Run mode is left when ▶ Run or a test is started, or when the workbook is reloaded.Request format (
--serve): one JSON per line on standard input ({"id", "op", …};opisstart,activate,select,enter,doubleClick,rightClick,control, ormacro). Responses go to standard output as one JSON line starting with\u001eRAS(ok,error,errors(handler errors),cancel,where(the active sheet and selection),rev(the workbook revision),controlsRev(the control state revision)).controlalso takesaction({ index },{ part }) andtext, andmacroalso takesaction. Lines the program printed come before it. Closing standard input ends it.
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 }
]
}
kindisras.userform.- Coordinates and sizes are in points, relative to the parent container.
form.width/form.heightare the client area (MS-OFORMSDisplayedSize). Whole-point values that do not give a whole number of pixels at 96 DPI (such as 340pt = 453⅓ px; multiples of 3 always give whole pixels) are rounded to the nearest pixel when written, just as the VBE saves them at 100% display scaling. MSForms places controls using the ratio of the client area's pixel count toDisplayedSize, so a fractional value would shift controls by one pixel. Other values (such as 349.2pt = 582 px at 120 DPI, imported from a workbook saved at a different scaling) are written as is. controlsis a flat array; nesting is expressed withparentId. The containers areFrame,MultiPage(children can only bePage), andPage(the parent can only beMultiPage). The tabs of aTabStripare written in thetabsarray.- Built-in controls:
Label,TextBox,ComboBox,ListBox,CommandButton,CheckBox,OptionButton,ToggleButton,SpinButton,ScrollBar,Image,Frame,MultiPage,Page,TabStrip. RAS-specific ones areProgressBar(written as a combination of labels; §14.11.13) andFilePicker(a text box and button pair; §14.11.14). - The details of the common properties (
left/top/width/height/tabIndex/zIndex/enabled/visible), the per-type properties (caption/text/value/selectedIndex/tabs, etc.), and the appearance properties (font/foreColor/backColor/textAlign/borderStyle/pictureAlignment/pictureSizeMode), along with which controls they apply to, follow xlflow's UserForm Specification. Colors are written as{ "kind": "rgb", "value": "#203040" },{ "kind": "system", "value": "buttonFace" }, or{ "kind": "ole", "value": "0x8000000F" }. - The validation result codes are
UFY001(JSON syntax) andUFV001toUFV028(UFV024is for the progress bar (§14.11.13),UFV025for the file picker (§14.11.14),UFV026for anchors (§14.11.16),UFV027for the form's minimum and maximum size (§14.11.17), andUFV028for placeholders (§14.11.18)). Messages are in Japanese.UFV022(warning) means that theheightof a single-lineTextBox/ComboBoxis too small for one line of the font. MSForms does not enlarge the field to fit the font, so in Excel the text is clipped and a line is left at the edge. The required height is the height of one line, derived from the font size and type (MS UI Gothic is 1x, Meiryo UI is 1.33x, Meiryo is 1.6x, and so on), plus 5.25pt (4.5pt for the border and padding, and one more pixel so that Excel does not take the line for overflowing and draw a line along the bottom edge while text is being typed (IME composition)), rounded up to a whole pixel (0.75pt). If no font is specified, it is computed as MS UI Gothic 9pt. The designer automatically enlarges a field to this height when an edit changes its height or font.UFV023(warning) means thatborderStyle1 (Single) and a non-zerospecialEffectwere both written. MSForms draws only one edge, and in the VBE setting one resets the other (setting Single makes it flat; setting a 3D effect removes the border). When writing,borderStyletakes priority andspecialEffectis set to 0. When only one of them is written, the result matches the VBE: a control with a Single border is written flat, and anImagewithspecialEffectwritten (new ones have a Single border) is written with no border.
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 / scrollTopWhen 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)
"picture": { "path": "forms/assets/logo.bmp" }specifies an image file. The path is relative to the project root (the folder containingras.toml); paths outside the root (.., absolute paths, drive specifications) are not allowed.- The supported formats are BMP, JPEG, PNG, GIF, WebP, TIFF, and ICO. A file can be up to 16 MiB. The format is determined by the file contents, not the extension. Metafiles (WMF / EMF) cannot be used.
- Only two forms are embedded in the designer storage as they are, the ones xlflow has confirmed on a real Excel that MS-Forms can read: BMP (a 40-byte
BITMAPINFOHEADER, 24-bit or 32-bit, uncompressed) and JPEG. Files in these forms are embedded as aStdPicturewith their contents unchanged (up to 16 million pixels). - Other images (PNG, GIF, WebP, TIFF, ICO, and BMPs such as 8-bit, RLE-compressed, or V4 / V5 header ones) are decoded on every write and converted to a 24-bit BMP before embedding. The original file is not modified, and
picture.pathcan keep pointing to the original file.- Transparent areas are composited over the
Image'sbackColor(BMP has no transparency). WhenbackColoris a system color, the Windows default color is used (buttonFaceis#F0F0F0); when it is unspecified,buttonFaceis assumed. - For an animated GIF the first frame is used; for an ICO with multiple images the largest is used.
- The converted BMP can be up to 16 MiB (roughly 5.5 million pixels). A larger image is an error (make it smaller, or use JPEG).
- The same file and the same background color always produce the same BMP (so the design hash does not change).
- Transparent areas are composited over the
- The original file is not needed to open the workbook.
"picture": { "remove": true }means no picture (the same as not writingpicture).- A control's picture is written to the
Pictureof its record (StreamDataofMorphData/CommandButton/Label); the background of aFrame,Page, or form is written after the font (TextProps) in eachfstream.pictureTilingis represented by aFormPropMaskbit (24) that has no value. mouseIconaccepts icon (ICO) and cursor (CUR) files, which are embedded as aStdPicturewithout conversion ([MS-OFORMS] 2.4.13 says aStdPicturecan hold an icon). BMP / JPEG, which MS-Forms can hold as they are, are also accepted, without conversion. For the form and forFrame/Page, it is written before the font in thefstream.
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;
}
this: Inside functions in the code-behind,thisrepresents the form (VBA'sMe). Its type is the form-name type, which has the members ofMSForms.UserForm(caption,hide(),controls, and so on) and the controls from the.form.json. Refer to a control asthis.<control name>; its type is a built-in control type such asMSForms.TextBox(ProgressBar/FilePickerare the bundled classes of the same name (§14.11.13, §14.11.14), and custom controls areobject). A member that the form does not have is an error (E0202).- Type definitions: The Microsoft Forms 2.0 types (
MSForms.UserForm,MSForms.Control, each control, event argument types such asMSForms.ReturnBoolean, and thefm…enums),load/unload/loadPicture, and constants such asvbModeless/vbFormControlMenuare bundled (stdlib/msforms.d.ras). Names are spelled in camelCase, as in the other type definitions (§15.3.1). In the generated VBA they are declared with the namespace, as inMSForms.TextBox. - Events: A function with
@on("<control name>.<event>")receives the event. The form's own events areUserForm.<event>(Initialize,Activate,QueryClose,Terminate, etc.). The compiler generates event procedures with the same declarations as the VBE (Private Sub btnOK_Click(),Private Sub txtName_Exit(ByVal Cancel As MSForms.ReturnBoolean), and so on) in the form's code module, and calls the handler from them. The events and arguments follow the list xlflow collected in the VBE (shared with the VS Code extension).- As with document module events (§12.2), multiple handlers can be written for the same event (called in declaration order), and an event that the handler itself fires during its execution is ignored (this can be lifted with
@on("…", { reentrant: true })). An error not caught by a handler is shown in the RAS error dialog. - A handler receives arguments from the start of the event's argument list, in order, and may omit trailing ones. For a
ByValobject argument (such asMSForms.ReturnBoolean), assign tovalueto return the result. To modify aByRefnumeric argument such asCancelofQueryClose, declare it asbyref cancel: short(shortis used forIntegerto match the type of the event procedure's declaration). - Errors: no such control (
E0613), an event the control does not have (E0611; page events are received on the parentMultiPage), too many arguments (E0612), an argument of a type that does not fit (E0301), and a function name equal to the generated event procedure name (btnOK_Click) (E0614).
- As with document module events (§12.2), multiple handlers can be written for the same event (called in declaration order), and an event that the handler itself fires during its execution is ignored (this can be lifted with
- Variables: Top-level
let/constbecome the form's module variables (Private). Initial values are set at the start ofUserForm_Initialize(generated even when there is noInitializehandler). They are held per form instance. - Instances and return values: If you write
function constructor(...), you can create an instance with arguments usingnew frmInput(...), and receive the value ofthis.close(value)fromshowModal()(§14.11.9). - Exporting:
export functionbecomes aPublicmember of the form, callable from other modules through the form's default instance, as infrmInput.enteredName(). The form name is a global usable from anywhere (the default instance), used as infrmInput.show(). Functions that are not exported arePrivate. Code-behind functions do not become macro entry points (and are not wrapped as in §12.4). - Exported variables (
export let):export let accepted = false;becomes aPublicvariable of the form's module, readable and writable from other modules as a member of the form (frmInput.acceptedfor the default instance,f.acceptedfor an instance created withnew; inside the code-behind, eitheracceptedorthis.acceptedworks). The value is held per instance, and the initial value is set at the start ofUserForm_Initialize, like other variables. The type annotation can be omitted (it is inferred from the initial value). Names that cannot be used as VBA identifiers get a_appended in the output, as with standard-module variables (name→name_).export constcannot be written (a VBA object module cannot havePublic Const;E0630). Array variables (other thanany[]) and struct variables also cannot beexported (they cannot be made public either;E0643). Export a function that returns the value instead.- A name equal to a control or an exported function (case-insensitive) cannot be used (
E0101). A variable that is notexported cannot be referenced from other modules (E0202).
WithEvents: Events of a top-level variable can be received with@on("<variable name>.<event>")(§12.2.2).- Handlers attached at run time: To attach the same handling to many controls, attach it in the
Initializehandler, as inthis.controls.on("Change", (c) => …),[this.txtA, this.txtB].on("Change", …), orthis.btnOK.on("Click", …)(§12.2.3). They are detached when the form closes. - What cannot be written (
E0630,E0632): top-level statements, classes, interfaces, structs,declare module,exported constants, enums, and type aliases,@macro/@init/@udf/@ribbon, and extension methods. Put anything to be shared in a module insrc/andimportit (code-behind canimport, but code-behind cannot beimported). - A
forms/<Name>.raswithout a.form.jsonis an error (E0631). - Debug runs (§14.10) show the form in a VS Code panel and run the code-behind (§14.10.7). Showing and running the form in Excel itself is "Run in Excel" (§14.11.8).
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)
- The designer storage (
<Name>/f,o,\x01CompObj,\x03VBFrame, the per-containeri<ID>/substorages, and thexofMultiPage) 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 incrates/ras-form/src/scalars.rs).tools/excel-checkis used to compare against a real Excel. - The code module
VBA/<Name>is created. A new form gets a form attribute header containingVB_Base = "0{GUID}{GUID}"(two new GUIDs); for an existing form, the header is kept and only the code is replaced. - 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.designis the hash of the designer storage andcodeis 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). - A
BaseClass=<Name>line is added to thePROJECTstream, and a reference to the Microsoft Forms 2.0 Object Library (MSForms) is added to thedirstream if it is missing. - 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".
- 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 (
--overwriteallows 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 ---
- An item of
listis a string, or an array of strings, one per column (1 to 10 columns;["001", "Yamada"]). For an item with multiple columns, the first column is set withAddItemand the rest with.List(.ListCount - 1, <column>) = …(MSForms can set up to 10 columns withAddItem/Liston a list not linked to cells). The number and width of the displayed columns are specified withcolumnCount/columnWidths. - The procedure
RAS_FormInitthat sets the items is generated in the RAS-managed area at the end of the module (enclosed by'--- RAS BEGIN ---/'--- RAS END ---). It is placed after the declarations, so it does not interfere with the code-behind'sOption Explicitor module-level declarations. - If the code-behind has no
UserForm_Initialize, aUserForm_Initializethat only callsRAS_FormInitis also generated in the managed area. - If the compiled code has a
UserForm_Initialize(generated when there is an@on("UserForm.Initialize")handler or variable initialization), a single lineRAS_FormInit '--- RAS ---is inserted at its start. selectedIndexis-1(no selection) or an index within the range oflist. A control with nolistcan only have-1(UFV020).listcannot be written for a control withrowSourcespecified (UFV021), because MSForms refusesAddItemon a list that reads its items from a cell range.- In item strings, control characters and characters that cannot be represented in the code page are output as
ChrW(n). - In the code-behind, you cannot write a procedure named
RAS_FormInitor the marker lines of the managed area (error).
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.
- If no name is given, all forms in the workbook are targeted. A form for which files of the same name already exist in
forms/is not written out (--forcereplaces them). - Design: The designer storage is read and turned into a FormSpec (a port of xlflow's projection, extended to import the properties the generating side can write).
Tag/ControlTipText(tag/controlTipText) andGroupName,MaxLength,BorderColor(properties) are imported too. The results of reading forms saved by Excel (crates/ras-form/tests/data) are verified incrates/ras-form/tests/snapshot.rs. A control with no saved caption getscaption: "", and if the form's caption is not in the form record, theCaptionin the designer block (VBFrame) is used. - Images: Control and form pictures (those saved as BMP / JPEG) are written to
forms/assets/<Name>.<control name>.bmp|jpg(for the form's own,forms/assets/<Name>.bmp|jpg) and referenced bypicture.path. Mouse icons are written toforms/assets/<Name>[.<control name>].mouseIcon.ico|curand referenced bymouseIcon.path. Excel saves a loaded JPEG as a BMP too, so extracted images are often BMPs. Images converted at write time (such as PNG) also come out as the converted BMP when extracted. - Code: The VBA from the code module, minus the
Attributelines, is converted to RAS and written toforms/<Name>.ras(see below). For a form written by RAS, the marker line, the RAS-managed area, and the insertedRAS_FormInitcall are removed before conversion.- For a form written by RAS (it has a marker line) when
forms/<Name>.rasalready exists, the code-behind is not rewritten (the code was compiled from that file). Only the design is re-imported. Edits to the code in the VBE are not imported.
- For a form written by RAS (it has a marker line) when
- VBA to RAS conversion: The syntax is rewritten into RAS (
ras_compiler::vba2ras).- An event procedure
<control>_<event>becomes a function with@on("<control>.<event>")(named likebtnOKClick),Mebecomesthis, and a control reference becomesthis.<control name>..valueis added for controls used through their default member (txtName = "x",If chkAll Then) and for arguments such asMSForms.ReturnBoolean(Cancel = True). - Host functions and members use RAS spelling (
MsgBox→msgBox,.ListIndex→.listIndex), and types become RAS types (Long→int,Integer→int(shortfor event arguments),Range→Excel.Range,TextBox→MSForms.TextBox). &concatenation becomes a template literal,/becomes real division (as doubleis added for two integers),=/<>become==/!=, andAnd/Or/Notbecome&&/||/!(&/|/~for numeric operations).If/Select Case(turned into anifchain) /For/For Each/Do … Loop/While … Wend/With(the target is repeated, or put in a temporaryconst) /Exitare converted.On Error Resume Next…On Error GoTo 0becomestry { … } catch { resume; }, andOn Error GoTo <label>…Exit Sub/<label>:… becomestry { … } catch (e) { … }(Err.Number/Err.Descriptionin the handler becomee.code/e.description).- The return value of a
Function(FunctionName = value) becomes areturnor a local variableresult. BecauseByValis the default for arguments, an argument withoutByValbecomesbyrefonly if it is assigned to inside the procedure. - For code of a form written by RAS (when extracting into a project with no
.ras), generated event procedures are turned back into@on, and variable initialization (RAS_ModInit) is turned back into initial values. Line numbers (forErl) are dropped. Propertybecomes accessors (get/set; §3.6),ParamArraybecomes variadic arguments (§3.5),Likebecomeslike(…),NullbecomesdbNull,Emptybecomesnull, aStaticvariable becomes a file-level variable named after the procedure, and aPublicvariable becomesexport let. Arrays keep their declared lower bound, so they becomeany(Dim a()→dynamicArray(),ReDim→redim/redimPreserve,a(i, j)→a[i, j],Erase→erase; §4.6). Assignment to a property that takes arguments (lst.Selected(i) = True) is written as is (§3.6.3)..valueis added where aRangeis assigned to, as inCells(…) = x. When the right-hand side of an assignment withoutSetmight be an object, it is wrapped inletValue(…)(§14.7.4).- A forward
GoTo(GoTo Finally…Finally:) turns everything up to the label into a labeleddo { … } while (false);and theGoTointo abreak.Mid(s, i, n) = xbecomes an expression usingleft/mid. ADiminside a block becomes a declaration at the top of the procedure (because VBA variables are scoped to the whole procedure). - What cannot be converted (a backward
GoTo, date literals, user-defined types of sheets and forms,Declare, conditional compilation, custom events, and so on) is left as the original line in a// TODO(VBA): <reason>comment, and a warning (file and line) is shown in the command output. The converted result does not always compile as it is. Check it withras checkand fix it. In an import through sync (§14.7.1), such code is imported as VBA in avbablock, and type-based rewriting is also applied (§14.7.4).
- An event procedure
- List items: They are not saved in the workbook, so they cannot be extracted. When
--forcereplaces an existing.form.json, thelist/selectedIndexof aComboBox/ListBoxof the same name and thepicture.pathof images are carried over from the existing file (for the image, only if converting the file at that path by the same rules as at write time yields the same result as the workbook's image; a form that specified PNG or the like keeps pointing to the PNG even after re-import). - What cannot be imported: Properties that FormSpec cannot represent (
helpContextId,accelerator,scrollBarsofFrame, and so on) have their names recorded inunsupportedfor each control, and a warning is shown in the command output. The font contents (textProps) are not reported if they are only things that come back identical when written back (eachfontitem, thepitchAndFamilythe VBE saves, theCFE_AUTOCOLORadded to bold and so on, the muted-color setting of disabled controls, and the centeredCommandButton). These become their default values when written back fromforms/. Non-built-in controls (ActiveX) are recorded astype: "Control"and cannot be generated. Images other than BMP / JPEG / icons (such as metafiles) cannot be extracted, andpicture(mouseIcon) remains inunsupported(in this case the form cannot be generated until you write a replacement image or{ "remove": true }). - Extraction alone does not change the workbook. To replace a form created in the VBE with the contents of
forms/, runras pack --overwrite(orras sync --overwrite). - Forms not in
forms/are also imported and replaced by the same conversion during sync (ras sync,ras pack, etc.; §14.7.1).
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 |
- Import: The form is written to a temporary folder as a
.frm(designer block, attributes, code) and a.frx(a compound file containing a 24-byte header and the designer storage), and loaded withVBComponents.Import. The contents of the.frxare the same as the designer storage thatras packwrites. - Re-import: The existing form is renamed to a temporary name (such as
RasOld1), then the new form is imported, and the old form is deleted after the whole sync succeeds. If it fails midway, the new form is deleted and the old form's name is restored (the all-or-nothing behavior of §14.6). - Loaded forms: A form to be re-imported and a form whose code is to be rewritten are closed before writing. The designer window open in the VBE is closed, and loaded instances (a form merely hidden with
Hide, or one shown modelessly) areUnloaded (because the VBE cannot rename a loaded form).Unloadadds a temporary standard module (RAS_SyncUnload) to the project, runs it withApplication.Run, and deletes it afterwards. The form'sQueryClose/Terminatehandlers are executed. If any form cancels closing inQueryClose, nothing is written and it is an error. - Deciding on changes: The VBE reformats and retains code, so the retained code cannot be compared with the code that was written. The decision uses the hash recorded in the marker line.
- Editing a form's design or code directly in the VBE does not change the marker line, so the edit stays until
forms/next changes (drift detection is not performed). To keep design edits made in the VBE, save the workbook and import them intoforms/withras form pull --force(code edits are not imported; §14.11.6). - Nothing is written while a macro is running or in break mode (§14.6). Re-importing a form resets that form's instances and the project's state.
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.
Application.Runcannot call procedures in a form's code module, andVBA.UserFormscan only be used from code inside the project. So when the project has forms, the following procedure is output to the runtime (RAS_Runtime) and called withApplication.Run "'<workbook name>'!RAS_Runtime.RAS_ShowForm", "<form name>".Public Sub RAS_ShowForm(ByVal name As String) VBA.UserForms.Add(name).Show End SubExcel is brought to the front before the form is shown (if Windows does not allow the foreground switch, the taskbar button flashes).
A call that shows a modal form does not return until the form is closed. Meanwhile, sync (including the sync on every save) waits.
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}`);
}
new FormName(arguments): Creates a new instance of the form. After the module variables are initialized and theInitializehandler runs, the code-behind'sfunction constructor(...)is called with the arguments.constructoris notexported and is written without type parameters or a return type (E0633). Default argument values and named arguments work as in ordinary functions. For a form with noconstructor, writenew FormName()with no arguments (passing arguments isE0402). Each instance has its own module variables (separate from the default instance too).The form type: The form name is both the default instance and a type name, so you can write
const f: frmInput = new frmInput("x");andfunction edit(f: frmInput).showModal(): Shows the form modally, waits until it is closed, and returns the value passed tothis.close(value). When it returns, the form has been unloaded (Terminateoccurs). If the form is closed other than throughclose(the title bar×, orthis.close()with no value), it returns the default value of the return type ("",0,false,null, and so on). It can also be used on the default instance (frmInput.showModal()).The return type: Determined from the types of the values of all
this.close(value)calls in the code-behind (as with function return type inference, differing types giveE0302; align them withas). If noclosepasses a value, it isvoid. Structs cannot be passed (E0636). The return value ofshowModal()cannot be used from within the same form's code-behind (E0634).this.close(value?): Can only be written inside the code-behind (E0635). A form shown withshowModal()is hidden and control returns toshowModal(); any other form (one shown withshow()) is unloaded (the same asunload(this)).unload(this): Writingunload(this)in the code-behind of a form that usesshowModal()/this.close()gives a warning (W0631). Referencing a module variable of an unloaded form makes VBA load the form again (Initializeoccurs), so the return value ofshowModal()cannot be guaranteed. Close withthis.close(value)/this.close().The
×button: A form shown withshowModal()is hidden, not unloaded, by the×button (unless theQueryClosehandler cancels it), and control returns toshowModal()(because referencing a member of an unloaded form makes VBA load the form again).Generated VBA: The following is generated in the code module of a form that uses
showModal()/close.newbecomes the factory functionNew_<form name>in the generated moduleRAS_Glue(constructoris output asFriend Sub RAS_Construct).' frmInput Private RAS_Result As String Private RAS_Modal As Boolean Friend Sub RAS_Construct(ByVal name_ As String, Optional ByVal limit As Long = 20&) ... End Sub Friend Function RAS_ShowModal() As String RAS_Modal = True Me.Show vbModal RAS_Modal = False RAS_ShowModal = RAS_Result Unload Me End Function Friend Sub RAS_Close(ByVal ras_value As String) RAS_Result = ras_value If RAS_Modal Then Me.Hide Else Unload Me End Sub Private Sub UserForm_QueryClose(ByRef Cancel As Integer, ByRef CloseMode As Integer) ...(the QueryClose handler) If RAS_Modal And Cancel = 0 And CloseMode = vbFormControlMenu Then Cancel = 1: Me.Hide End Sub ' RAS_Glue Public Function New_frmInput(ByVal name_ As String, ByVal limit As Long) As frmInput Set New_frmInput = New frmInput New_frmInput.RAS_Construct name_, limit End Function ' Caller name_ = RAS_Glue.New_frmInput("Yamada", 10&).RAS_ShowModal()When
ras form pullconverts the code of a form written by RAS, it turns these back intofunction constructorandthis.close(...).The same works in debug runs (§14.10.7).
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
- The display zoom itself (text and controls growing to match the display scaling) is not changed.
- Differences under 1 point (pixel rounding) are not corrected. At 100% display, nothing is done.
- The value is the size rounded to 96 DPI pixels, as when writing (§14.11.1; 340pt becomes 339.75pt).
- If the code-behind's
Initializehandler changesthis.widthor similar, that takes priority (RAS_FormInitruns before the handler).
14.11.11 Limitations
- Custom ActiveX controls cannot be generated (it is an error).
- Editing a form's design or code in the VBE is not reflected in
forms/automatically. The design can be imported withras form pull --force. Unless it is imported, the next timeforms/is changed and written, it is replaced with the contents offorms/(drift detection is not performed). - In the code-behind,
@on("<control name>.<event>")can handle only events of built-in controls. To attach the same handler to multiple controls (an array of controls), useon(§12.2.3). - Importing forms during live sync (
VBComponents.Import) cannot be tested automatically in an environment without Excel. The structure of the.frxis checked against files written by Excel (crates/ras-form/tests/project.rs).
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);
}
Schemas (
ValidationSchema): Create one withz.string()/z.int()/z.number()/z.date()/z.boolean()and chain rule methods (each returns the same schema). A message passed toint/number/datebecomes the error for input that does not match the type ("abc").Method Rule Default message required(msg?)Not empty (blank-only counts as empty). For boolean, it is checkedPlease enter a value / Please check the box optional()Cancels required()min(n, msg?)/max(n, msg?)For string, the number of characters; forint/number, the value; fordate, the date (serial value;cDbl(dateSerial(…))) is at least / at mostnEnter at least ncharacters… / Enter a value of at leastn…length(n, msg?)The number of characters is exactly nEnter exactly ncharacterspositive(msg?)/nonnegative(msg?)Greater than 0 / 0 or greater regex(pattern, msg?)Matches the regular expression ( VBScript.RegExpsyntax)The format is not valid email(msg?)Email address format Enter an email address oneOf(values, msg?)One of values(string[])Select from the list refine(fn, msg)fn(value)istrue. It can also refer to the values of other controls (this.txtA.text)noTrim()Validates without trimming leading and trailing whitespace (by default it is trimmed) check(value)Validates a string and returns the error message ( ""if none) (usable outside forms too)- Values are validated as the control's string. For
TextBox/ComboBox/ListBoxit istext; forCheckBox/OptionButton/ToggleButtonit is"true"if checked (""forNull). - When the field is empty, no rules other than
required()are checked (a non-required field may stay empty). Rules are checked in the order written, and the message of the first one that fails is shown.
- Values are validated as the control's string. For
-
Member Behavior rule(control, schema, errorLabel?)Attaches a rule to a control (replacing any existing one). For a control that has already been committed, the display is refreshed at once with the new rule remove(control)Removes the rule and clears the error being shown has(control)Whether it has a rule validate(control)Validates one control and shows the result; trueif validvalidateAll(focus = true)Validates all controls that have rules and shows the results; trueif all are valid. Iffocus, moves focus to the control of the first error (in the order rules were attached). Hidden and disabled (enabled == false) controls are not validated, and their errors are clearedisValid()Returns whether everything is valid, without changing the display error(control)The error being shown ( ""if none)setError(control, msg)Shows an error directly ( ""clears it). Use it for the results of checks that rules cannot expressreset()Clears all errors and returns to the uncommitted state (rules are kept) errorColorText color of the labels it creates (default 0x0000CC, red)commit(control)/edit(control)/commitActive(container)Called from the event procedures the compiler generates (see below) The label that shows the error: If you pass a label you prepared yourself as the third argument of
rule,errorLabel, the error is shown there (form.rule(this.txtTel, z.string().regex("^[0-9-]+$"), errorLabel: this.lblTelMessage); it can be written as a named argument (§3.3)). The label you pass keeps its position, color, and font as they are; onlycaptionandvisibleare changed. If you callruleagain with a different label, the error on the previous label is cleared and shown on the new one. If you call it again with the label omitted, the previous label continues to be used. IferrorLabelis omitted,<control name>Error(txtNameErrorfortxtName) in the same container as the control (form,Frame, orPage) is used. A label placed in the design keeps its position, color, and font; onlycaptionandvisibleare changed. If there is none, it is created the first time an error is shown, withcontrols.add("Forms.Label.1", "<control name>Error"): directly below the control (top= the control's bottom edge + 1pt,left/widththe same as the control, height 1.5 times the font + 2pt), with a transparent background (fmBackStyleTransparent), the text colorerrorColor, and the same font as the control. Leave room in the design for the label that will be created. When there is no error, the label is hidden.Connection to events: When the type of a module variable in the form's code-behind is
FormValidator, the compiler generates the following event procedures for the form's controls (calling them after any@onhandler).Exitof anMSFormscontrol cannot be received withWithEvents(§12.2.3), so the compiler generates it. While the variable isnull, nothing happens.Control Event What it calls TextBox/ComboBox/ListBox/CheckBox/OptionButton/ToggleButtonExit(input committed)commit: marks it committed and validatesSame as above Changeedit: re-validates a committed control. ForCheckBox/OptionButton/ToggleButton/ListBox, a change is itself a commitFrame/MultiPageExitcommitActive: commits the control inside that had focus (because MSForms does not raiseExitfor the controls inside when focus leaves the frame)Private form As FormValidator Private Sub txtName_Exit(ByVal Cancel As MSForms.ReturnBoolean) On Error GoTo RAS_OnError If Not form Is Nothing Then form.commit Me.txtName Exit Sub RAS_OnError: RAS_EventError "frmOrder.txtName_Exit", Err.Number, Err.Source, Err.Description End SubWhen to attach rules: Normally in
constructor(or theInitializehandler). When rules change depending on earlier input, callrule/removein a handler such as the control'sChange. If you read other controls' values inside arefinefunction, validation uses their values at that moment on every commit.Generated VBA: Outputs the standard module
RAS_Validation(functions that create schemas such asz.string()) and the class modulesFormValidator,ValidationSchema,RAS_ValidationField, andRAS_ValidationCheck. Therefinefunction becomes an escaping arrow function (§4.3).Debug runs: The same works in form debug runs (§14.10.7). The runtime supports
Controls.Add("Forms.<type>.1") andControls.Removefor controls added that way, and draws the added controls in the panel.Placing a
FormValidatorin a variable of a module insrc/does not connect events (in that case, callcommitand so on yourself).When the form is closed with the
×button,Exitdoes not occur (no validation).
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;
Design properties: The common properties (
left/top/width/height/enabled/visible/tag/controlTipText; there is notabIndex) and the following. The default size is 200×24 points.Property Meaning If omitted captionThe text shown at the upper left ""valueThe current value (between minandmax)0 min/maxThe range of values ( maxis greater thanmin)0 / 100 showValueShow the percentage ( 56%) at the upper righttruebarHeightThe thickness of the bar (points) 4.5 (6 pixels) barColorThe color of the bar The system color highlight(see below)trackColorThe color of the bar's background #D7D7D7(see below)foreColor/fontThe text color and font of caption(fontis also used for the percentage)The label default valueColorThe text color of the percentage grayTextThe validation result code is
UFV024(maxis not greater thanmin,valueis out of range,barHeightis 0 or less, an invalid color specification, or one of the label names below is the same as another control).Writing:
ras pack/ras syncwrite a progress bar as four labels stacked at the same position.Label Position Contents <name>_TrackThe bottom edge. Height barHeight, the full widthThe background ( trackColor). ItsTagholds settings that a label cannot express (RAS.ProgressBar|min=0|max=100|value=56|showValue=1)<name>_BarSame as _Track. The width is the percentage (rounded to pixels)The bar ( barColor). Hidden when the value is at or belowmin<name>_CaptionThe top edge. The height is the total minus the bar and a 3pt gap; the width is the total minus the 36pt for the percentage caption(transparent background)<name>_ValueThe upper right. Width 36pt The percentage (right-aligned, transparent background; hidden if showValueisfalse)The label names are fixed as
<name>_Trackand so on, so a control with these names cannot be placed on the form (UFV024).ras form pullturns the four labels whose_TrackTagstarts withRAS.ProgressBarback into a progress bar when importing.Operating it from code:
this.<name>in the form (frmUpload.<name>from other modules) is an object of the bundled classProgressBar(crates/ras-compiler/stdlib/progressbar.ras, written in RAS).Member Meaning value/min/maxThe value and range ( double). Values outside the range can be set, and the bar stops at the endfraction/textThe progress (0 to 1; read-only) and the string shown at the upper right ( "56%"; rounded)caption/showValueThe upper-left text, and whether the percentage is shown barColor/trackColor/foreColor/valueColorColors (VBA color values, such as rgb(0, 120, 215))barHeightThe thickness of the bar (points) left/top/width/heightPosition and size (points). Changing them rearranges the labels visible/enabled/tag/controlTipTextSame as a control ( tagis theTagof_Caption)There are no events (
@on("pbUpload.Click")is an error).Generated VBA:
Public pbUpload As ProgressBaris declared in the form's code module and connected to the labels at the start ofUserForm_Initialize(afterRAS_FormInitand before the code-behind's handlers). A code module for this is output even for forms with no code-behind. The class moduleProgressBarand the standard moduleRAS_ProgressBarare output only when a progress bar is placed. It can also be used from hand-written VBA, as infrmUpload.pbUpload.Value = 56.Public pbUpload As ProgressBar Private Sub UserForm_Initialize() RAS_FormInit '--- RAS --- On Error GoTo RAS_OnError Set pbUpload = New ProgressBar pbUpload.RAS_Attach Me, "pbUpload" …Default colors: If
barColoris omitted, the workbook is written with the system colorhighlight(vbHighlight, the background of selected items;#0078D7on Windows 10 / 11). The designer draws it as#0078D7. The defaulttrackColor,#D7D7D7, is the gray whose contrast ratio with the form's default background (buttonFace,#F0F0F0) is the same as that of#E5E5E5on white (about 1.26). Anaccent=in theTagof workbooks written earlier is ignored.Debug runs: The form panel (§14.10.7) draws it as the same four labels as when writing, and operates it with the same class.
Designer:
ProgressBaris in the "Standard" section of the toolbox. It is drawn on the canvas with the same layout as when written, can be moved and resized like other controls, and the properties in the table above can be edited in the property grid.
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();
}
Design properties: The common properties (
left/top/width/height/tabIndex/enabled/visible/tag/controlTipText) and the following. The default size is 200×18 points. When the height is too small for the font, it isUFV022(warning), as withTextBox.Property Meaning If omitted textThe path in the box ""dialogTypeThe kind of dialog ( msoFileDialogType; 1: Open, 2: SaveAs, 3: FilePicker, 4: FolderPicker)3 title/buttonNameThe dialog's title and the text of its confirm button The dialog default allowMultiSelectAllows choosing multiple files ( dialogType1 and 3)falseinitialFileNameThe location where the dialog opens when the box is empty ""initialViewThe dialog's view style ( msoFileDialogView; 0 is the dialog default)0 filtersFile types: [{ "description": "Excel workbooks", "extensions": "*.xlsx; *.xlsm" }](dialogType1 and 3)The dialog default filterIndexThe file type selected first (from 1) 1 buttonCaption/buttonWidthThe button's text and width (points) .../ 24lockedPrevents editing the box directly (it can still be chosen with the button) falseforeColor/backColor/fontThe box's colors and font ( fontis also used for the button)The TextBoxdefaultThe validation result code is
UFV025(dialogTypeis not 1 to 4, the shape offiltersis wrong or it is written fordialogType2 or 4,filterIndexis outside the range offilters,allowMultiSelectis written fordialogType2 or 4,buttonWidthis 0 or less, or one of the part names below is the same as another control).Writing:
ras pack/ras syncwrite it as a text box<name>_Text(whose width is the total minus the button's width) and a button<name>_Buttontouching its right edge (withTakeFocusOnClickset toFalse, so focus stays in the box when it is pressed). The dialog settings are held in the button'sTag(RAS.FilePicker|type=3|multi=0|title=…|filters=Excel workbooks,*.xlsx%3B *.xlsm;% | = ; ,in values are written as%25and so on). Controls with the part names cannot be placed on the form (UFV025).ras form pullturns these two back into aFilePickerwhen importing.Operating it from code:
this.<name>in the form (frmImport.<name>from other modules) is an object of the bundled classFilePicker(crates/ras-compiler/stdlib/filepicker.ras).Member Meaning browse()Shows the dialog, puts the chosen paths in the box, and returns them as a string[]. On cancel, it leaves the box unchanged and returns an empty array (lengthis 0). If the box has a path, the dialog opens at that location (for FolderPicker, with a trailing\added so it opens inside that folder)pathsThe array of paths in the box (read-only). Split by ;and line breaks, with surrounding whitespace and the"at both ends (added by Explorer's "Copy as path") removed. An empty box gives an empty arraypathThe first path in the box ( ""if none). Assigning sets the box to that pathtextThe string in the box itself. Multiple paths are separated by ;dialogType/title/buttonName/allowMultiSelect/initialFileName/initialView/filterIndexDialog settings (the properties of the same name on FileDialog). They start from the design valuesaddFilter(description, extensions)/clearFilters()Adds a file type / removes all of them buttonCaption/buttonWidth/locked/visible/enabled/left/top/width/height/tag/controlTipText/setFocus()Same as a control ( tagis the box'sTag)- When focus leaves the box after a path is pasted (
Exit), the text is tidied by the same rules aspathsand rewritten separated by;("C:\a b\x.xlsx"becomesC:\a b\x.xlsx). ;can be used in Windows file names, but in the box it is treated as a separator.- From VBA, the return value of
browse()isString(), and on cancel it is an array with no elements (unallocated) (callingUBoundin hand-written VBA gives error 9). From hand-written VBA, checkfpBook.Path(on cancel it stays as it was before choosing), or wrapUBoundafterBrowsein error handling.
- When focus leaves the box after a path is pasted (
Events:
@on("<name>.<event>")receives events of the box (TextBox) (Change,Exit,KeyDown, and so on; the generated event procedure isfpBook_Text_Change). The button'sClickand the box'sExitare passed to the class from event procedures the compiler generates, before the form code's handlers (fpBook_Button_Click→fpBook.RAS_Click).Changealso occurs when a path is chosen with the button or assigned topathand so on.Generated VBA: As with the progress bar (§14.11.13),
Public fpBook As FilePickeris declared in the form's code module and connected to the parts inUserForm_Initialize. The class moduleFilePickerand the standard moduleRAS_FilePickerare output only when a picker is placed.Debug runs: The form panel (§14.10.7) draws it as the same box and button as when writing, and operates it with the same class. In runs without Excel,
ShowofApplication.FileDialogresponds the same asgetOpenFilename(getSaveAsFilenamefor SaveAs) (ras run --open-file,mockGetOpenFilenamein tests; multiple paths as an array, cancel asfalse). With no response,FileDialoggives an error saying Excel is required.Designer:
FilePickeris in the "Standard" section of the toolbox. It can be moved and resized like other controls.filterscannot be edited in the property grid (write it in JSON).
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();
}
How it works:
importing the moduledialogadds to the project an empty form with no controls,RAS_Dialog(a bundled design and code-behind), andras pack/ras syncwrite it to the workbook together with the other forms. Each time one is shown,Dialog/Progresscreates an instance withnew RAS_Dialog(), lays out controls withcontrols.add, and connects events withon(§12.2.3). It is unloaded when closed.RAS_Dialogdoes not appear informs/, andras form pull(with no name given) does not extract it either. A form with the same name cannot be placed in the project (if you do, that one is used and the dialogs do not work).choose(message, buttons, title?, cancel = -1, enter = 0): Placesbuttonsright-aligned undermessageand returns the number of the button pressed.cancelis the button pressed by Esc (the return value is then -1), andenteris the button pressed by Enter (MSFormsCancel/Default). If the title is omitted, it isMicrosoft Excel.new Dialog(title?, message?): Items are laid out in a single column from the top, in the order the item-adding methods are called (the heading goes above the field).messageis the description above the items.Method Item Value text(label, value?, multiline = false, rows = 4)Text box (Enter inserts a line break if multiline) textpassword(label, value?)A text box that hides input with *textselect(label, items, index = 0)A drop-down list (no typing) index,textcombo(label, items, value?)A combo box that also allows typing text,indexlist(label, items, multi = false, rows = 5)A list box. With multi, a check box per item (scrolls if there are more than the visible rows)index,text,selected(string[]),isPicked(i)/pick(i, on)radio(label, items, index = 0)Option buttons index,textcheckbox(caption, checked = false)A check box checkedfile(label, path?, dialogType = 3, title?)/folder(label, path?, title?)A file or folder picker (the FilePickerof §14.11.14;dialogTypeis the kind ofApplication.FileDialog)text(the path)label(text)Text only text- Every method returns an item (
DialogField). Values can be set beforeshow(), and can still be read aftershow()returns (after it closes). Callingshow()on the sameDialogagain starts from the values at the previous close. - Other members of
DialogField:enabled,rule(schema)(avalidationschema; §14.11.12),required(message?)(z.string().required(message); forcheckbox, it makes checking mandatory),addFilter(description, extensions)(file),hint(text)(a tooltip),error(the error being shown), andcontrol(the control being displayed;nullif closed). buttons(captions, cancel = -1, enter = 0)replaces the buttons (the default is OK and Cancel, with Cancel on Esc).width(the inner width; default 300 points),title, andmessagecan also be changed before showing.show(): Shows it modally and returns the number of the button pressed. × and Esc (thecancelbutton) give -1. Any other button validates all items that have rules; if there are errors, they are shown below the field (in the row reserved for items with rules), focus moves to the field of the first error, and the dialog does not close. An item that has been validated once is re-validated on every later change.ok()isshow() == 0.onChange((f) => …): Called whenever an item's value changes (fis the changed item). Reading and writing item values andenabledin the handler is reflected in the controls being shown.onSubmit((d) => …): Called after rule validation for any button other than cancel; if it returnsfalse, the dialog does not close.close(result = -1): Closes from within a handler.
- Every method returns an item (
new Progress(caption?, max = 100, title?, cancelable = true, width = 300): Shows modelessly and returns immediately. It lays out a bar (theProgressBarof §14.11.13; colors and so on can be changed throughprogressBar), one line below it (message), and, ifcancelable, a "Cancel" button.value,min,max,caption,message,step(by = 1),cancelled(the cancel button or × was pressed; when pressed, it shows "Cancelling…" and is disabled), andclose()(may be called any number of times; after closing,valuestill returns the last value).- × sets
cancelledtotruewithout closing the form (closing is done byclose()). When the value is changed and whencancelledis read, if at least 0.1 seconds have passed since the last redraw (immediately whenmaxis reached), it redraws withRepaintandDoEventsand accepts button operations.
Generated VBA: The standard module
RAS_Dialogs; the class modulesDialog,DialogField,Progress, andRAS_DialogHost; the parts used (ProgressBar,FilePicker,ValidationSchema, and so on); theonclasses (RAS_On_CommandButton_Clickand so on); and the formRAS_Dialog. Only the handling of×is done by the code ofRAS_Dialog(UserForm_QueryClose).Debug runs: They are shown in the form panel (§14.10.7) and can be operated. A modeless form draws changes each time
DoEventsis called while it is shown, and accepts panel operations on the spot (it does not wait). In tests andras runwithout Excel, showing is error 429, as with other forms.Limitations: Layout is a single column only, and item sizes are estimated from the number of characters (MS UI Gothic 9pt). Items can be added or removed only before showing. A multi-select list is a series of check boxes, not a list box (because RAS cannot assign to
ListBox.Selected(i)).
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" }
- Values: A string of
top,bottom,left, andrightseparated by commas (or spaces or|; case-insensitive; the same edge cannot be written twice), ornone, which anchors to no edge. If omitted, it istop,left(does not move). The designer writes lowercase values in the ordertop,bottom,left,right, and settingtop,leftremovesanchor. Any other value is an error (UFV026). It cannot be written onPage(whose size is determined byMultiPage) orProgressBar(UFV005). - How it moves: When the parent's inner width changes by
dwand its height bydh: horizontally, if bothleftandrightare set, the width grows bydw(never below 0); with onlyright, it movesdwto the right; with neither, it movesdw / 2(staying centered); with onlyleft, it does not move. Vertically, the same applies withtopandbottom. AFrameorMultiPagewhose width (height) grows or shrinks passes the same amount to the controls inside it (forMultiPage, the controls of its pages). ForFilePicker(§14.11.14), when both left and right are set, the text box grows and the button moves right. - Generated VBA: If any control has an anchor,
RAS_FormResizeis generated in the managed area and called fromUserForm_Resize(if the code-behind has aUserForm_Resize, one lineRAS_FormResize '--- RAS ---is inserted at its start; if not, aUserForm_Resizethat only calls it is also generated). It changes theLeft,Top,Width, andHeightof controls by the difference in the inner size (InsideWidth/InsideHeight) from last time. It does not move anything before and afterRAS_FormInit(§14.11.5) adjusts the form size to the display scaling (§14.11.10) (RAS_FormResize 1/RAS_FormResize 2). It acts whenWidth/Heightis changed in code and when the user resizes a form that isresizable(§14.11.17).Private Sub RAS_FormResize(Optional ByVal mode As Long) Static w As Single, h As Single, ready As Boolean Dim dw As Single, dh As Single If mode = 1 Then ready = False: Exit Sub If mode = 2 Then w = Me.InsideWidth: h = Me.InsideHeight: ready = True: Exit Sub If Not ready Then Exit Sub dw = Me.InsideWidth - w: dh = Me.InsideHeight - h If dw = 0 And dh = 0 Then Exit Sub w = Me.InsideWidth: h = Me.InsideHeight With Me.btnOK .Left = .Left + dw .Top = .Top + dh End With With Me.txtNote If .Width + dw > 0 Then .Width = .Width + dw Else .Width = 0 If .Height + dh > 0 Then .Height = .Height + dh Else .Height = 0 End With End Sub RAS_FormResizebecomes a name that cannot be used in the code-behind. The designer storage has no anchors, soras form pullcarries over theanchorfrom the existing.form.jsonto controls of the same name.- Debug runs: When the form's
width/heightis changed, controls are moved by the same rules, and then theUserForm.Resizehandler is called. - Designer: In the property grid's Anchor (Layout), click the bars of the cross-shaped diagram, as in Visual Studio, to choose edges. When the size of the form, a
Frame, or aMultiPageis changed (including the preview while dragging), controls move by the same rules. The form cannot be made smaller than the size at which a control anchored to fixed edges would stick out or a control that stretches and shrinks would fall below 1pt.
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
}
- Values:
resizableis a boolean (defaultfalse).minimumWidth,minimumHeight,maximumWidth, andmaximumHeightare in points of the inner size (InsideWidth/InsideHeight), likewidth/height, and 0 or greater (UFV016). 0 or omitted means no limit. It is an error when the minimum is greater than the maximum, or whenwidth/height(240 / 180 if omitted) is outside the range (UFV027). - Resizing: For a
resizableform,RAS_FormInit(§14.11.5) calls the runtime'sRAS_FormSizable Me, which adds a resizing border (WS_THICKFRAME) to the window through the Windows API, and then adjusts the inner size (§14.11.10). The runtime (RAS_Runtime) includesRAS_FormSizableand itsDeclares (IUnknown_GetWindowinshlwapi;GetWindowLongW,SetWindowLongW, andSetWindowPosinuser32) only when the project has aresizableform. In environments where the Windows API is unavailable (Excel for Mac), it does nothing.Private Sub RAS_FormInit() RAS_FormSizable Me 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 End Sub - Minimum and maximum: If any is specified,
RAS_FormResize(§14.11.16) is generated and called fromUserForm_Resize; it returns an out-of-range size to the nearer end of the range and then moves the anchored controls. It acts both on the user's resizing and whenWidth/Heightis changed in code (even if the form is notresizable).UserForm_Resizedoes nothing while it is restoring the size (busy). Windows are in pixels, so differences under 1pt are not restored. While dragging, an out-of-range size may be shown for a moment (because window messages are not intercepted (subclassed)).Private Sub RAS_FormResize(Optional ByVal mode As Long) Static w As Single, h As Single, ready As Boolean, busy As Boolean Dim dw As Single, dh As Single If mode = 1 Then ready = False: Exit Sub If mode = 2 Then w = Me.InsideWidth: h = Me.InsideHeight: ready = True: Exit Sub If Not ready Then Exit Sub If busy Then Exit Sub busy = True If 200 - Me.InsideWidth >= 1 Then Me.Width = Me.Width + 200 - Me.InsideWidth If Me.InsideWidth - 480 >= 1 Then Me.Width = Me.Width + 480 - Me.InsideWidth If 150 - Me.InsideHeight >= 1 Then Me.Height = Me.Height + 150 - Me.InsideHeight busy = False dw = Me.InsideWidth - w: dh = Me.InsideHeight - h If dw = 0 And dh = 0 Then Exit Sub w = Me.InsideWidth: h = Me.InsideHeight End Sub ras form pullcarries overresizableand the minimum and maximum from the existing.form.json.- Debug runs: A
resizableform can be resized by dragging the panel's right edge, bottom edge, or bottom-right corner. Including whenwidth/heightis changed in code, the size is brought within the range, then the anchored controls are moved and theUserForm.Resizehandler is called. - Designer: Resizable, MinimumWidth, MinimumHeight, MaximumWidth, and MaximumHeight in the property grid's Layout. The form's size stays within the range whether changed by dragging or by entering Width / Height, and setting a minimum or maximum that puts the form out of range also changes the form size to it (the same as Visual Studio).
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" }
- Values: A string. An empty string or omission means no placeholder. It can be written only on
TextBox. - Writing: A label
<name>_Placeholderis added immediately behind the box (in front in z-order). The label is overlaid inside the box (3pt from the edge), with a transparent background, the text colorgrayText, the same font andtextAlignas the box,wordWrapequal to the box'smultiLine,mousePointer3 (fmMousePointerIBeam), andTagRAS.Placeholder. If the box hastext/value, it is written hidden. This name cannot be given to other controls (UFV028).ras form pullturns a label whoseTagisRAS.Placeholderback into theplaceholderof the same-named box with the same parent. - Generated VBA:
RAS_Placeholder(show / hide) andRAS_PlaceholderClickare generated in the managed area and called from the following event procedures. If the code-behind has the same event procedure, a… '--- RAS ---line is inserted at its start (if not, one that only makes the call is generated).MouseUpof the label: hides the label and callsSetFocuson the box (does nothing if the box is disabled).Enterof the box: hides it.Exit: shows it if the box is empty.Change: shows it when the box is empty and has no focus (whentextis changed in code).Enter/Exitof aFrame/MultiPagecontaining the box: MSForms does not raiseEnter/Exitof the controls inside when focus enters or leaves aFrame/MultiPage, so the display is decided again then.UserForm_Activate: hides the one for the box that has focus at the time of display.
Private Sub txtName_Enter() RAS_Placeholder Me.txtName, Me.txtName_Placeholder, 1 End Sub Private Sub txtName_Placeholder_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) RAS_PlaceholderClick Me.txtName, Me.txtName_Placeholder End SubThe label is aligned with the box's position when shown, and with anchors (§14.11.16) it moves together with the box. When the box's
Visibleis changed in code, it is brought into line the next time the display is decided again (Change, focus in and out). - Debug runs: The label is not created; the panel overlays the same hint on the box (an I-beam pointer, and releasing the button focuses the box).
- Designer: Placeholder in the property grid's Appearance. For an empty box, the canvas also shows the hint in gray.
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
- No tests in the main source: Tests go in
*.test.rasfiles undertest/(§14.12.2). You cannot write tests insrc/modules (the equivalent of vitest's in-source testing). - Not included in the workbook: Test files and test helpers are not included in the output of
ras build/ras pack/ras sync/ras watch.ras checkand the LSP type-check and lint them. - Statically enumerable:
describe/testcan be written only at the top level of a file and insidedescribe, and their names must be string literals (§14.12.3). The compiler and the LSP can obtain the list of tests (names, positions, nesting) without running them. - Excel stand-in by default: Even on Windows with Excel installed, tests run on the Excel stand-in by default (so that results do not depend on the environment). To run against the real Excel, specify
--excel(§14.12.7). - Not a verification of the VBA build: As with debug runs, optimizations (§8–§10.4) are not applied. For differences in semantics, see §14.10.4 and §14.10.5; for differences between the stand-in and Excel, see §14.10.8.
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 |
- Referring to the code under test: Test files
importand use theexported items of the modules insrc/andforms/(import { lastRow } from "src/report";; the path is relative to the project folder; see §12.1.3). Functions that are notexported cannot be called. Globals such as sheet code names (Sheet1) andthisWorkbookcan be used just as in ordinary modules. - No references in the opposite direction: Importing a file under
test/from a module insrc//forms/is an error (E0701). - Changing the location:
includein[test]ofras.tomlchanges the patterns treated as test files (§14.12.9). Every file that matchesincludeis treated as part of the tests (not included in the build).
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.
import- Declarations of functions, classes, structs, enums, and type aliases (
exportis unnecessary; adding it has no effect) const/letdeclarations (to share values between hooks (§14.12.4) and tests)- Call statements of
describe/test(it) /beforeAll/afterAll/beforeEach/afterEach
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.
- The first argument (the name) of
describe/testmust be a string literal (E0703). Template strings and variables cannot be used. - The table of
test.each/describe.each(§14.12.4) can be any expression. If it is an array literal, the list (LSP,--list) shows a name for each case. For any other expression, the cases are not known until the tests run, so the list shows only one name template. @macro/@init/@udf/@on/@ribbon, andMainmade of top-level statements (§12.4), cannot be written (E0704). Extension methods can be used if you declare them in a helper module andimportthem.- The bodies of tests and hooks are ordinary lambdas (§4) and can capture and read/write a
letin adescribe.
// 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 |
- Execution order: Tests in a file run one at a time in the order written (not in parallel). Files may run in parallel (the results do not change because of the isolation in §14.12.6). On the Excel stand-in, the files run in processes of their own, as many at a time as there are CPUs, and the results are shown in the order of the files (each once its file has finished). With
--sequence(§14.12.7),--excel,--inspect-brkor--bail, one file runs at a time. - Hook failures: If
beforeAllfails, all tests in thatdescribefail (their bodies are not run). IfbeforeEachfails, the body of that test is not run and the test fails;afterEachstill runs. - Timeout: The default is 10 seconds per test (
timeout-msin[test]). When exceeded, the test fails and the run of that file is aborted (the remaining tests fail). Because JavaScript execution cannot be stopped midway, the whole process is terminated. - No
async: Test bodies run synchronously.sleep/waitUntilandDoEventsbehave as in debug runs.
14.12.5 Workbooks and test isolation
- A new runtime per file: Each test file runs in a new runtime (module variables,
@init, application state, Excel stand-in). Module initialization and@initrun once, before the first use of a module under test in that file (same as §14.10.2). Within the same file, module variables persist across tests (same as vitest). - The workbook is restored for each test: At the start of each test, the state of the workbooks (open workbooks, all cells, formats, names, sheets, selection, calculation mode, the range being copied) is restored to the state at the point when all
beforeAllhooks enclosing that test have finished. ThenbeforeEachruns. Changes made by a test or itsbeforeEachdo not carry over to the next test. Setup done inbeforeAll(such as writing cells) is included in the state at the start of each test. - Default workbook: The
workbookinras.toml(§15.2). If there is noworkbook, a blank workbook with one sheet is used. useWorkbook(path: string): Excel.Workbook: Replaces the project's workbook with the contents of the workbook atpath(relative to the project root). The workbook's code names (Sheet1, etc.) remain those of the project's workbook and are mapped to the sheets of the workbook atpath(mapped in sheet order; if the workbook atpathhas more sheets, the rest can be referenced by name only). It can be called frombeforeAll/beforeEach/ a test body. The original file is not modified.Workbooks.Open:Workbooks.Opencalled from a test loads the file as in debug runs and does not modify the original file (§14.10.8). Workbooks opened this way are also returned to the closed state at the start of each test (those opened inbeforeAllremain open).- File system: Reads and writes through
Scripting.FileSystemObjectgo to the real file system (they are not restored). Files that a test writes should be placed intempDir(): string(an empty folder created for each test and deleted after the test ends). Files that a test reads are found fromprojectDir(): string(the absolute path of the project root). - Events:
@onhandlers for workbooks and sheets are invoked in response to the test's operations, as in debug runs (§14.10.8). An error not caught by a handler does not stop execution in a debug run, but in a test it fails that test (setevent-errors = "ignore"in[test]to not stop).
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 |
- The type of
expectisexpect<T>(actual: T), and the expected value oftoBe/toEqualmust be of a type assignable toT(otherwise a type error). Whenactualisany, any value is accepted. - A matcher failure is not caught by
try/catch(§5) (even if youcatchit inside a test, it is always reported as a failure). - Snapshots:
toMatchSnapshotcompares the value as text (the elements of arrays,Maps and structs one a line; strings in"…"with line breaks and tabs written\nand\t) with the one recorded in__snapshots__/<test file name>.snapin the folder of the test file.- A record is named
<full name of the test>[: <hint>] <n>(n: which call of that name in the test). The file is text,=== <name> ===lines each followed by the value, so its diffs can be read. Commit it to the repository. - With no record, the value is recorded and the matcher passes (with
--cinothing is recorded and it fails). When it differs, it fails showing the first line that differs (recorded, actual).ras test -u(--update-snapshots) records the differing ones again. - Records no test uses any more are reported as unused.
-uremoves them when every test of the file ran (no-tfilter,skip,only, or stop by--bail). The records of a failed test count as used. - In a hook, and
not.toMatchSnapshot: error 5.
- A record is named
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) |
- A replaced function keeps a record of its calls (
const m = mockMsgBox(...); expect(m.calls.length).toBe(1); expect(m.calls[0].prompt).toContain("Done");). - A dialog that is not replaced gives the same response as in debug runs (§14.10.8) and is shown as a warning in the test result (with
--ci, it fails the test). - What the user does:
simulate(...events: string[])does what the user does and raises its events (the@onhandlers run). They are written as forras run --event(§14.13) (simulate("enter:Sheet1!A2=10"),simulate("open", "click:Sheet1!btnRun")). An error of a handler fails the test. Not available with--excel(run-time error 445). - Output:
printed(): string[]returns the lines thatdebug.printoutput during that test. The output ofdebug.printis shown in the result only when the test fails.
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) |
--excel: The JavaScript of the tests runs against the real Excel, throughras_com.node(§14.10.3), instead of the Excel stand-in.- Excel and the workbook: As
ras excel(§14.17) does, an Excel is started for it alone (shown minimized: a hidden Excel behaves differently, e.g.Worksheet.Activatedoes not switch to its workbook) and the copy ofproject.workbookwith the project written into it (build/test/excel/<book>; an.xlsxbecomes an.xlsm) is opened. The user's Excel and the original workbook are not used. Excel calls the@onhandlers as the VBA written into the copy. - Calls of the project's functions: The functions of the modules of
src/that a test calls run as the VBA written into the copy, inside Excel, instead of as JavaScript ([test]excel-calls = "vba", the default). A call is oneApplication.Runinstead of one COM call per cell, as fast as VBA (one report of the 様式2E checker: 154 seconds became 9). It also checks the very VBA that ships.- The bridge:
ras testadds the moduleRAS_TestBridgeto the copy (not to the project's workbook, nor tobuild/). It holds one procedure for each exported function (not@onhandlers, generic functions, accessors or extension methods) whose parameters and result are only numbers, strings,boolean, dates, enums,any/cellValueand Excel's objects (Excel.*), withoutbyrefor rest parameters. The procedure initialises the project as a macro does (§12.3) and calls the function with as many arguments as were given (optional ones can be left out). A function that takes or returns arrays,Maps, structs or RAS classes runs as JavaScript. - Decided for each test file: The calls of a test file go to the VBA only when the file (and the test modules it imports) uses the project's modules only by calling functions the bridge can call. A file that creates the project's classes, uses other functions or the variables of a module, or uses replacements (
mock*),printedorsimulateruns entirely as JavaScript (with part of the project's code in VBA and part in JavaScript, the variables of the modules would be two sets;printedcannot receive VBA'sDebug.Print). With--inspect-brkit runs as JavaScript too (for the breakpoints). - Decided for each call: A call runs as JavaScript when an
anyargument is a RAS object or an array, when an argument in the middle is left out, or whileuseWorkbookhas put another workbook in place of the project's. - Errors: An error in the VBA comes back to the test as a run-time error with the same number and description. It shows the place in the
.rasfile that the error handling of a function the error passed through recorded (tryand so on; it needs the line numbers of[build] erl), and otherwise the place of the test's call (VBA cannot tell a caller on which line of a procedure without error handling the error happened).
- The bridge:
- A workbook for each test: When a test starts, every open workbook is closed without saving and the copies taken when the
describestarted (afterbeforeAll) are opened again. They are not reopened when no object of Excel was called since they were last reopened (or copied): a test of a pure function changed nothing (calls of a COM object inside the Node process, such asVBScript.RegExp, do not count).useWorkbookopens a copy of the file in place of the project's workbook and gives its sheets the code names in order. The workbooks of failed tests (§14.12.8) are saved withSaveCopyAs(in the format of the original). - Dialogs: The dialog watcher of §14.10.6 runs with
dismiss(nobody is there to answer). - Time: In a test that runs as JavaScript, each call to Excel is a COM call between processes (0.2 to 2 milliseconds; several times longer with Excel shown than hidden), so a test that reads and writes cells one by one is much slower than on the stand-in or in VBA (about 20 times VBA for the 様式2E checker). A test that calls the project's functions through the bridge is about as fast as VBA. The time-out is 10 times
timeout-ms(or the test's own). After a test file was ended, Excel is started again. - Paths:
thisWorkbook.pathis the folder of the copy. Find the files of the tests fromprojectDir().
- Excel and the workbook: As
- Exit code: 0 if everything succeeds (including skipped and todo), 1 if there are failures, 2 if the tests could not be run, for example because of a compile error.
- Compilation: Before the tests, the same checks as
ras checkare performed, and if there are errors the tests are not run. The same applies to type errors in test files. - Failure display: Shows the test's name, the failed matcher (expected value, actual value, diff) or the run-time error (VBA error number and description), the
.raslocation (source map, §14.10.2), the output ofdebug.print, and the path of that test's workbook (§14.12.8).
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"}
statusispassed/failed/skipped/todo.failure.kindisexpect(a matcher failure) /error(a run-time error; hascode,description, andlocation) /timeout/hook(a hook failure).
14.12.8 Workbooks of failed tests
- For a failed test, the workbooks at the moment of failure (the project's workbook and the workbooks opened by the test) are saved to
build/test/workbooks/<test file name>/<test full name>.xlsx(the saving method and limitations are the same as in §14.10.8; the VBA project is not included). You can check what the test wrote with Excel or other tools. - The result of a failed test shows, for each workbook saved, the differences of the cells from the start of the test (when the
beforeAllhooks enclosing it had finished), in the same form asras book diff(§14.14; the first 20 cells in the human-readable output). With--reporter jsonthey arediffs([{ "workbook", "diff" }],diffasras book diff --format jsongives it). A workbook the test opened itself (useWorkbookand so on) has no start, so it is not shown. With--excel, they are shown against the copy of the workbook as the test started (.start/). - With
save-workbooks = "always"in[test], the workbooks of passed tests are also saved. With"never", nothing is saved. - Characters that cannot be used in file names (such as the
>in>) are replaced with_(rebuildReport _ writes twice the row number in column C.xlsx). Other workbooks opened by the test are saved as<test full name> - <workbook name>.xlsx. - When the workbooks are saved, the workbooks as they were when the test started (after the
beforeAllhooks enclosing it, §14.12.5) are saved too, under the same names in.start/(build/test/workbooks/<test file name>/.start/<test full name>.xlsx). The editor compares with them to show the cells the test changed (§14.12.10). A workbook opened during the test has none.
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
- Test Explorer: The VS Code extension shows the result of
ras test --list --reporter jsonin VS Code's Test Explorer (Testing API) and reflects run results (--reporter json). It shows a message (expected and actual values) at the location of the failed matcher. - Workbooks of failed tests: For a test whose result has workbooks (§14.12.8;
workbookof--reporter json), the button (testing/message/content) and the context menu (testing/message/context) of the failure message, the context menu of the test in the Test Explorer (testing/item/context), and the command "RAS: Show the Failed Test's Workbook in Sheet Preview" (ras.test.openWorkbook; without an argument, it offers the tests with saved workbooks) show the workbook in the sheet preview (the editor of §14.14). The differences from the workbook as it was when the test started, in.start/, are marked (ras book view --diff); the project's workbook without one is compared with the project's workbook (workbookofras.toml). When the test saved several workbooks, the user chooses which to show. It is shown read-only. - Running and debugging: Tests are run and debugged from the Test Explorer and from the buttons VS Code shows in the gutter next to
test/describein a test file ("Debug Test" in their context menu); no CodeLens is shown. "Debug" runs that test with breakpoints and stepping, the same as a debug run (§14.10) (includingbeforeAll/beforeEach). The VS Code extension runsras test --inspect-brk --reporter jsonand attaches the debugger at eachinspectorevent. - Completion and types: In test files, the test API (§14.12.4–§14.12.6) appears in completion and quick info. It does not appear in modules in
src/. - Test generation: Above each
exported function of a module insrc/(one that has a body and is not@on/@init), "Generate Test" is shown (in the VS Code extension, as a CodeLens and the commandRAS: Generate Test(for the function at the cursor); in the playground, as a line above the function in the editor). Activating it adds a test skeleton for that function to the test filetest/<module key>.test.ras(test/util/str.test.rasforsrc/util/str.ras) and opens the line of the added test. The language server command isras.generateTest(argument{ uri, name }or{ uri, position }; the result is{ uri, path, created, edits, line }), and the playground's wasm function isgenerateTest(input, path, name).- Skeleton: One
testinsidedescribe("<function name>"). The arguments (excluding optional ones and rest arguments) becomeconsts with type annotations, given placeholder values suited to their types (integer0, real number0.0, string"",booleanfalse, datedateSerial(2000, 1, 1), array[],Mapnew Map<K, V>(), struct a literal with the non-optional fields, tuple a literal of its elements, enum its first member, function type a lambda returning a placeholder value,Excel.Worksheetthe code name of the workbook's first sheet (thisWorkbook.worksheets(1)if there is no workbook),Excel.Rangeitsrange("A1"),Excel.WorkbookthisWorkbook, other objectsnull), and then the function is called. For an extension method, thethisargument becomestargetand it is called astarget.f(...). The return value is compared with a placeholder value using a matcher suited to its type (toBeCloseTofor real numbers,toEqualfor arrays, structs, andMaps,not.toBeNothingfor objects,toBe("")forany/cellValue,toBeotherwise). For a function with no return value, a comment after the call gives an example of checking a cell value. For a function with arguments,test.todo("boundary values (…)")is also added. The skeleton passes the type check and can be run as is (rewrite the placeholder values into the expected values before use). import: Imports the function and the types (enums, structs, classes) of thesrc/module used in annotations. For types that are notexported, no annotation is written and inference is left to the compiler.- Existing test file: If the file exists, the names are added to an existing
import { … }from the same module (if there is none, animportis written on the line after the lastimport, and if there is noimport, at the top). If a top-leveldescribe("<function name>", () => { … })exists, the new test is added at the end of its body; otherwise a newdescribeis added at the end of the file. If there is unsaved editor content, it is added to that.
- Skeleton: One
14.12.11 Limitations
- A VBA build (running tests as real VBA) is not provided. Verifying code that has gone through optimizations (bulk transfer, inlining, etc.) is still done on a real machine, as before.
- There is no module mocking (replacing functions of an
imported module), and no parallel execution of tests (within a file). - Showing a user form (
frmInput.show()) is an error (445) in tests. Anexport functionin a form's code-behind can be called. - With
--excel, the handling of events raised by Excel (those caused by user actions) and of dialogs is the same as in debug runs (§14.10.6), and themock*replacements apply only tomsgBoxand the like called from RAS (they do not apply to dialogs shown by hand-written VBA).
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"
- Execution: Outputs JavaScript for debugging to
build/debug/(same asras build --target js) and runsras-main.json a JavaScript runtime. Excel operations always go to the Excel stand-in (§14.10.8), even on Windows. - Runtime: Searched for in the order: the environment variable
RAS_NODE,nodeon the PATH, the VS Code executable (run as Node withELECTRON_RUN_AS_NODE). The Excel stand-in add-on is searched for in the order: the environment variableRAS_BOOK_ADDON,ras_book.nodein the same folder asras. The same applies toras test. - What is shown: The
debug.printlines (shown during execution), the dialogs that were shown and their responses, run-time errors (VBA error number, description, and.raslocation), and the diff of changed cells (same format asdiffin §14.14; it compares the loaded file with the workbook saved inbuild/debug/workbooks/).--no-diffsuppresses the diff. - Dialog responses: Specify
--msgbox <vbYes etc.>,--inputbox <string>,--open-file <path>, and--save-file <path>(falseto cancel) in the order the dialogs appear. An unspecifiedmsgBoxreturnsvbOKand an unspecifiedinputBoxreturns the default value (cancel if there is none), and this is shown. A file selection dialog with no response is error 445. - Functions with parameters:
ras run Module.f --arg 3 --arg BranchAcalls a function with parameters (@udffunctions too) with the values of--argas its arguments, in order. Each value is converted to its parameter's type (int/longand the like are rounded as VBA'sCInt/CLng,doubleis a number,booleanistrue/false,dateis written as2026/4/1,stringis taken as it is,anyis a number when it reads as one). A value that cannot be converted raises run-time error 13; a wrong number of arguments, 450. The return value and the values of thebyrefarguments after the call are shown (resultandbyrefwith--json).ras run --listlists the functions that can be called with arguments, with their signatures, separately. - Events (
@onhandlers):--eventdoes what the user does on the stand-in and raises its events (as the run mode of the sheet panel, §14.14):open(Workbook.Open),activate:Sheet,select:Sheet!A1(SelectionChange),enter:Sheet!A1=value(Change; nothing after=clears the cells),double-click:Sheet!A1/right-click:Sheet!A1(BeforeDoubleClick/BeforeRightClick),click:Sheet!name(an ActiveX control'sClickand so on; for a shape or form control, its@on("<name>.Click")handlers). The sheet is its tab name or code name. Several are done in order, after the function when one is given;--eventalone, without a function, also works. An error of a handler goes toeventErrorsof the result. - Replacements:
--replace-run <macro name>=<module name.function name>calls a project function instead of the hand-written VBA called withapplication.run(and the hand-written functions declared intypes/*.d.ras).--replace-object <ProgID>=<module name.class name>uses an instance of a project class (or, if a function is specified, its return value) instead of the COM object created withcreateObject/new. This is the same mechanism asmockRun/mockCreateObjectin tests (§14.12.6). If the specified function or class does not exist, an error occurs at the time it is called. - Specifying in debug runs: In VS Code debug runs (§14.10), the same things are written in
answersoflaunch.json:{ "msgBox": ["vbYes"], "inputBox": ["2026/4"], "openFile": [], "saveFile": [], "run": { "Legacy": "Mocks.legacy" }, "createObject": { "ADODB.Connection": "Mocks.FakeConnection" } }. Dialogs with no specified response are shown and answered as before. When connected to a real Excel, this also applies tomsgBox/inputBox/application.run/createObjectcalled from RAS (it does not apply to dialogs shown by hand-written VBA). --view: Creates an HTML file that shows the workbook after the run as a grid inbuild/view/<workbook name>.html(theviewof §14.14; changed cells are highlighted).--json: Outputs a single object withentry,ok,printed(thedebug.printlines),dialogs(kind,prompt,answer,answered),error(code,description,source,file,line),eventErrors,notes, andworkbooks(name,file,source,diff).- Exit code: 0 if it ends normally, 1 if it ends with a run-time error, 2 if it could not be run, for example because of a compile error.
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
dump(no sheet specified): For each sheet, prints its name, code name, visibility, used range, the number of cells with values and formulas, merged cells, filters, tables, data validation, conditional formatting, notes (the cell and the text), and the formulas. Formulas copied down or to the right in the same form (identical in R1C1 notation) are collapsed into one line with the range and the formula of its first cell. The workbook's defined names follow. If the workbook is omitted, theworkbookfromras.tomlis used.dump --sheet: Prints one cell with a value per line asaddress <tab> value(for formula cells,address <tab> formula <tab> → value). Strings appear as"...", dates as2026-04-01, and error values as#N/A.--sheettakes a sheet name, code name, or 1-based index, and can be given more than once.--rangeisA1:F20orSheet1!A1:F20.--formatsalso prints the number format and the cell's display (Text).- Formats (
dump --sheet --styles): After the cell values, prints the cells whose format (font, fill, borders) differs from the workbook's default (the Normal style's font and size, no fill, no borders), cells with the same format together, asrange <tab> format(e.g.A1:C1 bold, fill #FFFF00, border-bottom thin). A range joins the adjacent cells of a row, and those with the rows below that span the same columns (A1:C2,E2). Only what differs from the default is printed, in this order:font "Meiryo",size 14,bold,italic,underline single,strike,color #FF0000(the font color; black is not printed),fill #FFFF00(a pattern other than solid asgray125 #FF0000, a gradient asgradient), andborder-left/border-right/border-top/border-bottom/border-diagonal-down/border-diagonal-up(the line style such asthin,mediumordouble, with its color when it is not black). When the four sides have the same border it is written once asborder thin. Theme colors are printed as RGB. Cells without values are included. The formats of whole rows and columns, alignment, protection, conditional formats and table styles are not.jsonaddsdefaultFont(name,size) andstyles(rangeandstyle, wherestylelooks like{"bold": true, "size": 14, "fill": "#FFFF00", "border": {"bottom": "thin"}});markdownadds a "Formats" section. Not available withcsv. - Large sheets: By default, up to 200 rows × 50 columns are printed (
--max-rows/--max-cols;--allremoves the limit), and when output is cut off, the printed range is shown. - Formats:
jsonholds the sheet information andcells(address,row,column,type,value,formula, and with--formats,numberFormatandtext);csv/markdowntabulate the cells' display. diff: Matches sheets by name and compares values, formulas, and number formats cell by cell. As structural differences, it prints added, deleted, and renamed sheets (renamed = same contents, or swapped one-for-one at the same position) and inserted/deleted rows and columns (inferred from the cell layout: the contents of the rows and columns are aligned by their longest common subsequence, so insertions and deletions at several places are printed too, from the top; not inferred when the part to align is too large). Cells that merely shifted because of an insertion or deletion are not reported as differences. Differences in defined names are printed as well.--format jsongives JSON.diff --styles: Also compares the formats of the cells (asdump --styleshas them: what differs from the default in font, fill and borders), including cells that have a format and no value. A cell whose format changed is printed asaddress <tab> value <tab> format fill #FFFF00 → #00B0F0, bold none → yes(aftervalue → valuewhen the value changed too), a new cell asformat bold, fill #FFFF00. With--format json, thebefore/afterof a cell getstyle(only when it differs from the default). Without--styles, formats are not compared (nor are they in the differencesras runshows after a run, or in the comparisons ofras excel).- Exit code: For
diff, 0 if there are no differences, 1 if there are, 2 if reading fails. - Out of scope (
dump/diff): Formats other than font, fill and borders (alignment, protection, and so on), column widths and row heights, charts, shapes, comments, and differences in VBA code (extract withras unpackand compare).
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
- Output: A single self-contained HTML file that references no other files (
-ofor the output path,--stdoutfor standard output). It shows a grid with row numbers and column headings, the sheet tabs, and the address and formula (or value) of the selected cell. As in Excel, the grid draws gridlines even over ranges with no data and continues to the edge of the screen, with rows and columns growing as you scroll (it follows hidden rows and columns and the sheet's "hide gridlines" setting). - Formulas: Selecting a formula cell shows the formula in the formula bar, color-codes the cell references in it, and surrounds each referenced cell with a frame of the same color (as when editing a formula in Excel). Hovering over a formula cell shows the formula in a tooltip. The bar's "Show Formulas" (Ctrl+` / Ctrl+Shift+@) works like Excel's "Show Formulas": cells show the formula instead of the value (cells with plain values show the value as entered) and column widths double.
- Name box and Go To: The name box shows the address of the active cell (or the name, if the selection equals the range of a defined name). Typing a cell address, a range (
B2:D5,3:5,B:D,Sheet2!A1), or a defined name into the name box and pressing Enter selects it (switching to another sheet if needed; names are looked up in the current sheet first). Ctrl+G (also F5 in an editable grid; in a browser F5 remains reload) opens "Go To" (a list of names and an input for the reference). - Find (Ctrl+F): You specify the text to find, where to search (sheet or workbook), what to search (formulas, values, notes), match case, and match entire cell contents. "Find Next" (Enter; Shift+Enter for previous) moves to the next matching cell after the active cell (in row order), and "Find All" shows a list of matching cells (click to jump).
*,?, and~are wildcards as in Excel. The search covers the cells that are drawn (see "Large sheets"). - Status bar: When two or more cells are selected, it shows the number of non-empty cells (count) and the average and sum of the numeric (including date) cells (cells in hidden rows and columns are not counted). As in Excel 2021, the average and sum are shown in the number format of the active cell (for General, the General display up to 11 characters, without thousands separators; for a time-only format,
[h]:mm:ss), and if any cell holds an error value, only the count is shown. Number formats the page cannot apply (fractions, conditions, Japanese era names, etc.) are shown as General. On the left it shows "Ready", "Enter", "Edit", and "Point" (while a reference is being entered into a formula). - Notes, data validation, freeze panes: Cells with notes (comments) get a red triangle in the upper-right corner, and hovering shows the note (author and body). Selecting a cell with list data validation shows a button to the right of the cell (not shown if "In-cell dropdown" is turned off in the file), and shows the input message below the cell if there is one. List values are read from
"a,b,c", a cell range (including on other sheets), or a name (empty cells are skipped; up to 1000 items). Frozen panes keep the frozen rows and columns on screen while scrolling (shapes, selections, and reference frames over them stay too) and draw a line at the boundary. For a file whose frozen pane's top-left is scrolled (topLeftCellis not A1), the rows above and columns to the left of it are also drawn frozen. - What is drawn: Cell display (with the number format applied); fonts (name, size, bold, italic, underline, strikethrough, color; for strings with per-character formatting (rich text), characters are drawn with their own fonts (including superscript and subscript), and rows without a specified height fit the largest character, as in Excel); fills; borders; horizontal and vertical alignment (numbers and dates with no specification to the right, booleans and error values centered); wrapping; indents; column widths and row heights; hidden rows and columns (collapsed, with the boundary indicated); merged cells; filter headings; sheet tab colors; hidden sheets. A string whose right-hand neighbor is empty overflows into it, as in Excel (no gridlines are drawn over the overflowed range or filled cells). Row numbers and column headings are the same size as in Excel 2021 (11pt Yu Gothic, column heading height 24 px, scaled with zoom). Cells whose formula results in an error value get the same green triangle at the upper left as Excel's error checking. When a sheet is opened, the selection saved in the file (that of the active pane) is selected.
--diff <before>: Marks cells that differ frombefore(the same comparison asdiff), and shows a list of changes (click to jump to the cell) and the previous contents.- Large sheets: By default, up to 500 rows × 100 columns per sheet (
--allremoves the limit). --sheet <sheet>: Specifies the sheet to show first by code name or sheet name (if both match, the sheet with that code name; an error if none). If not specified, the sheet is chosen in this order: the sheet shown last time, the first sheet with changes, the active sheet.- Shapes, pictures, controls: Items in the sheet's drawing (including those with a macro assigned that runs on click) are drawn over the cells. Shapes (all preset shapes and freeforms, fills, lines, arrowheads, shadows, glow, reflection, text and vertical text), text boxes, WordArt (text transforms, gradients, outlines, shadows), connectors, groups, SmartArt (from the drawing Excel saves (
xl/diagrams/drawingN.xml); Excel saves the size of a sheet's SmartArt frame as 0 × 0, so the size is determined from the anchor), pictures (PNG, JPEG, GIF, SVG, etc.; EMF is drawn by converting GDI records (lines, shapes, paths, text, bitmaps, transforms, clipping) to SVG; EMF-only-EMF+ files and WMF get an "image in an unsupported format" frame), and embedded objects (the picture is drawn over the object's shape fill and under its line; a new Excel object has a white fill and a black 0.75pt line; when there is no picture or it cannot be drawn, the file's icon is drawn with its name below (the embedded file's name, or the program's name if it is not a file), laid out like Excel's icon picture; which icon appears depends on the PC's file associations and cannot be known in a browser). Form controls (button, check box, option button, list box, combo box, spin button, scroll bar, label, group box, text box) and ActiveX controls (MSForms CommandButton, CheckBox, TextBox, etc.; caption, value, colors, and font are read from the saved control data) are drawn in the Windows look, and those with a linked cell show that cell's value (checked state, selected item). ActiveX controls other than MSForms are drawn with their saved picture. Charts are drawn as SVG: column and bar (clustered, stacked, 100%), line, area, pie and doughnut, scatter and bubble, radar, and combinations of them (secondary axis). Title, legend, axes (ticks, axis labels, number format, minimum and maximum, reversed), gridlines, data labels, series and element colors (color styles, theme colors). Series values are read from the current values of the referenced cells (values changed by a run also appear in the chart; if they cannot be read, the chart's cache is used). 3-D charts are drawn as 2-D, and newer types (waterfall, treemap, etc.) and contour charts become a frame with the title. Clicking shows the name in the name box and the assigned macro in the formula bar. The shape drawing follows the xljs print implementation (src/api/xlsx_shape.rs). How shape geometry (preset shape and WordArt definitions and their evaluation), colors, anchors, and part relationships are read is shared with xljs and lives in the umya-spreadsheet fork'sdrawingml(it reads the file's drawing XML withxml_tree, not through the umya-spreadsheet model). Sheet view settings (gridlines, zoom, panes, selection), table styles (including custom ones) and filter buttons, and the font and alignment of the Normal style are read from the umya-spreadsheet model. --drawings <workbook>: Reads shapes, pictures, and controls from this workbook. A workbook saved by the Excel stand-in (the result ofras run, a snapshot during debugging) keeps cells, formatting, shapes, and controls, but drops things umya-spreadsheet does not hold, such as the VML of form controls; soras run --viewand the editor specify the pre-run workbook (the stand-in does not modify shapes).- Conditional formatting and tables: Conditional formatting draws the formats of rules (fill, font color, bold, italic, underline, strikethrough, borders, number format) for cell value, formula, top/bottom, above/below average, duplicate/unique, text, blanks, errors, and dates (today, this week, last month, etc.), plus color scales, data bars, and icon sets, following priority and "Stop If True" (matched to the xljs print implementation; today's date is the same as the Excel stand-in's TODAY). Tables draw the fill, bold, font color, and borders of the table style (the workbook's own style, or the built-in light, medium, and dark styles approximated per family) beneath the cell's own formatting (header row, total row, banded rows, first and last columns). Table headings get filter buttons (except for columns whose button is hidden; a filtered column shows ▼) (display only; what can be filtered in the grid is the sheet's filter). Icon set arrows and quarter circles use the shapes and colors of Excel 2021, are drawn 16 px in size at the left of the cell (vertically centered if the cell is vertically centered).
- Hyperlinks and zoom: Cells with hyperlinks (cell links, and the
HYPERLINKfunction with the address written as a string) navigate to the target on click (locations and names in the workbook are selected; http, https, and mailto open in the browser (VS Code in the editor); other links are not opened). Holding the mouse down selects the cell. Zoom at the right of the status bar (10–400%, Ctrl+wheel) scales the view. Initially the file's sheet zoom (zoomScale) is used, and a changed zoom is remembered per sheet by the panel (it is not written to the file). - What is not drawn: Chart details (trendlines, error bars, data tables, axes and gridlines with changed formatting, shape effects), note formatting and the always-show setting (notes appear only on hover), threaded comments (shown as the legacy notes Excel saves alongside), diagonal borders, and Japanese-era built-in number formats (27–29, 36, 50, 51, 54, 57, 58). The conversion from formatting to CSS (theme colors, border styles, pixel width of columns) follows the xljs print (PDF output) implementation.
- Editor: The VS Code extension shows the same page in a panel (sheet preview). "RAS: Show Workbook in Sheet Preview" (also shown in the right-click menu of
.xlsx/.xlsmin the Explorer) shows the workbook file, and a result workbook underbuild/is shown with the differences from the project's workbook highlighted. In Excel-less debug runs (§14.10.8), each time execution stops at a breakpoint or step, it shows the workbook at that moment and highlights cells that changed since the last stop (the first time, cells changed from the file) (not shown if the settingras.debug.sheetViewisoff). "RAS: Show Sheet Preview" shows the project's workbook with that sheet, for a sheet file (objects/<code name>.ras; §12.2;ThisWorkbook.rasis excluded) (ras book view --stdout --sheet <code name>). It appears in the editor title bar and right-click menu and in the Explorer right-click menu (which files qualify is tracked by the extension, which watches.raschanges and keeps the context keyras.sheetFiles). At every stop, the extension evaluates$rasBookSnapshot(<folder>)in the debuggee to have it write out the open workbook, and shows the output ofras book view --stdout(shapes are loaded with--drawingsfrom the source workbook). When the project's workbook is shown, as in the form designer (§14.11), you can open or add the handler for an event from the right-click menu of a shape or control, the ribbon's Shape Format tab "View Code", the events in the right pane, or double-click (default event). For ActiveX controls (§12.2.1) this is a function with@on("<control name>.<event>")in the sheet file (choose the event from a list); for shapes, pictures, charts, and form controls, a function with@on("<shape name>.Click")in the sheet file (§12.2.1; if there is none, afunction <name>Click()is added). The generated macro (Sheet1.button1_click) is registered in the workbook with themacroop ofras book edit. If another macro is already registered, it is opened (the "Assign function to click event…" and "Assign click event…" items in the right-click menu let you choose either an@onhandler or a function in the files underobjects/andsrc/; for list and combo boxes it is called the "selection event", for spin buttons and scroll bars the "change event". The assigned function is opened with "View Code"). The page's JSON gives objectsactivex(the MSForms kind; empty for other ActiveX controls),onAction(a macro can be assigned), andshapeId(the control's shape number).
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"}'
Edits: Specified with
--op(JSON of one edit or an array of them; may be given more than once) and--ops-file <file>(-for standard input).--set/--clear/--insert/--deleteare the shorthand forms in the table below and are performed in this order, followed by the JSON edits. An edit names its sheet withsheet(sheet name, code name, or 1-based index); if absent,--sheet; if that is absent too, the first sheet. If the workbook is omitted, theworkbookfromras.tomlis used.opArguments Description setrange,textEnter into cells. textis read the same way Excel reads input (a leading=makes it a formula; numbers, dates, times, percentages, and booleans become those values; dates and the like also get a number format). With a range, the same content goes into all cells, and relative references in formulas are shifted from the first cell (Ctrl+Enter). Addingruns([{"t": "red ", "f": {...}}, {"t": "text"}]) sets formatting for parts of the string (rich text; same as selecting some characters while editing a cell in Excel and formatting them).fis the font for that part, withname,size(pt),b,i,s(strikethrough) (booleans),u(single/double/singleAccounting/doubleAccounting),color("#RRGGBB"), andva(superscript/subscript). Parts withoutfuse the cell's font. Thetvalues concatenated must equaltext(excluding a leading'), and it is applied only when the entered result is a string cell (formulas, numbers, etc. are entered normally). Asetwithoutrunsmakes the cell an unformatted string. Shorthand:--set B2=100valuesat,rows(array of arrays of strings)Enters each row's strings, with atas the top-left (pasting from outside)clearrangeClears formulas and values (keeps formatting). Shorthand: --clearinsertrange,shift(down/right)3:5inserts rows,B:Dcolumns,B2:C3cells, and moves the cells that were there down (rightfor right). Shorthand:--insert(direction with--shift)deleterange,shift(up/left)Deletes rows, columns, or cells and closes the gap with the cells below ( leftfor the right). Shorthand:--deletecopyfrom,fromSheet,toCopy and paste (shifts relative references in formulas; pastes formatting and merged cells too). If tois an integer multiple of the size offrom, it is pasted repeatedlymovefrom,fromSheet,toCut and paste (references to the moved cells and defined names follow) fillrange,dir(down/right)Copies the first row (column) of the range to the rest (Ctrl+D / Ctrl+R) autofillfrom,toFill handle. toisfromextended in one direction (up, down, left, or right). Two or more numbers or dates form an arithmetic series (least-squares line), a single date advances by one day, a string containing a number (Round 1,No.008) increments the number, formulas are copied with relative references shifted, and anything else is repeated. Formatting is copied tooformatrange,setSets formatting. Keys of set:bold/italic/underline/strike/wrap(booleans),fontName,fontSize(pt),color/fill("#RRGGBB";nullis automatic / no fill),align(left/center/right/general),valign(top/middle/bottom),numberFormat(number format code),border(all/outline/thick/top/bottom/left/right/diagonalDown(\) /diagonalUp(/) /none(also removes diagonal borders)),style(cell style:Hyperlinkis Excel's Hyperlink (one of the 8 built-in styles; if the file lacks the style, it is added, as Excel does, as the Normal font with underline and the theme's link color),Normalresets to Normal). A cell with no formatting changes starting from the Normal style's formatting (font, alignment), as in Excel. It can also be applied to whole rows and columns (3:5,B:D)clearFormatsrangeClears formatting (also unmerges) sizerange(B:Dor3:5),pxColumn width / row height. Specified in pixels as the grid draws at 100% (for columns 8 px is one character; for rows 1 px is 0.75 pt). As in Excel, 0 hides, and specifying a size for a hidden row or column shows it again fitrows([[row (from 0), px], ...])Sets rows without a specified height to a height fitted to the font (as in Excel, only htis written andcustomHeightis not added). Rows with a specified height and hidden rows are unchanged. The sheet preview sends this together withformatops that change the font name or size, and withclearFormats, attaching heights measured in the browser (the font's ascent plus descent in integer pixels, plus 2 px)hiderange(B:Dor3:5),hiddenHide and show rows and columns merge/unmergerange,acrossMerge cells ( acrossmerges per row) and unmerge. As in Excel, merging keeps only the contents of the top-left cellpasteSpecialfrom,fromSheet,to,paste(all/formulas/values/formats/allExceptBorders/columnWidths/formulasAndNumberFormats/valuesAndNumberFormats),operation(none/add/subtract/multiply/divide),skipBlanks,transposePaste Special (same as the Excel stand-in's PasteSpecial). Iftois an integer multiple of the size offrom, it is repeated (withtranspose, once from the top-left cell). Formulas are pasted as in Excel: withtranspose, references pointing insidefromgo to the swapped positions (the$of row and column are swapped too), other references without$swap the row and column of their offset from the cell, and references with$stay as they are. Pasting formulas withoperationmakes formulas combined with the destination (=100+(B1*2),=(C1*3)+(B1*2))sortrange,by(column letter) anddesc, orkeys([{ "by": "B", "desc": true }, ...]; up to 64, earlier ones take priority),headerSorts rows. If rangeis a single cell, sorts the filter range containing that cell, or if none, the current region. Ifheaderis omitted, it is inferred whether the first row is a headerfilterrange, oroff: trueSets (a single cell means the current region) and removes an AutoFilter filterBycolumn(column letter), andvaluesandblanks,criteria([[operator, value], [operator, value]]; operators are=<>>>=<<=, and values may use*?) andand(defaulttrue),toporbottom(count) andpercent, orclear: trueFilters a filter column (keeps rows whose display is any of values, rows with empty cells ifblanks, rows satisfying one or two comparisons, or the top/bottom rows) and clears it. It is written to the file asfilters/customFilters/top10macroobject(object name) orshape(the VML shape number of a form control; 1025 for_x0000_s1025),macro(Sheet1.button1Click)Assigns a macro ( OnAction) to a shape, picture, chart, or form control. Writes the drawing'smacroattribute and, for form controls,[0]!<macro>into the sheet'scontrolPrmacroand the VMLx:FmlaMacro. Cells are not changedfreezeat(one cell), oroff: trueFreezes and unfreezes panes. Freezes the rows above and the columns to the left of at(A2is the top row,B1the first column,A1does not freeze). Rewrites thepaneandselectionof the sheet's firstsheetViewin the same form as Excel, and setstopLeftCellto A1. Cells are not changedtablerange,header(defaulttrue),nameCreates a table (Ctrl+T). If rangeis a single cell, the filter range containing that cell, or if none, the current region. Whole rows and columns are narrowed to the used range. Ifheaderisfalse, cells are inserted above the range (shifting down) and the headings "Column1", "Column2", … are entered. As in Excel 2021, headings that are empty become "Column", and those equal to an earlier one (case-insensitive) get appended ( is a single counter shared by both: from 1 (2 or more when appended), the next after each name made; numbers that collide with other headings in the row are skipped; [q, , q, ]becomes[q, Column1, q2, Column3]), and non-string headings (numbers, formulas) become strings as displayed. If the name is omitted, it is "Table" (not colliding with other tables or defined names). Adds the table part ( xl/tables/table<n>.xml, styleTableStyleMedium2) and the sheet'stableParts, relationship, and content type. If the sheet's filter overlaps the range, it is removed. Ranges overlapping other tables or merged cells are refusedlinkrange,url(web page, file,mailto:) orto(location in the workbook:Sheet2!A1, a name),display,tip, oroff: trueInserts or replaces (Ctrl+K) and removes a hyperlink. Removes the hyperlinkentries in the sheet'shyperlinksthat overlap the range and adds the new one (urlis written to the sheet's relationships withTargetMode="External"; relationships no longer used are removed). Cell contents and formatting are not changed (the sheet preview sends the entry of the display string and, as Excel does, the cell style "Hyperlink" (styleofformat) as separate edits, and resets to Normal when removing a link)noteat(one cell),text,author, oroff: trueAdds, edits, and deletes a note (comment). Rewrites the commentin the sheet's comments part (creating the part if absent), and for a new note adds a note frame to the VML drawing (hidden; as with Excel's "New Note", 128 × 79 pixels, starting 15 pixels in from the next column and one row up (for a cell in row 1, row 1); the anchor is computed from the sheet's column widths and row heights) (if absent, creates the VML drawing and the sheet'slegacyDrawing, with shape numbers in a block not colliding with other VML drawings). Cells with threaded comments are refused (edit in Excel)shapeshape(rect,roundRect,ellipse,triangle,rtTriangle,diamond,parallelogram,trapezoid,pentagon,hexagon,octagon,rightArrow,leftArrow,upArrow,downArrow,star5,heart,smileyFace,wedgeRectCallout,wedgeRoundRectCallout,wedgeEllipseCallout,textBox,line,arrow; defaultrect), position ("Object position" below),text,flipH/flipVInserts a shape, text box, line, or line arrow (Insert > Shapes). Appends to the end of the sheet's drawing part what Excel writes for a new shape ( twoCellAnchor, the theme'saccent1fill and line; a text box is white with a border and text at the upper left). If the sheet has no drawing, creates the drawing part (xl/drawings/drawing<n>.xml), relationship, content type, and the sheet's<drawing>. As in Excel, the name is the kind and number, like "Oval 1" (the object's number − 1).texthas one paragraph per line. If the size is omitted, it is the size Excel 2021 places on a click: 96 × 96 pixels (isosceles triangle 111.36 × 96, left/right arrows 102.72 × 50.88, up/down arrows 50.88 × 102.72, line and line arrow a 96 × 96 diagonal, text box 144 × 36).flipH/flipVmean a line drawn from right to left or bottom to toppicturedata(base64; adata:URL is also accepted) orfile(path), positionInserts a picture (PNG, JPEG, GIF, BMP; the format is determined from the file's leading bytes) (Insert > Pictures). Puts the picture at xl/media/image<n>.<extension>, adds the drawing relationship and the extension's content type, and adds it to the drawing as "Picture" with "move with cells but don't size" ( editAs="oneCell") and a locked aspect ratio, as in Excel. If the size is omitted, it is the size obtained from the picture's resolution (PNG pHYs, JPEG JFIF, BMP; 96 dpi if absent and for GIF) converted to pixels at 96 dpi, as in Excel (if only one dimension is given, the aspect ratio is kept). Up to 64 MBobjectname(object name) orshape(the shape number of a form control; 1025 for_x0000_s1025), and some of: position (move/resize),text(shape text),textAnchor(vertical text alignment;ttop,ctrmiddle,bbottom),textWrap(whether text wraps inside the shape),inset(text margins; those to change of{"left": 7.2, "top": 3.6, "right": 7.2, "bottom": 3.6}; points),fill("#RRGGBB";nullis no fill),line(line color;nullis no line),lineWidth(line width; points),shadow(outer shadow; those to change ofcolor,transparency(%),blur(points),angle(°),distance(points);nullis none),glow(color,transparency,size(points)),reflection(transparency,size(%),blur,distance),placement(object positioning;twoCellmove and size with cells,oneCellmove but don't size with cells,absolutedon't move or size with cells),print(print the object),locked(lock),lockText(lock text; shapes only),rotation(clockwise angle),flipH/flipV(flip),adjust(adjustment values of a preset shape; name and value like{"adj": 25000}),order(frontbring to front,forwardbring forward,backwardsend backward,backsend to back),delete: true(delete)Modifies and deletes a drawing object (shape, picture, chart, group; for one wrapped in mc:AlternateContent, the whole). Moving rewrites the anchor (from,to,pos,ext) and the shape'sxfrm, and if the size is omitted, the current size is kept. Text applies only to shapes (sp) and replaces the paragraphs keeping the first paragraph's paragraph and character formatting. Vertical alignment, wrapping, and margins are written to the shape's (sp)bodyPrasanchor,wrap(square/none),lIns,tIns,rIns,bIns(EMU) (for a shape without text, an emptytxBodywith center alignment is created). Fill and line are written to the shape'sspPrin schema order (shape geometry, then fill, thenln) and take precedence over the shape's style (style) (fill for shapes and pictures; line for shapes, lines, and pictures; line color and width can be changed independently, and other children oflnsuch as arrowheads are kept). Positioning is written to the anchor'seditAs(twoCellremoves the attribute;oneCellAnchorandabsoluteAnchorare rewritten as atwoCellAnchorat the current position), print and lock to theclientDatafPrintsWithSheetandfLocksWithSheet(off is"0", on removes the attribute), and text lock to the shape's (sp)fLocksText. As in Excel, after edits that change column widths or row heights (hide, unhide, and filtering too), anchors are rewritten so thateditAs="oneCell"objects keep their size andabsoluteobjects keep their position and size (for row and column insertion and deletion,twoCellmoves and stretches,oneCellonly moves,absolutestays). Effects are written to theouterShdw(blurRad,dist,dir, coloralpha),glow(rad), andreflection(stA,endPos,blurRad,dist) of theeffectLstinspPr(created after the fill and line if absent), with unspecified values taking the current ones (when newly applied, Excel's first style: shadow is Outer, Offset: Bottom Right; glow is 5 pt, Accent 1; reflection is Reflection (weak): Touching).nullremoves that effect (an emptyeffectLstis kept, so it takes precedence over the effect of the shape's style). Other effects (inner shadow, blur, 3-D, etc.) are kept. Shapes and groups witheffectDagare refused. Rotation and flip go toxfrm'srot,flipH,flipV(0° and no flip remove the attribute). Adjustment values are written to theavLstofprstGeomas<a:gd name="adj" fmla="val 25000"/>(replacing the one with the given name and keeping other adjustments; creatingavLstif absent; non-preset shapes, pictures, groups, and charts are refused). As in Excel, the anchor of an object rotated 45°–135° or 225°–315° is the object's box rotated 90° about its center (width and height swapped) (xfrmis the pre-rotation box). The z-order is the order within the drawing, and the object's element is moved. Deleting also removes relationships used only by the object and parts no longer referenced from anywhere (pictures, charts and their style and color parts) and their content types. Chart formatting and rotation, group fill and line, and line fill are refused. Form controls can be moved, resized, and deleted, and changed intext(text of buttons, check boxes, option buttons, labels, group boxes),link(linked cell;nullor empty unlinks),items(input range of list and combo boxes),checked(check boxes, option buttons),selected(number of the selected item in list and combo boxes; 0 is none; up to the number of cells in the input range),value,min,max,step(spin buttons, scroll bars),page(scroll bars), and for buttonsfont(name,size,bold,italic,underline,strike),foreColor(text color;nullis automatic),textAlign(horizontal;left,center,right,justify,distributed),textVAlign(vertical;top,center,bottom,justify,distributed),inset(margins; points),insetAuto(automatic margins), for those with text (buttons, check boxes, option buttons, labels, group boxes)lockText(lock text), and for all form controlsplacement,print,locked,altText(alternative text) (fill, rotation, etc. are refused; settings not applicable to the kind are refused too). A button's font and alignment are written to the VML text box (thetext-alignof thediv, one per line, and theface,size(1/20 pt),coloroffont, andb,i,u,s) andx:TextHAlignandx:TextVAlign, the property part'stextHAlignandtextVAlign, thealgnof paragraphs and the characterrPr(sz,b,i,u,strike,solidFill,latin,ea) in the copy in the drawing, andbodyPr'sanchor; margins to the VMLv:textbox'sinset(points) and the shape'so:insetmode(custom/auto), and the copy'sbodyPrlIns,tIns,rIns,bIns. Text lock is written to the VMLx:LockText(off isFalse), the property part'slockText(on is"1"), and the copy'sfLocksText; placement, print, lock, and alternative text are written to the sheet'scontrolPrand the VML as for ActiveX controls, and also to the copy's anchoreditAsandclientDatafPrintsWithSheetandfLocksWithSheet. Settings are written to both the VMLx:ClientData(FmlaLink,FmlaRange,Checked,Sel,Val,Min,Max,Inc,Page) and the property part (fmlaLink,fmlaRange,checked="Checked",sel,val,min,max,inc,page), and text to the VML text box (onedivper line; keeping the first paragraph's formatting and font) and the copy in the drawing. It is refused unless minimum ≤ maximum, and if changing the range puts the current value outside it, the value is clamped to the range (a specified current value that is outside is refused). The state of a check box with a linked cell (TRUE/FALSE), the number of the selected item in a list or combo box, and the value of a spin button or scroll bar are also entered into the linked cell, just as when operating the control in Excel (since the cell's value is what the control displays). ActiveX controls (Microsoft Forms 2.0 ones) can also be moved, resized, and deleted, and changed intext(Caption;Valuefor text, list, and combo boxes),checked(Valueof check boxes, option buttons, toggle buttons),link(LinkedCell),items(ListFillRangeof list and combo boxes),value,min,max,step(Position,Min,Max,SmallChangeof spin buttons and scroll bars),page(LargeChangeof scroll bars), and properties (Microsoft Forms):font(those to change ofname,size(points),bold,italic,underline,strike; not available for spin buttons and scroll bars),foreColor(text color),backColor(background color; both"#RRGGBB",nullis the kind's default color),backStyle(opaque,transparent),enabled,wordWrap(not for list and combo boxes),autoSize(not for list boxes), and the on-sheet settingsplacement,print,locked,altText(alternative text; empty clears it). The position rewrites the VML shape (ObjectType="Pict"),<controls>, the copy's anchor, and the control data's size (HIMETRIC).Captionand the like are written to the control data (the MS-OFORMS stream inxl/activeX/activeX<n>.bin; only when its records are in a readable form; pictures and fonts after the records are kept as they are) or the part'sax:ocxPr(persistPropertyBag), andLinkedCellandListFillRangeto the sheet'scontrolPrlinkedCellandlistFillRange. Fonts go to theTextPropsafter the data records (after the picture):FontName,FontHeight(twip),FontEffects(bold 1, italic 2, underline 4, strikethrough 8; also 700 / 400 forFontWeightif present),ForeColorandBackColorare OLE_COLOR (0x00BBGGRR; the default is, as Excel places on a sheet, the window color for text, list, and combo boxes, check boxes, option buttons, and labels, and the button color for the others (command buttons, toggle buttons, spin buttons, scroll bars), as system colors), andBackStyle,Enabled,WordWrap,AutoSizeare written to bits ofVariousPropertyBits(those in apersistPropertyBagare refused). Placement goes to the sheet'scontrolPranchormoveWithCellsandsizeWithCells, VMLx:MoveWithCellsandx:SizeWithCells(present when not moving or sizing), and the copy's anchoreditAs; print and lock tocontrolPrprintandlocked(off is"0") and VMLx:PrintObjectandx:Locked(off isFalse); alternative text tocontrolPraltText. Control data inpersistStorageis not changed (refused). If there is a linked cell, the state, text, value of list and combo boxes, and value of spin buttons and scroll bars are also entered into the cell. Deleting also removes the control's part and data and the control's substitute picture (controlPrr:id, VMLv:imagedata; those not used elsewhere). The control's substitute picture (what Excel shows when it cannot use ActiveX) is not redrawn. Renaming (which VBA code references by name) is not done. Embedded objects are refused (do it in Excel). If several objects have the same name, the first one is used. Changes are applied in this order: position and text, formatting and rotation, z-ordercontrolcontrol(button,checkBox,optionButton,label,groupBox,listBox,comboBox,spinner,scrollBar; defaultbutton), position,text(displayed text; default is the name),macro(Module1.run),link(linked cell;$B$2,Sheet2!$A$1),items(range of items for list and combo boxes),checked,value,min,max,step,page(spin buttons, scroll bars; 0–30000),horizontal(horizontal scroll bar),font(text font;{"name": "Yu Gothic UI", "size": 10}; default is the workbook language's: MS PGothic 11pt in a Japanese workbook, Calibri 11pt otherwise. A workbook is Japanese when the first font of its styles (its standard font) is a Japanese face or has character set 128. Notes (note) likewise get MS P Gothic 9pt or Tahoma 9pt)Inserts a form control (Developer > Insert > Form Controls). For those with text (buttons, check boxes, option buttons, labels, group boxes), fontbecomes the VML text box'sfontfaceandsize(1/20 pt) and the copy'srPrsz,latin,eain the drawing. A control inserted in the sheet preview uses 10pt of the system UI font (Windows' SystemFonts.MenuFont; on Japanese Windows 10 and later, Yu Gothic UI), as the form designer does. A control is stored split across the VML drawing's shape (x:ClientData) in the sheet, the entry in the sheet's<controls>that Excel 2010 and later save, the property part (xl/ctrlProps/ctrlProp<n>.xml), and a hidden copy in the drawing (a14:compatExt). A new control is written to match the form in which the sheet stores other controls: for a sheet without<controls>, only the VML shape (the same form as Excel 2007); for a sheet with it, all four places (the same form as Excel 2010 and later). If there is no VML drawing, one is created with a block of shape numbers that does not collide with other VML, and the sheet's<legacyDrawing>is added. The shape number is in the last block of the VML drawing, after other shapes, controls, and drawing objects. As in Excel, the name is "Button 1", "Check Box 2", … (the kind and the number within the shape-number block). If the size is omitted, it is the size Excel places on a click. The default maximum of a spin button is 30000, as in Excel (100 for a scroll bar), and buttons, labels, and spin buttons move and size with cells. If there is a linked cell, thecheckedof a check box and thevalueof a spin button and scroll bar are also entered into that cell (since the control displays the cell's value). Moving (position inobject) rewrites the VMLx:Anchorandstyle, the<controls>anchor, and the copy's anchor together, and deleting (deleteinobject) removes the VML shape, the<controls>entry (the whole<controls>if it was the last one), the property part with its relationship and content type, and the copyactiveXcontrol(commandButton,comboBox,checkBox,listBox,textBox,scrollBar,spinButton,optionButton,label,toggleButton; defaultcommandButton), position,name(the control's name; starts with a letter, letters, digits, and_, up to 40 characters; default, as in Excel, isCommandButton1etc., the kind's name with a number that collides with no object name on the sheet),text(Caption; default is the name;Valuefor text boxes and combo boxes; cannot be specified for list boxes, scroll bars, and spin buttons),font(name,size(points), and an optionalcharset(character set; default is Shift_JIS, 128, in a Japanese workbook and 0 otherwise); default is MS UI Gothic 9pt in a Japanese workbook and Tahoma 8pt otherwise; not used for spin buttons and scroll bars)Inserts an ActiveX control (Microsoft Forms 2.0) (Developer > Insert > ActiveX Controls). It is written in the form in which Excel 2010 and later save a control placed on a sheet: the control part ( xl/activeX/activeX<n>.xml;ax:classidis the kind's CLSID,ax:persistence="persistStreamInit"), the data (activeX<n>.bin) its relationship (activeXControlBinary) points to (the CLSID followed by an MS-OFORMS control stream: records ofCommandButton,MorphData,Label,SpinButton,ScrollBar.VariousPropertyBits, and forMorphDatatheDisplayStyle, colors, and combo box and list box settings are those of a new control (the same as whatras-formwrites for a new control).Caption(for check boxes, option buttons, toggle buttons,Valueis set to0) and the size (HIMETRIC) are written, and for those withTextProps,font; the default is the same font as the VBA editor (MS UI Gothic 9pt in a Japanese workbook, Tahoma 8pt otherwise). Those inserted in the sheet preview are 10pt, as in the form designer (the system UI font in VS Code, Yu Gothic UI in the playground)), the content types (anOverrideofapplication/vnd.ms-office.activeX+xmlfor the part; for the data, aDefaultofapplication/vnd.ms-office.activeXif there is noDefaultfor extensionbin, or anOverrideifbinis for the VBA project), the sheet's<controls>entry (anmc:AlternateContentwithRequires="x14"containingcontrolPr(defaultSize="0" autoLine="0" autoPict="0") and the anchor (moveWithCells="1"), and inmc:Fallbackthecontrolthat Excel 2007 reads. If there is no<controls>, it is created at the schema position. If<controls>is inside anmc:AlternateContentand itsmc:Fallbackalso has<controls>, the entry is added there as well) and its relationship (control), and the VML drawing's shape (ObjectType="Pict",idis the control's name,o:spidis the shape number,x:SizeWithCells,x:CF,x:AutoPict; the VML drawing and shape numbers are the same as for form controls). The hidden copy in the drawing and the control's substitute picture (controlPrr:id, VMLv:imagedata) are not written. When the size is omitted, command buttons and toggle buttons are 96 × 32 px, list boxes 96 × 72 px, scroll bars 17 × 96 px, spin buttons 17 × 32 px, and the others 96 × 24 px. An inserted control, like existing ActiveX controls, can be moved, resized, deleted, and have its properties changed withobject, is drawn in the grid (with the kind inactivex), and is also included in the compiler's list of controls (§12.2.1). It is refused if an object with the same name exists on the sheetsheetaction(add,copy,remove,rename),sheet(foradd, the sheet after which the new sheet is placed; for others, the target sheet),name(tab name;add,rename; if omitted forcopy,<original name> (2)),codeName(code name foradd,copy; default is the first freeSheet<number>)Inserts, makes a copy of, deletes, and renames sheets (right-click on a sheet tab). Rewriting the workbook file is the same as ras sheet(§14.16) (references in formulas and defined names are rewritten too), and the files inobjects/are not changedtabColorcolor("#RRGGBB";nullis no color)Sheet tab color. Rewrites the sheet's sheetPrtabColor(rgb="FFRRGGBB") (creatingsheetPrif absent)conditionalrange(several ranges separated by spaces or,; forclear, the whole sheet if omitted),type, settings per type,format,stop,clearConditional formatting (Home > Conditional Formatting). type:cellIs(operator:between,notBetween,equal,notEqual,greaterThan,lessThan,greaterThanOrEqual,lessThanOrEqual; one value invalues(two forbetweenandnotBetween); as in Excel's dialog, a leading=makes it a formula, numbers are numbers, and anything else is a string),expression(formula),containsText,notContainsText,beginsWith,endsWith(text),containsBlanks,notContainsBlanks,containsErrors,notContainsErrors,duplicateValues,uniqueValues,top10(rank(default 10),bottom,percent),aboveAverage(below,equal,stdDev(1 to 3 standard deviations above (below withbelow))),timePeriod(period:today,yesterday,tomorrow,last7Days,thisWeek,lastWeek,nextWeek,thisMonth,lastMonth,nextMonth),dataBar(colorswith one color.solid: solid fill (default is gradient),barBorder: border color (falsefor no border; if omitted, gradients get a border of the same color as the bar and solid bars no border),direction: bar direction (context,leftToRight,rightToLeft), negative values and axis settings (negativeFill,negativeBorder: fill and border color of negative bars (default red),negativeFillSame,negativeBorderSame: same color as positive bars,axis: axis (automatic,middle,none),axisColor: axis color (default black))),colorScale(colorswith 2–3 colors: minimum, (midpoint (50th percentile),) maximum),iconSet(icons: an icon set such as3Arrows,3TrafficLights1,4Rating,5Quarters—the 17 kinds of Excel 2007 plus Excel 2010's3Stars,3Triangles,5Boxes—,reverse,iconOnly). The thresholds of data bars (barOnly: show bar only), color scales, and icon sets arethresholds([{ "type": "num", "value": 10, "gte": true }, ...].type:auto(automatic, for data bars),min(minimum),max(maximum),num(number),percent(percent),percentile(percentile),formula(formula).valueis a number or a formula starting with=(percent and percentile are 0–100). Data bars take two (minimum and maximum), color scales the same number as colors (the middle ones other thanminandmax), icon sets as many as icons, starting from the smallest icon (the first is the start of the smallest icon;gte: false makes it ">"). If omitted, Excel's defaults apply (data bars automatic, color scales minimum and maximum with the midpoint at the 50th percentile, icons divided equally by percent)).format(required except for data bars, color scales, and icon sets; as in the "Format Cells" of an Excel rule, items not specified stay as the cell's formatting):numberFormat(number format code),color(font color) andfill(background color) ("#RRGGBB"),bold,italic,strike(true;falseremoves it from the cell's formatting),underline(single,double,singleAccounting,doubleAccounting,none;trueissingle),pattern(pattern kind:darkGray,mediumGray,lightGray,gray125,gray0625,darkHorizontal,darkVertical,darkDown,darkUp,darkGrid,darkTrellis,lightHorizontal,lightVertical,lightDown,lightUp,lightGrid,lightTrellis) andpatternColor(pattern color),borders(per-side borders{ "left": { "style": "thin", "color": "#RRGGBB" }, "bottom": "dashed", ... }; sides areleft,right,top,bottom; lines arethin,hair,dotted,dashDotDot,dashDot,dashed; omitting the color means automatic),border("#RRGGBB": thin line on all four sides). The format of rules is also returned with the same keys in theconditionalRuleslist. As in Excel, acfRule(priority 1; existing rules are each lowered by one) is added to the sheet's<conditionalFormatting>, and the format to<dxfs>inxl/styles.xml. Rules for text, blanks, errors, and dates also get the formula Excel writes (referencing the top-left cell of the range). As in Excel 2010 and later, data bars write their appearance (fill, border, automatic, bar direction, negative values and axis) to the sheet'sextLstas anx14:cfRule, linked byx14:id. Excel 2010 icon sets (stars, triangles, boxes) are written only toextLst."clear": trueis "Clear Rules": removes the range's cells from the rule's range (sqref; also thexm:sqrefof Excel 2010 rules inextLst), and deletes rules that have no cells leftconditionalRulesrules(array of rules, highest priority first)Manages conditional formatting rules. Reorders the sheet's rules in the order of rules(priorities 1, 2, …) and deletes rules not inrules. Each element:id(an existing rule;m<n>that the grid data'scondRulesholds in priority order (the order of the sheet'scfRule) orx<n>(rules only in Excel 2010'sextLst)),range(changes what it applies to),stop(stop if true), andtypewith the same settings asconditional(rewrites the rule; withoutid, it is a new rule and needsrange). Rules that are kept stay as the original XML (onlypriority,stopIfTrue,sqrefare rewritten), and a<conditionalFormatting>is written per rule. Rules that are half inextLst(data bars, etc.) and rules only in Excel 2010 havexm:sqrefandpriorityrewritten to match, and are deleted together when the original rule is deletednamename,ref(reference range;=Sheet1!$A$1:$B$5, constant, formula),scope(sheet name; omitted or null for the workbook),comment,old({ name, scope }: the name to change),deleteDefined names (Formulas > Name Manager, Define Name). Without old, a new name (an error if the same name exists for the same scope, if the name is unusable, or if the reference range is unreadable); withold, changes that name toname,ref,comment(the range is unchanged; renaming also rewrites formulas that use the name to the new name);delete: truedeletesname(scopescope). RewritesdefinedNamesinxl/workbook.xmland makes Excel recalculate formulas when it opens the fileObject position (
shape,picture,object):range(B2:D6; exactly overlays the cells of the range), orat(one cell) withdxanddy(pixels from the cell's top-left) andwidthandheight(pixels). Pixels are the size the grid draws at 100%, converted from column widths and row heights to an anchor (cell and offset within the cell; EMU).Meaning of edits: The edits themselves are done by the Excel stand-in (§14.10.8,
crates/ras-workbook). Inserting and deleting rows, columns, and cells re-targets references in formulas and defined names on all sheets, and inserted rows and columns get the formatting of the previous row or column, as in Excel. Formulas that depend on edited cells, including those on other sheets, are recalculated and their values written to the file. Edits that Excel refuses, such as moving only part of a merged cell or array formula, or an insertion that pushes non-empty cells off the sheet, are errors and change nothing.Writing: The file is not saved from the stand-in's workbook (saving with umya-spreadsheet would drop what it does not hold (the VML of form controls, etc.; the fork's
FORK.md) and change how what it does hold is written). The loaded workbook and the edited workbook are compared cell by cell (formulas, values, formatting), and only the changed cells are written back into the original file's sheet XML. Everything else (the VBA project, shapes and pictures, styles, shared strings, unchanged sheets) is left as the original bytes, part by part.- Cells that did not change are written as the original XML except for the address, even if their position changed through row and column insertion or deletion (shared strings, rich text, format numbers). For a cell whose only change is formatting, only the format number (
s) is rewritten. Newly written strings are inline strings (t="inlineStr"). Rich text writes, for eachrof the inline string, anrPr(rFont,charset(128 for non-ASCII names such as Japanese),b,i,strike,color,sz,u,vertAlign, in schema order). Copying, moving, and sorting rich-text cells (when formatting is pasted too) carries the per-character formatting along. - Formatting uses the original file's
xfnumbers. Formatting that the file lacks is added toxl/styles.xml: a format that differs only in number format (such as entering a date) is the originalxfwith the number format attached. Others (formats with changed font, fill, border, or alignment) are made by having umya-spreadsheet write a workbook of only cells with that format, and copying the resultingxfand the fonts, fills, and borders it points to onto the end of the original styles (reusing an element with identical content if one exists). The numbers of existingxfs, cell styles, and differential formats (dxf) do not change. - Column width, hidden state, and formatting rewrite only the relevant columns of
<cols>, and row height, hidden state, and formatting only the attributes of<row>(other attributes such as outline are kept). Filters rewrite<autoFilter>(for conditions the stand-in only preserves, such as filtering by color or icon, the original element is kept) and add, fix, or remove the filter range's name (_xlnm._FilterDatabase). Rows hidden by a filter become<row hidden="1">. - Formulas the stand-in cannot calculate (formulas that call VBA functions, references to external workbooks, etc.; §14.10.8) keep the file's formula as it is (the value is what was saved). On insertion and deletion, their references are re-targeted too. They disappear only when overwritten or cleared.
- Shared formulas (the form in which Excel stores copied formulas) are expanded into per-cell formulas when that sheet is rewritten. Dynamic array formulas are written, when newly entered, as array formulas (
t="array") (existing ones keepcm). - The calculation chain (
xl/calcChain.xml) is deleted andfullCalcOnLoad="1"is written tocalcPr(Excel recalculates when it opens; the written values are the stand-in's calculation results). - Edits to shapes and pictures (
shape,picture,object) do not rewrite cells. They rewrite only the sheet's drawing part (created if absent) with its relationships, content types, and picture parts, and, when a drawing is newly created, the sheet's<drawing>.
- Cells that did not change are written as the original XML except for the address, even if their position changed through row and column insertion or deletion (shared strings, rich text, format numbers). For a cell whose only change is formatting, only the format number (
What follows insertions and deletions: The sheet's column widths and formatting (
cols), row heights, merged cells, conditional formatting, data validation, filters (including filtered columns), sort ranges, hyperlinks, protected ranges; the extension (extLst) conditional formatting, data validation, and sparklines; defined names (including built-in names such as print areas); table ranges (row count changes); notes and threaded comments (they move with the cell and are removed when the cell is removed); anchors of shapes, pictures, charts, and controls (for insertion and deletion of whole rows and columns, following the object's "Move and size with cells" setting); the linked cells of form controls and ActiveX controls; chart series references; the source data range of PivotTables; and the conditional formatting and data validation formulas on other sheets.What file rewriting cannot do (reported as an error, directing you to do it in Excel): inserting or deleting columns across table columns, deleting a table's heading row or a whole table, and inserting or deleting on a sheet with a PivotTable. Up to 200,000 cells can be entered at a time.
Safety: Before writing, the rewritten file is read back with the Excel stand-in, and it is verified that the presence and values of cell formulas match the edited workbook (if they do not match, it is an error and the file is not changed). Writing is the same as §14.9.3 (write alongside, then replace; for the project's workbook, the previous file is kept in
build/backup/). A workbook open in Excel (an owner file~$Book.xlsmexists, or it cannot be opened for writing) is not rewritten and is an error. An edit that changes nothing (entering the same value) does not write the file.-o <file>: Writes the rewritten workbook to another file and leaves the original workbook unchanged.--view: Prints the grid of the rewritten workbook (the same HTML asras book view --stdout) to standard output.Exit code: 0 on success; 1 for an edit that cannot be done or a workbook open in Excel (the reason goes to standard error); 2 if the workbook cannot be read.
The editor's sheet preview: The workbook files shown by "RAS: Show Workbook in Sheet Preview" and "RAS: Show Sheet Preview" can be edited in the sheet preview (result workbooks under
build/and the display during debugging are read-only). The page sends operations to the extension as the edits above ({ type: "edit", ops: [...] }), and the extension runsras book edit <workbook> --ops-file - --view --editableand redraws the page with the returned HTML (keeping the selection, scroll position, and displayed sheet). The reason an edit cannot be done is shown below the sheet preview. The HTML file thatras book viewcreates (opened in a browser) is read-only.- Selection: click, Shift+click, or drag for a cell range; row numbers and column headings for whole rows and columns; the top-left corner for everything. Arrow keys, Tab, Enter, Home, Ctrl+Home, Ctrl+arrows (edge of data), PageUp / PageDown, Ctrl+A. A merged cell is treated as one cell. Ctrl+click and Ctrl+drag add ranges (multiple separate ranges; formatting, clearing, Ctrl+Enter input, and hiding rows and columns are done per range, and the status bar counts all ranges; copy, paste, insert, delete, sort, merge, and the like give "That command cannot be used on multiple selections." as in Excel).
- Move and copy: dragging the border of the selection (cells) moves (
move), and with Ctrl held copies (copy). When moving onto cells that have data, it asks "There's already data here. Do you want to replace it?". - Per-character formatting: while entering or editing a cell (except formulas), select some characters and use the ribbon's font name, font size, increase/decrease size, bold, italic, underline, font color, Ctrl+B / Ctrl+I / Ctrl+U / Ctrl+5 (strikethrough), or Ctrl+1 (a Format Cells with only Font: font name, style, size, underline, color, strikethrough, superscript, subscript) to set formatting on just those characters (
runsofset). Setting it without selecting characters becomes the formatting of the characters typed next. Typed characters take the formatting of the character before the caret, as in Excel. A string with formatting can be edited with F2 or double-click keeping per-character formatting (also when editing in the formula bar), and typing over it makes an unformatted string. While editing, the ribbon buttons show the formatting of the character at the caret. Starting with=does not use per-character formatting (formula entry). - Entry: typing starts entry by overwriting; F2, double-click, or the formula bar edit the current contents. Enter confirms and moves down, Tab moves right (Shift reverses), Ctrl+Enter enters into all selected cells, Alt+Enter inserts a line break in the cell, Esc cancels. Ctrl+; enters today's date and Ctrl+: the current time (while editing, at the caret position).
- Function autocomplete: while entering a formula, it lists functions (those the Excel stand-in can calculate) and defined names starting with the word being typed; choose with ↑↓ and insert with Tab (functions also get
(). It shows the arguments of the function at the caret (VLOOKUP(lookup_value, table_array, ...); argument names are in English) and bolds the current argument. - Formula references: for input beginning with
=,+, or-, when the caret is after an operator,(,,,:, or a space, clicking a cell, row number, or column heading inserts that reference (drag or Shift+click for a range; a merged cell gives the merged range), and during entry (not F2 editing) arrow keys move the reference from the active cell (Shift for a range, Ctrl for the edge of data). While you keep using click or arrows, the same reference is replaced; typing a character ends it. F4 cycles the$of the reference at the caret in the order A1 → $A$1 → A$1 → $A1 (for whole rows and columns, with and without $). The references of the formula being entered are shown in the grid with color-coded frames (the one being inserted is dotted). - Data validation: the list button (Alt+↓) shows the list of values and enters the chosen one. A value not in the list (formulas excepted) cannot be entered in a list cell whose error alert style is "Stop" (a message is shown and entry continues; Excel's "Retry"). The "Warning" and "Information" styles are entered without checking. Paste is not checked (as in Excel).
- Replace (Ctrl+H, "Replace" in Find): the matching part is replaced with the "Replace with" string and re-entered into the cell's formula (for value cells, the entered content) (
set). "Replace" replaces if the active cell matches and then finds the next; "Replace All" replaces all matching cells in one edit (undoable in one step). - Delete / Backspace clear formulas and values. Ctrl+C / Ctrl+X / Ctrl+V copy, cut, and paste (cells copied in the grid are
copy/move; text from other applications is pasted asvalues, split by tabs. Copied cells also go to the clipboard as tab-separated text of the displayed values). Ctrl+D / Ctrl+R copy down and right. Cells copied in the grid are pasted aspasteSpecialvia right-click "Paste Values" and "Paste Special…" (Ctrl+Alt+V; paste, operation, skip blanks, transpose). - Insert and delete: Ctrl++ (Ctrl+Shift+;) and Ctrl+-, or the right-click menu (cut, copy, paste, insert, delete, clear formulas and values). If whole rows or columns are selected, those rows or columns are used; if cells are selected, the same dialog as Excel (shift cells right, shift cells down, entire row, entire column) chooses the direction.
- Ribbon (above the formula bar. The same tabs, groups, and button layout as Excel's ribbon. Double-clicking a tab collapses it. On a page that cannot be edited, buttons that edit are disabled and it starts collapsed):
- Home: Undo (undo and redo), Clipboard (Paste; the ▾ offers Paste Values, Paste Formatting, Transpose, and Paste Special…; Cut, Copy), Font (font name (the ▾ lists the fonts installed on the system. In VS Code the extension gets them from the OS (PowerShell
InstalledFontCollectionon Windows,NSFontManageron macOS,fc-liston Linux); in the playground via the browser's Local Font Access API, which asks permission the first time the list is opened. If it cannot be obtained, the main Office fonts are used. A name can also be typed), font size, increase and decrease font size, bold, italic, underline, borders (bottom, top, left, right, no border, all borders, outside borders, thick outside borders; the button is the last border chosen), fill color, font color (the button is the last color chosen)), Alignment (top, middle, bottom, align left, center, align right, wrap text, merge & center; the ▾ offers merge across, merge cells, unmerge cells), Number (number format (General, Number, Comma, Currency, Percentage, Date, Time, Text), currency format, percent style, comma style, increase / decrease decimal places), Cells (Insert, Delete: cells…, sheet rows, sheet columns. Format: row height…, AutoFit row height, column width…, AutoFit column width, hide / unhide rows / columns), Styles (Conditional Formatting: split into submenus as in Excel, and each "More Rules…" opens a new formatting rule of that kind. Highlight Cells Rules (greater than, less than, between, equal to, text that contains, a date occurring, duplicate values), Top/Bottom Rules (top and bottom 10 items and 10%, above and below average), Data Bars (6 colors each of gradient fill and solid fill), Color Scales (12 kinds), Icon Sets (20 kinds, in the same groups (directional, shapes, indicators, ratings) and order as Excel; icons are drawn in Excel's colors and shapes, as in the cell), New Rule… (rule types with the same names and order as Excel (Format all cells based on their values (format style: 2-Color Scale, 3-Color Scale, Data Bar, Icon Sets; the type of minimum, midpoint, and maximum (also Automatic for data bars), value, and color; Show Bar Only, bar appearance (gradient fill, solid fill, and color; no border, solid border, and color; Negative Value and Axis… (fill and border color of negative bars, axis settings and color dialog), bar direction), icon style (chosen from a list of icons in the same order as Excel's dialog), Reverse Icon Order, Show Icon Only), Format only cells that contain (cell value, specific text, dates occurring, blanks, no blanks, errors, no errors), Format only top or bottom ranked values, Format only values that are above or below average (also 1–3 standard deviations above and below), Format only unique or duplicate values, Use a formula to determine which cells to format), with their settings, preview, and Format… (Format Cells: font (style, underline, color, strikethrough), border (none, outline and color), fill (background color), clear). With "Applies to", which Excel lacks, you can specify the cells to apply the rule to (default is the selection; it can also be changed when editing a formatting rule). The format of simple dialogs such as Highlight Cells Rules is one of Excel's default 6 kinds or Custom Format… (Format Cells). Choosing icons one by one and the number format of a format cannot yet be specified), Clear Rules (from selected cells, from the entire sheet), Manage Rules… (the same dialog as Excel. Show formatting rules for (current selection, this worksheet), New Rule, Edit Rule (also by double-click), Delete Rule, ▲▼ to change priority, per-rule format preview, applies-to, and stop if true. When editing data bars, color scales, and icon sets, the threshold type (minimum, maximum, number, percent, formula, percentile) and value, and the icons' ">=" and ">" are also specified. OK writes everything asconditionalRulesedits. Of the rules only in the Excel 2010 and later format, icon sets with individually chosen icons and the like cannot be edited, only deleted, moved, and have their applies-to changed). It is an edit ofconditional. One rule is applied to all the selected ranges), Editing (Fill: down, right. Clear: all, formats, formulas and values. Sort & Filter: sort A to Z, Z to A, Custom Sort… (a dialog sorting by multiple columns. Add and delete levels, whether to use the first row as headers), Filter (Ctrl+Shift+L), Clear. Find & Select: Find…, Replace…, Go To…). Buttons show the formatting of the active cell. As in Excel, strikethrough is not on the ribbon and is toggled with Ctrl+5. - Insert: Tables (Table), Illustrations (Pictures, Shapes), Controls (on an editable page. You choose from the 9 kinds of form controls and draw by dragging on the sheet, like shapes (a click gives the default size; a scroll bar drawn wide is horizontal). ActiveX controls, 10 kinds (
activeX), can be drawn the same way. In Excel they are under "Insert" on the Developer tab. Since opening in VS Code is for development anyway, no Developer tab is provided), Text (Text Box), Links (Link), Comments (New Note, Edit Note, Delete Note), Symbols and special characters. - Shape Format (appears only while a shape, picture, chart, or control is selected): Shape Styles (Shape Fill, Shape Outline; the button is the last color chosen, the ▾ offers colors, none,
#RRGGBB, and for outlines weights of 0.25–6 pt too), Arrange (Bring Forward / Bring to Front, Send Backward / Send to Back, Selection Pane (a list of the sheet's objects in the right pane, front-most at the top; click to select), Align: Align Left, Align Center, Align Right, Align Top, Align Middle, Align Bottom (when two or more are selected; aligned to the edge or center of the whole selection, using the rotated outer frame as it appears), Distribute Horizontally / Vertically (when three or more are selected; the objects at the ends stay put and the spacing is made equal), Snap to Grid (while on, the sides you moved by moving or resizing snap to the nearest cell gridline; dragging with Alt held also snaps), Rotate: Rotate Right 90°, Rotate Left 90°, Flip Vertical, Flip Horizontal, More Rotation Options (rotation in the right pane)), Size (height and width in cm; ▴▾ and ↑↓ change by 0.1 cm; the button at the lower right opens the format in the right pane), Code (for the project's workbook: View Code. Opens or registers the event code of the selected shape or control). Buttons for changes that cannot be done (line fill, chart formatting and rotation, control formatting, rotation, and z-order) are disabled. It hides when the selection is cleared, and the next time something is selected it returns to the same tab. Shapes and controls can be multi-selected with Ctrl / Shift+click (also in the Selection Pane list; click a selected one to remove it), and moving by dragging or arrow keys, Delete, fill, outline, rotation, z-order, and size apply to all selected (those that cannot are skipped). - Formulas: Formula Auditing (Show Formulas. Ctrl+
/ Ctrl+Shift+@), Defined Names (Name Manager (Ctrl+F3. A list of name, value, refers to, scope, and comment; New, Edit, Delete, and changing the Refers to of the chosen name. OK writes asname` edits), Define Name (name, scope, comment, refers to). Renaming also rewrites formulas that use the name). - Data: Sort & Filter (sort A to Z, Z to A, Sort, Filter, Clear).
- View: Zoom (Zoom, 100%, Zoom to Selection), Window (Freeze Panes: freeze, freeze top row, freeze first column, unfreeze).
- Home: Undo (undo and redo), Clipboard (Paste; the ▾ offers Paste Values, Paste Formatting, Transpose, and Paste Special…; Cut, Copy), Font (font name (the ▾ lists the fonts installed on the system. In VS Code the extension gets them from the OS (PowerShell
- Shapes and pictures: In Insert, "Shapes" lets you choose a kind (lines, rectangles, basic shapes, block arrows, stars, callouts) and draw by dragging on the sheet (
shape; a click alone gives the default size. Shift keeps width and height equal and snaps lines to horizontal, vertical, and 45°. Esc cancels). "Text Box" asks for the text after drawing. "Pictures" lets you choose a file and inserts it at the active cell's position (picture; a picture larger than the window is scaled down to fit). Pasting a clipboard image with no text (such as a screenshot) with Ctrl+V also inserts it at the active cell's position. An inserted shape or picture is selected. - Editing shapes, pictures, and charts: A selected object moves by dragging (with Shift, only horizontally or vertically) and is resized with the 8 handles around it (for pictures, the corners keep the aspect ratio; for shapes, Shift keeps it). Arrow keys move it 1 pixel (10 pixels with Ctrl), Delete / Backspace deletes it, and F2, Enter, double-click (for shapes whose events cannot be opened), or right-click "Edit Text…" changes its text (
object; the right pane's Text). Dragging the round handle at the top rotates it (in 15° steps with Shift), and Alt+→ / Alt+← rotate in 15° steps. Preset shapes (rounded rectangles, arrows, callouts, arcs, smiley faces, etc.; those with adjustment handles in the ECMA-376 definition) show yellow adjustment handles, and dragging them changes the shape (adjustofobject). During a drag, the shape itself is changed to the new form to show it (the handle moves too). The handle's position, and the adjustment value that brings the handle closest to the mouse position, are found by the page evaluating the definition's guide formulas (adjustment values are clamped to the handle's minimum–maximum). For a rotated object, the selection frame and handles rotate too, and side handles resize along the object's sides (the opposite side does not move). The right-click menu has "Format Shape", "Bring to Front", "Bring Forward", "Send Backward", "Send to Back", "Rotate". Object formatting is shown not in a dialog but in the right pane, as with the form designer's properties (while selected; if closed with ×, it is not shown until opened again with right-click "Format Shape" etc.), and changed items are written immediately. As with Excel's Format Shape, the pane is divided into icon tabs, with a Code tab last. The order of tabs and the names of items match the Format Cells pane (Number, Text, Fill & Border, Properties), in this order: Text, Fill & Line, Effects, Size & Properties, Code: Text (the control's text (confirm with Ctrl+Enter), font (name, style, size, underline, color), text effects (strikethrough), text alignment (horizontal, vertical), text control (wrap text in shape;WordWrapof ActiveX controls), margins (left, right, top, bottom; buttons also have automatic)), Fill & Line (color, line width), Effects (shadow, reflection, glow), Size & Properties (Size (height, width (cm), rotation (°), flip horizontal, flip vertical,AutoSizeof ActiveX controls), Properties (object positioning, print), Protection (lock, lock text), Alt Text, Control (below)), Code (the object's name and how to refer to it from code (Sheet1.shapes("Oval 1"); for ActiveX controlsSheet1.CommandButton1), events (the registered function, with buttons to view and register code), object model (the names of theShapeobject model, with the current values ofLeft,Fill.ForeColor.RGB,Placement,ControlFormat, etc., shown in a list opened with triangles like browser developer tools. Read-only)). Esc returns to cell selection. Form controls too can be moved and resized with drag, handles, and arrow keys, and deleted with Delete or right-click "Delete" (shapeofobject; formatting, rotation, and z-order are not changed). In the right pane opened by right-click "Format Control" ("Properties" for ActiveX controls), depending on the kind, you change the text (Caption,Value), checked / unchecked, input range, linked cell, selected item, current value, minimum, maximum, incremental change, and page change, and text is changed over the control with F2, Enter, right-click "Edit Text", or double-click (when events cannot be opened), as with shapes (the text of buttons, labels, check boxes, option buttons, and group boxes; theCaptionof ActiveX controls; theValueof text boxes and combo boxes. A caption takes a line break with Enter, a value is confirmed with Enter. Esc, Ctrl+Enter, or a click elsewhere confirms. A list box's value is changed in the pane). ActiveX controls are likewise moved, resized, and deleted. Embedded objects are not moved (they can be selected). The grid reads the anchor of an object rotated 45°–135° or 225°–315° as a rotated box, as Excel does. - Column width and row height: Drag the right edge of a column heading or the bottom edge of a row number (this changes the selected columns and rows together). Double-clicking the edge fits to the drawn cell contents. The right-click menu of headings has "Column Width…", "Row Height…", "Hide", and "Unhide".
- Filter: The button at the lower right of a heading cell (the same ▼ square as Excel) opens a menu in the same layout as Excel (Sort A to Z, Z to A, "Clear Filter From "heading"", a search box, a checklist of values to show; dates as a tree of year, month, and day, including "(Blanks)"). Columns with many dates show a "Date Filters" submenu, columns with many numbers "Number Filters" (including Top 10…), and the others "Text Filters", which open Excel's "Custom AutoFilter" (up to two conditions with AND / OR: equals, is greater than, is greater than or equal to, begins with, contains, etc.) and "Top 10 AutoFilter". The button of a filtered column becomes a funnel icon.
- Fill handle: Dragging the ■ at the lower right of the selection does
autofill, and double-clicking copies down to the bottom of the data in the adjacent column. - Sheet tabs: Right-click gives "Insert…", "Delete", "Rename", "Move or Copy" (Create a copy), "Tab Color…". Double-clicking a tab edits the name in place (Enter or a click elsewhere confirms, Esc cancels). The + at the right end of the tabs and "Insert…" ask for the sheet name, code name (automatic if blank), and tab color in one dialog and insert after the displayed sheet. For the project's workbook, this is done with the editor's commands (§14.16) together with the files in
objects/(including the confirmation for deleting a sheet); for other workbooks and the playground, with thesheetandtabColoredits (in the playground, the deleted sheet'sobjects/<code name>.rasis deleted too). - Undo and redo (Ctrl+Z, Ctrl+Y / Ctrl+Shift+Z): The extension keeps the file's contents from before each edit (50 per workbook, up to 200 MB in total) and writes them back. If something else (Excel,
ras pack, sync) changes the file, the history is discarded.
Limitations: The following cannot be done yet: creating icon combinations for conditional formatting, editing data validation, filtering by color, icon, above average, etc., specifying border line styles and colors, custom-list series such as weekdays and month names, clicking cells on other sheets while entering a formula to insert a reference, adding and editing notes, splitting windows (as opposed to freezing), gradients, patterns, line types (dotted, etc.), effects, and text formatting of shape formatting, grouping, inserting charts, ActiveX controls, and SmartArt, changing the name, color, font, etc. of ActiveX controls, and selecting multiple objects. Formulas in a sorted range that the stand-in cannot calculate become values. For a workbook with cells that could not be loaded (some workbooks made by non-Excel software), an edit that overwrites those cells is an error. There is no editing of workbooks open in Excel (a path that operates Excel). Chart series and conditional formatting ranges that reference cut-and-pasted cells are not re-targeted (formulas and defined names are). Cutting and pasting a cell with a formula the stand-in cannot calculate turns it into a value. Because the workbook is re-read for every edit, a large workbook (100,000 cells or more) takes several seconds per edit.
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
- CSV: RFC 4180 (fields in
","", line breaks in a field). The separator is,(a tab when the first line has tabs and no,). The encoding is UTF-8 (with or without a BOM), else Shift_JIS. A field's value is read as Excel reads what is typed into a cell (numbers, dates,TRUE/FALSE, formulas starting with=, else text). - JSON: An array of rows (
[["Code", "Qty"], ["A1", 3]]) or an array of objects (their keys become the header row, in the order they first appear). Strings stay text (not read as numbers);nullis an empty cell.
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" }
] }
]
}
- Paths are relative to the folder of the recipe. An item of
editsis an edit ofras book edit --op(one withop), or the short forms{"sheet", "set": {cell: input}}(input as with--set; a formula when it starts with=) and{"sheet", "clear": [ranges]}. An edit withoutsheetis of the first sheet of the source. - A name
Print_Area/Print_Titlesdefined for a sheet (scope) is, as in Excel, that sheet's print area / print titles (_xlnm.Print_Area), replaced when there is one. When a sheet is removed, the references to it become#REF!whole, as in Excel (Basics!$E$17:$G$31→#REF!), and the formulas are calculated again. --checkcompares the files with what the recipe makes, without making them again (the comparison ofdiff, §14.14), so CI can make sure the inputs of the tests were not changed by hand.
Implementation note (current version): The parts and data that
ras book edit'sactiveX(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 byobject, 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
--message-format json: For any command, prints errors and warnings to standard output as JSON, one per line (the human-readable display is not printed).{"type":"diagnostic","code":"W0304","severity":"warning","message":"In RAS, write `cells` instead of `Cells` (…)", "file":"src/main.ras","range":{"start":{"line":3,"column":8},"end":{"line":3,"column":13}}, "fixes":[{"file":"src/main.ras","range":{"start":{"line":3,"column":8},"end":{"line":3,"column":13}},"newText":"cells"}], "explain":"ras explain W0304"}severityiserror/warning/info/hint. Lines and columns are 1-based, and columns are in UTF-16 code units (counted the same way as in editors).fixesare the edits thatras check --fixmakes, and are present only when there are any.relatedare the places related to the diagnostic (the first declaration of a name declared twice,E0101, and the like), each withfile,rangeandmessage, present only when there are any. The human-readable display shows them as lines= <message>: <file>:<line>:<column>, the language server asrelatedInformation. The results of user form checks (forms/*.form.json) are written in the same shape (fileis the form's file,rangethe place of the property at fault, its start and end the same; withoutrangewhen the place is not known).ras explain <code>: Shows the meaning of that code, typical causes, and how to fix it (with an example for some). If the code is omitted, it prints a list. Every code the compiler emits has an explanation. In the human-readable display, when there are errors, it points toras explain.ras doc <name>: From the bundled type definitions and the project's declarations, shows the signature, the doc comment, the name in VBA and whether the Excel stand-in has it (the same judgement asW0510–W0513below) of a name (Range.find,Excel.Worksheet,msgBox,xlUp,path.join; case-insensitive). It is the same as the quick info of the language server.--listlists the members of a type, enum or module (one per line, marking those the stand-in cannot do),--jsonwrites JSON (name,kind,signature,vba,doc,standIn). A name that does not exist fails, showing similar names. When the head of a name is both a type and a function (range), it is the type when a member follows (Range.findisfindofExcel.Range), otherwise the one written in the same case.ras doc --stand-in: Writes the list of the members of the objects the stand-in models and whether it has each, as Markdown (--json: one JSON object per line, withobject). The reference's "Excel stand-in support" is this output; an automated test checks they match.Quick info: The quick info of a member of an object the stand-in models shows whether the stand-in has it (available, missing, needs Excel, not saved in the workbook, not calculated), whatever the setting of
ras check --target stand-in.ras check --target stand-in(orstand-in = trueunder[lint]inras.toml): Warns, before running, about things that cannot be used in runs that do not use Excel (ras run,ras test, Excel-less debug runs). It is not shown by default, because such code is fine when run as VBA in Excel.Code Description Run-time error W0510Members not in the Excel stand-in's Application/Workbooks/Workbook/Sheets/Worksheet/Range/Names/Name/Sort/Hyperlinks/Hyperlink/OLEObjects/OLEObject/Shapes/Shape/ControlFormat/FileDialog, worksheet functions (WorksheetFunction) the stand-in cannot calculate, and VBA standard functions not in the runtime438 (445 for VBA standard functions) W0511Operations that need Excel itself ( application.runand handwritten VBA intypes/*.d.ras,getOpenFilename/getSaveAsFilename/fileDialog,onTime,Worksheet.copy()/move()without a destination)445 W0512COM objects that cannot be created (a ProgID written as a string literal in createObject("..."), a host class that isnewed; other thanScripting.FileSystemObject,Scripting.Dictionary,VBScript.RegExp,ADODB.Stream)429 W0513Format settings the stand-in does not save in the workbook (those of Font/Interior/Borders/Border/PageSetupother than the saved ones; they can be set, but only give back what was set while the program runs, not what the workbook has)None W0514Argument values the stand-in does not support (a color or icon operatorofautoFilter(xlFilterCellColor/xlFilterFontColor/xlFilterIcon), asortOnofsortFields.add/add2other than values). Only arguments written as numbers or enum members are checked1004 The list of members the stand-in has (
crates/ras-compiler/stdlib/standin.json) is generated from the stand-in's implementation bytools/standin/members.js, and automated tests verify that it matches the implementation. The list of settingsFont/Interior/Border/PageSetupsave in the workbook is generated the same way. Only references to members whose type is known are checked (members ofany/object, members of union-typed values, and members of objects not in the table above are not checked). Of argument values, only those ofW0511/W0514above are checked (what is known only when it runs, such as copying a sheet to another workbook, is not).
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
Specifying a sheet: By code name or tab name (if both match, the sheet with that code name; the same as
--sheetin §14.14). Only worksheets are handled; chart sheets andThisWorkbookare not.Where it writes: As with sync and
ras pack, if the workbook is open in Excel it operates Excel (Windows only), and if closed it rewrites the workbook file directly (§14.9; atomic writing, backup, and verification after writing are the same as §14.9.3).- Changes made to a workbook open in Excel do not reach the file until it is saved in Excel (the command does not save). Meanwhile, the code name check is done on the open workbook (§12.2).
- It is not done while a macro is running, in break mode, or while a cell is being edited (§14.6). It is an error and nothing is changed.
All or nothing: The workbook is changed first, then the files in
objects/. If it fails midway, the workbook is restored (for a workbook open in Excel, the added sheet is deleted or the name restored; deletion is done last, and if it fails nothing is changed).Operations:
Command Workbook objects/and sourceadd <tab name>Adds an empty worksheet. Position by --before <sheet>/--after <sheet>(default is the end). Code name by--code-name(default, as in Excel, is the first freeSheet<number>)Creates <code name>.ras(a comment-only file, the same as in §14.7.2)copy <sheet> [<tab name>]Duplicates the sheet. Position by --before/--after(default is right after the source). The default tab name is<original name> (2), as in Excel, and the code name is--code-name(default is the same asadd)Copies the source file as <new code name>.raswithout changing its contents (the same as the duplication in §14.7.2)remove <sheet>Deletes the sheet Deletes <code name>.rasrename <sheet>Changes the tab name with --nameand/or the code name with--code-name(either or both)When the code name is changed, renames the file and rewrites references to that code name across the whole project ( src/,objects/,forms/,test/) (the same as the editor's rename; §16.2.5)Name checks: The tab name follows Excel's rules (up to 31 characters, does not contain
: \ / ? * [ ], does not start or end with', does not collide case-insensitively with other sheets). The code name is a VBA identifier that does not collide with the names of other sheets, modules, and forms (§12.1.1). A violation is an error and nothing is changed.Confirmation for
remove: In the following cases, it shows the reason and does not delete. With--force, it deletes.- The file has code (a comment-only file does not count).
- The project's source has a reference to that code name (deleting would cause a compile error; the reference locations are shown).
- A formula or defined name in the workbook has a reference to that sheet (deleting would produce
#REF!; the referencing cells and names are shown). - If there is no other visible sheet, Excel refuses the deletion, so even with
--forceit is an error.
rename --name: References to the sheet from the workbook's formulas, defined names, charts, etc. are re-targeted by Excel if the workbook is open in Excel. When rewriting the file directly, ras re-targets formulas and defined names. Places in the source that refer to a sheet by the tab name as a string (worksheets("Revenue")) are not rewritten, and their locations are shown as warnings (there is no effect if the sheet is referenced by code name; §13.4).Limitations when rewriting the file directly:
add: Adds the sheet part,xl/workbook.xml, relationships, and[Content_Types].xml, and for a workbook with a VBA project, the document module (VBA/dir,PROJECT,PROJECTwm; §14.9.2).copy: Duplicates cell values, formulas, formatting, merged cells, column widths and row heights, conditional formatting, data validation, and the sheet's view settings. Sheets with tables, PivotTables, charts, shapes, pictures, controls, or comments cannot be duplicated by rewriting the file (it is an error, directing you to open the workbook in Excel and do it there).remove: Deletes the sheet part and the parts only that sheet uses (shapes, comments, etc.). Formulas and defined names that pointed to that sheet become#REF!, as in Excel. The calculation chain (calcChain.xml) is deleted and Excel is left to rebuild it.rename --name: Re-targets formulas (cells, conditional formatting, data validation), defined names, chart references, hyperlink destinations, and the PivotTable's source sheet.- For a workbook that has sheets with no recorded code name (such as workbooks made by software other than Excel; code names are decided from the order as
Sheet<number>), the code names of all sheets are written to the file first, so that code names do not shift when sheets are added or removed. - Binary-format workbooks (
.xlsb) cannot be handled by rewriting the file (it is an error, directing you to open the workbook in Excel and do it there).
VS Code: The extension exposes the same operations as commands (delegated to the language server's
workspace/executeCommand; §7.4).- "RAS: Add Sheet", "RAS: Duplicate Sheet", "RAS: Delete Sheet", "RAS: Rename Sheet". They can be run from the right-click menu of
objects/and the files in it in the Explorer, the title bar of the sheet file's editor, and the right-click menu of the tabs in the sheet preview (§14.14). - The tab name, code name, and position are asked for in input boxes. For deletion, a confirmation dialog shows the reasons
removerefuses (there is code, there are references), and if accepted, it behaves like--force. - When a file in
objects/is renamed in the Explorer, it asks whether to rename the sheet's code name as well, and if accepted behaves likerename --code-name. When a file is deleted, it asks whether to delete the sheet too (if not, the next sync recreates the file; §14.7.2). - After add and duplicate, the created file is opened. If the workbook file was rewritten, the open sheet preview is refreshed.
- The extension calls the language server command
ras.sheet. The argument is{ action: "add" | "copy" | "remove" | "rename" | "list", sheet, name, codeName, before, after, force }, and the result has the same form as--json(when refused,{ ok: false, refused: [reasons] }; when it could not be done,{ ok: false, message }).
- "RAS: Add Sheet", "RAS: Duplicate Sheet", "RAS: Delete Sheet", "RAS: Rename Sheet". They can be run from the right-click menu of
Operations done in Excel: When a sheet is added or duplicated in Excel, the next sync creates the file (§14.7.2). When a sheet is deleted or its code name changed in Excel, the file with no matching sheet gets
E0610, and the message points to deleting or renaming the file (in VS Code this can be done with a quick fix).--json: Prints the result (the operation performed, the files created, deleted, or renamed, the number of rewritten references, warnings) as a single object.Exit code: 0 on success; 1 when
removerefused to delete and gave reasons (it can be deleted with--force); 2 when it could not be done otherwise (a name check violation, no such sheet, Excel does not accept the operation, a write failure, a compile error, etc.). The same with--json.
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
- Workbook:
--book, elseproject.workbookofras.toml. The workbook itself is not written to. It is copied tobuild/excel/run-<time>/, the project is written into the copy offline (asras packdoes, §14.9; an.xlsxbecomes an.xlsm), and that is opened. When it cannot be written (compile errors, drift, a hand-written module of the same name;--overwriteoverwrites), nothing is run. The state before the run is kept inbefore/, the open workbooks after it inafter/. The 5 newest folders are kept. - Excel: A new instance is started (the Excel the user has open is not used). It is shown minimized unless
--visibleis given (then at its normal size). It is not hidden because a hidden Excel behaves differently:Worksheet.Activatedoes not switch to its workbook, for one.AutomationSecurityis set to low so the macros of the workbook (Workbook_Openincluded) run. Afterwards the workbooks are closed without saving and Excel is quit; if it does not end, its process is ended (--keep-openleaves Excel open with--visible). - Dialogs: During each call the dialog watcher of §14.10.6 runs with the "locate" answer. Each dialog is read, answered as follows, and included in the result.
MsgBoxand the like: the default answer (asdismissof §14.10.6).- A VBA run-time error: Debug is pressed, the module, line and code of the line are read from the VBE's selection (
ActiveCodePane.GetSelection), and the VBA project is reset (the VBE's Reset).Application.Runreturns an error (40040) as soon as Debug is pressed and leaves break mode behind, so the caller reads and resets too. - A compile error (the VBE's message): closed with OK; the location is read and the project reset likewise.
- The error box of RAS (the
MsgBoxof a macro entry witherlon, titled "RAS"; §12.4): closed with OK; the error number, description and.raslocation are read from the message. - Reading the location needs Excel's "Trust access to the VBA project object model". Without it, the result says the location could not be read and goes on.
- Locations: A VBA module and line are turned into a
.rasfile and line withbuild/<module>.rasmap(§14.8; the nearest mapped line above when the line has none). Hand-written VBA modules show the VBA location only. run: CallsApplication.Run "'<book>'!<module>.<function>". A function named like a VBA reserved word (write→write_and the like) is called by its VBA name, looked up in the generated modules. Integers andtrue/falseare passed as such, other arguments as strings. The return value is shown as text (Emptyis not shown). When the run has not ended after--timeout <seconds>(600 by default, 0 for no limit), Excel is ended. After the run, a copy of each open workbook is saved and compared with the file it was opened from (in the form ofdiff, §14.14). A new workbook that was never saved is named only.compile: Runs the VBE's "Compile VBAProject" (control 578, §14.6). The VBE shows a compile error afterExecutehas returned, so it waits until a dialog has come and gone (2 seconds when none comes).compare: To check a port, runs the same function with the same arguments in the workbook of the original macro (--baseline) and in a copy of the workbook with the project written into it, and compares the results.ras excel compare checkReport "C:\data\report.xlsx" --baseline original.xlsm ras excel compare Main.run --baseline original.xlsm --baseline-entry Module1.Run --ignore "Errors!G1" --ignore History- Each runs in an Excel started for it alone, as
rundoes (the dialogs are handled the same way). The macro run in the original workbook is--baseline-entry(the name of the function when omitted). - Both run with the workbook in
build/excel/run-<time>/book/and the arguments that are files copied intofiles/(each run copies them afresh from the originals), so what a macro writes ofThisWorkbook.Pathor of the paths of its inputs is the same on both sides. - What is compared: the outcome of the call (return value, error number, time-out); the dialogs shown (kind, text and answer, in order; not where VBA stopped); the workbooks open after the run (the workbooks run against each other, the others matched by name; the differences "baseline → port" are shown in the form of
diff, §14.14). Cells that--ignore <sheet>/--ignore <sheet>!<range>covers are not compared (dates and the like that change every time). --jsonprintsentry,args,baseline/port(workbook,macro,seconds,timedOut,returned,error,failed,openError,dialogs),workbooks(name,role:main/other,same,diff,note) andsame.- The exit code is 0 when they are the same, 1 when they differ, and 2 when they cannot be compared (a workbook cannot be opened, the project cannot be written, and the like).
- Each runs in an Excel started for it alone, as
--json: Printsworkbook(the copy opened),ok,dialogs(kind:message/input/runtimeError/compileError/rasError/other,title,texts,answer,reset,error(number,description),location(module,line,code,ras(file,line))),entry,args,seconds,returned,error,timedOut,workbooks(name,path,changed,saved,diff) andcompiledas one object.- Exit code: 0 when it ended normally; 1 when it stopped at a run-time or compile error or was ended at the time limit; 2 when it could not run (the project could not be written, Excel could not be started, and the like).
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
- Type definitions for the Excel object model (
Excel.Range,Excel.Worksheet, etc.) and for the Office and VBA standard functions are bundled. - Other COM libraries (ADODB, etc.) are generated from their type libraries with
ras typegen. Code that uses the generated types is emitted with late binding (Object+CreateObject) by default, to avoid depending on references (@earlyBindingswitches to early binding). - Scripting Runtime and VBScript regular expressions: Type definitions for
Scripting(FileSystemObject,File,Folder,Files,Folders,TextStream,Dictionary) andVBScript(RegExp,MatchCollection,Match,SubMatches) are also bundled. Neither library is in the references, so the generated VBA uses late binding (variables areObject; no reference is needed).- Creating: Write
new Scripting.FileSystemObject()/new Scripting.Dictionary()/new VBScript.RegExp(). A regular expression can also be created with a literal such as/abc/i(§2.8). They are emitted to VBA asCreateObject("Scripting.FileSystemObject")and so on. Other types (File,TextStream, etc.) cannot be created withnew. - Type of
createObject: AcreateObjectcall that passes one of these 3 ProgIDs as a string literal, such ascreateObject("Scripting.FileSystemObject"), has that type instead ofobject(case-insensitive). Member completion and type checking work. When the ProgID is passed in a variable, or for any other ProgID, the type isobjectas before. - Enum values:
forReading/forWriting/forAppending(IOMode),tristateTrue/tristateFalse/tristateUseDefault(Tristate), andwindowsFolder/systemFolder/temporaryFolder(SpecialFolderConst) are available. Without the reference, VBA has no such constants, so they are emitted to VBA as numbers (fso.openTextFile(path, forReading)becomesfso.OpenTextFile(path, 1&)). For attributes (attributes) and compare methods (compareMode), use the VBA constants (vbReadOnly,vbTextCompare, etc.). - Collections:
folder.files/folder.subFolders/ the result ofRegExp.execute/ aDictionary(its keys) can be enumerated withfor...ofand the methods in §4.4. - Dictionaries: For a key-value dictionary, normally use
Map<K, V>(§13.3). TheScripting.Dictionarytype exists for existing code that usesCreateObject("Scripting.Dictionary")as is (values areany; set withd[key] = value, read withd(key)/d.item(key)). - Importing hand-written VBA (§14.7.1):
Dim fso As New FileSystemObject,As Dictionary,New RegExp,ForReading, etc. are converted to these types and enum values. - See §14.10.5 for how debug runs handle them.
- Creating: Write
- ADO Stream: Type definitions for
ADODB(Streamand the enumsStreamTypeEnum,SaveOptionsEnum,StreamReadEnum,StreamWriteEnum,LineSeparatorEnum) are also bundled. It is used to read and write text with a specified character encoding (setcharsetto"utf-8","shift_jis", etc.). As withScripting, it uses late binding, and is created withnew ADODB.Stream()/createObject("ADODB.Stream")(which has that type). Enum values (adTypeBinary,adTypeText,adSaveCreateOverWrite,adReadLine, etc.) are emitted as numbers. The RAS standard library'sfs.readText/fs.writeText(§15.4.4) use it, so normally use those instead.
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 |
- Conversion rule: Lowercase the leading run of uppercase letters as one word. If another word follows, its first letter stays uppercase.
Value→value,VBProject→vbProject,RGB→rgb,UBound→uBound,CStr→cStr,FormulaR1C1→formulaR1C1. - Globals that collide with keywords: A global whose converted name would be a RAS keyword keeps its VBA spelling (
Switch(...)). Members are written after a., so they may collide with keywords (range.delete(),ws.select()). - Generated VBA: Emitted with the type library's spelling (
ws.Cells(r, 1).Value). Members of an untyped value (any/object) are also emitted with that spelling when the bundled type definitions have a member of the same name (activeSheet.cells(1, 1)→ActiveSheet.Cells(1, 1)). - When written in the VBA spelling: VBA is case-insensitive, so writing
ws.Cells(r, 1).Valueresolves to the same member. However, it produces a warning (W0304).ras check --fixand the editor's quick fix rewrite it to camelCase. - Names declared by the project stay as they are: Sheet code names (
Sheet1) and names declared intypes/*.d.rasare referenced as written and emitted as is. Only names in the bundled type definitions are converted. - Writing the bundled type definitions: The
.d.rasfiles themselves are written in the type library's spelling (the same form as the output ofras typegen). The element type of a collection is expressed with a type argument (interface Sheets<T>). A host type used without type arguments gets its default type argument if it has one (Excel.SheetsisExcel.Sheets<Excel.Worksheet | Excel.Chart>; §2.6.5), and otherwise its elements areobject. Even for members that the type library declares as returning Object / Variant, when the value's type is known it is written as a union type (§2.6.5).
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 |
- Functions that take a file number:
freeFile(),eof(n),lof(n),loc(n), andfileAttr(n, 1)are used as the VBA standard functions (camelCase per §15.3.1). The value offileAttr(n, 1)is the same as the values ofFileIO.OpenMode(fileAttr(n, 1) == forBinary). - Functions that do not take a file number:
dir,kill,fileCopy,fileLen,fileDateTime,getAttr/setAttr,mkDir,rmDir,chDir,chDrive, andcurDirare called as VBA standard functions (kill(folder + "\\*.tmp"),dir(path, vbDirectory)). - Constant arguments: The mode, access, and lock of
fileOpenbecome keywords of the VBAOpenstatement, so write the constants directly (a variable or expression is errorE0416). TheFileIOenums do not exist in VBA, so when used as values (in comparisons, etc.) they are emitted as numbers. - Values to write:
print/printLineconvert each value to a string by the same rules as${}before writing (unlike VBA'sPrint #, no spaces are added around numbers;trueistrue).write/writeLinepass values through as they are, so the result has the VBAWrite #format (strings as"…", booleans as#TRUE#, dates as#2024-01-31#). Numbers, strings, booleans, and dates (includingany) can be written; an object or array is an error (E0381). - Read targets: The targets of
inputandfileGetare variables, fields, or array elements (the same rules as abyrefargument; a literal or expression isE0406). VBA'sInput #/Getcan read only into variables, so when reading into a field or element, RAS reads into a temporary variable and then assigns.fileGet/filePuthandle variables of number, string, boolean, and date types, and one-dimensional arrays of them (an array is read or written for as many elements as it has). When an expression is passed tofilePut, it is put in a temporary variable of the expression's type before writing (so that the byte count is determined by the RAS type;filePut(f, 1)writes the 4 bytes of aLong). - Debug runs: In debug runs, tests, and the playground, which have no Excel, the runtime (
ras-scripting.js) keeps a table of file numbers and reads and writes in the same formats as VBA on Japanese Windows (text is ANSI (Shift_JIS) with CR LF, theWrite #format, the byte sequences ofGet/Put, and the string length offorRandom(2 bytes)). Errors also use the VBA numbers (52 bad file name or number, 53 file not found, 54 bad file mode, 55 file already open, 59 bad record length, 62 input past end of file, 63 bad record number, 67 too many files, 75 path/file access error).lock/unlockonly check that the file is open and do not lock.Variantand objects withGet/Putare not supported (error 445). - Importing hand-written VBA (§14.7.1): These statements are converted to the functions above (
Open p For Input As #1→fileOpen(1, p, forInput),Line Input #1, s→s = lineInput(1),Input(5, #1)→inputString(1, 5)). The,ofPrint #(next tab position) andSpc/Tabare not converted (left as TODO).
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
like(text: string, pattern: string): boolean: Emitstext Like pattern. The pattern is VBA's:?is any single character,*is zero or more characters,#is a single digit,[abc]/[a-z]is any one of the listed characters (range), and[!abc]is any one character other than those.[*],[?],[#], and[[]are the characters themselves. The generated module hasOption Compare Binary, so it distinguishes case and full-width from half-width (for a case-insensitive comparison, normalize first, as inlike(s.toUpperCase(), "A*")). When the pattern is invalid (an unclosed[, or a reversed range), it is run-time error 93. If the project declares a function namedlike, that one takes precedence.dbNull(any): Emits VBA'sNull. Use it to putNullinto a database field or control value, or to returnNull. Check whether a value isNullwithisNull(v).- RAS's
nullis notNull: put into anany, it becomesEmpty, and for an object type it becomesNothing(§13.2).v == nullandv ?? xtreatEmpty,Nothing, andNullalike as no value (RAS_IsNullish). dbNullis not an object, so an assignment to ananyis emitted asv = Null, without theSetcheck (RAS_Assign). PuttingNullinto a variable of a number, string, or similar type causes run-time error 94 (Invalid use of Null), as in VBA. Converting to a string in a template string or with+gives an empty string (RAS_Str).- Comparing with
==/!=:==/!=ofanyvalues becomes VBA's=/<>. When one side isNull, so is the result: as the very condition of anif/while/for/?:,==and!=are both false (the branch for false is taken); stored in a variable, used with&&/||or returned, it is run-time error 94. ComparingdbNullitself, or a variable the function assignsdbNullto (except one the same function checks withisNull()), with==/!=is a warning (W0314). Check withisNull(v).
- RAS's
- Debug runs (§14.10): The runtime evaluates
likeby the same rules.dbNullis a dedicated value distinct fromEmpty(null):isNull(dbNull)istrue,isEmpty(dbNull)isfalse,typeName(dbNull)is"Null", andvarType(dbNull)is1(vbNull).==/!=behave as in VBA: false as the very condition, run-time error 94 as a value ($rt.eqCond/$rt.eqValue). In a run connected to Excel, it is passed to COM asNull(VT_NULL); the Excel stand-in makes assigning it to a cell an empty cell (as Excel does). ANullreceived from COM is still read asnull(Empty), as before.
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$ |
- Width: Half-width characters are ASCII characters (
U+0000toU+007E) and half-width katakana and punctuation (U+FF61toU+FF9F). A surrogate pair counts as 2. toValue: Decided by applyingIsNumeric/IsDatetoStrConv(s, vbNarrow)(read with the regional settings of Japanese Windows). An empty string stays an empty string.
15.4.2 Arrays
Extension methods (ras_array; usable without an import).
xs.unique(): T[]: A new array with duplicates removed (in order of first appearance; compared with==, asincludesdoes).m.flat(): T[]: Turns a 2-D array into a 1-D array, laid out row by row from the left (range.toArray().flat()).
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.
path.join(...parts): Joins with a single separator between parts (empty parts are skipped;path.join("C:\\data", "2026", "sales.xlsx")).path.basename(p, ext = "")/path.dirname(p)/path.extname(p): The last part (withextremoved if it ends with it), the folder without it ("."if there is no separator;C:\forC:\sales.xlsx), and the extension (from the.;.gitignoregives""). A trailing separator is ignored.path.root(p): The root ("C:\\","\\\\server\\share\\","\\";""for a relative path).path.sep:"\\".
15.4.4 Files and folders (fs)
Used with import * as fs from "fs"; (RAS_Fs; creates one Scripting.FileSystemObject and reuses it).
fs.exists(p)/fs.isFile(p)/fs.isDirectory(p): Whether it exists / is a file / is a folder.fs.list(dir, hidden = false): string[]: The paths of the folders and files directly under it (folders first).fs.walk(dir, pattern = "*", directories = false, files = true, hidden = false): string[]: The paths of the files (and of folders withdirectories) whose names matchpattern, including subfolders.patternis a wildcard (alikepattern; case-insensitive) or a regular expression.- Hidden items: When
hiddenisfalse(the default), hidden and system files (attributes), names that start with., and Office lock files (~$) are excluded, and the inside of hidden folders is not searched. - If the folder does not exist,
list/walkreturn an empty array.
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"
}
fs.readText(p, encoding = "auto"): string: Reads the whole file. A leading BOM is removed, and line breaks stay as in the file. If the file does not exist, error 53.fs.writeText(p, text, encoding = "utf8", append = false): Recreates the file and writes (withappend, appends to the end; no BOM is written when appending). Line breaks stay as intext. Characters that cannot be represented become?.fs.readLines(p, encoding = "auto"): string[]/fs.writeLines(p, lines, encoding = "utf8", newline = "\r\n", append = false): Read and write as an array of lines.readLinessplits at CR LF, LF, or CR, and does not include the empty line after the last line break.writeLinesaddsnewlineafter each line.fs.detectEncoding(p): string:"utf8bom"/"utf16le"/"utf16be"if there is a BOM; otherwise"utf8"if the bytes are valid UTF-8 (including ASCII-only and empty files); otherwise"cp932".fs.encodingName(name): string: Normalizes an encoding name to the canonical name (see the table below). Other names are returned in lowercase.Encoding names (case-insensitive;
_and-are not distinguished; the names are the same as xljs'sencoding):Name Aliases When reading When writing "auto"""Decided by the BOM and by whether the bytes are valid UTF-8; if neither applies, Shift_JIS Same as "utf8""utf8""utf-8"A BOM may or may not be present No BOM "utf8bom""utf-8-bom","utf-8-sig", etc.Same as "utf8"With BOM "cp932""shift_jis","sjis","windows-31j","ms932", etc.Shift_JIS (CP932, including Windows extension characters) Same "eucjp""euc-jp"EUC-JP Same "iso2022jp""iso-2022-jp","jis"JIS (ISO-2022-JP) Same "utf16le""utf-16","unicode"UTF-16 LE (a BOM may or may not be present) With BOM "utf16be""utf-16be","unicodeFFFE"UTF-16 BE (same) With BOM Other names are passed as is to the
charsetofADODB.Stream("big5","iso-8859-1", etc.; names found underMIME\Database\Charsetin the Windows registry).VBA: Emitted to
RAS_ReadTextand others inRAS_Fs. The file is read into a binaryADODB.Stream, the BOM and whether the bytes are valid UTF-8 are checked using aBytearray, and then it is read with a text stream whosecharsetis set. When writing, what was written to a text stream is turned into binary, and it is saved without the BOM that ADO adds (SaveToFileoverwrites; withappend, the new text is added after the file's existing content and then saved).
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);
}
csv.parse(text, delimiter = ",", cast = false, trim = false, skipEmptyLines = true, comment = ""): any[][]: Turns a CSV string into a 2-D array. A value enclosed in quotes (") can contain the delimiter, line breaks, and""(a single quote). Characters between a closing quote and the next delimiter are appended to the value as they are. Line breaks may be CR LF, LF, or CR. In rows with fewer columns than the others, the missing columns are filled with""(nullwithcast).trimremoves whitespace around values,skipEmptyLinesskips empty lines, andcomment(such as"#") skips lines that start with that string. A leading BOM (U+FEFF) is removed. The delimiter is a single character other than a quote or a line break.cast(csv.castValue(s)): An empty value becomesnull;TRUE/FALSE(case-insensitive) become a boolean; a number (including thousands separators such as1,234, and exponents) becomes anint(no decimal point or exponent, up to 9 digits) or adouble; a date (2026/4/1,2026-04-01,2026/4/1 9:30,2026/04/01 09:30:15) becomes adate; anything else stays a string. Digit strings with a leading 0 (007; codes) and digit strings of 16 or more digits stay strings so that their digits do not change. Quoted values are converted too (as when opened in Excel).csv.stringify(rows: T[][], delimiter = ",", newline = "\r\n", quoteAll = false): string: Turns a 2-D array into CSV.newlineis added after each row (an empty array gives""). Values are written withcsv.formatValue(v, delimiter, quoteAll):nullis empty, booleans areTRUE/FALSE, dates are2026/04/01(2026/04/01 09:30:00if there is a time), cell error values are#N/Aand so on, and anything else is the same as${v}. Values that contain the delimiter, a quote, or a line break (all values withquoteAll) are enclosed in quotes, and quotes inside become"".csv.read(p, encoding = "auto", …)/csv.write(p, rows, encoding = "utf8bom", …, append = false): Reads a file andparses it /stringifys and writes it. Encoding names are those in §15.4.4. The default for writing is UTF-8 with BOM (no garbled text when Excel opens the file by double-click); for the same Shift_JIS as Excel's "CSV (Comma delimited)", use"shift_jis".
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
}
json.parse(text): any: Values map as follows: an object →Map<string, any>(Scripting.Dictionary; keeps key order; if the same key appears twice, the later one wins), an array →any[](0-based), a number →int(no decimal point or exponent, up to 9 digits) ordouble, a string (including escapes such as\uXXXX) and a boolean stay as they are, andnull→null(Empty). A syntax error is an error with the line, column, and the character at that position (the same number asthrow new Error(…)). A leading BOM is skipped.- Getting values out: A value is
any, so give it a type withas Map<string, any>/as any[]before use (instanceofcannot narrow toMap, so check for an object withjson.isMap(v)and for an array withisArray(v)).json.get(v, path)returns the value at the position where keys are joined with.and array elements are written as[0]or.0(nullif anything on the way is missing;json.get(v, "items[1].price") ?? 0). A 2-D array (such asrange.toArray()) is addressed with two indexes, row and column (json.get(table, "[1][2]")). An out-of-range index (including one that does not fit in anint) and arrays of 3 or more dimensions givenull. json.stringify(value, indent = 0): string: AMap<K, V>and aScripting.Dictionarybecome an object (keys are converted to strings); arrays (1-D, arrays of arrays, andCollection) become an array; a 2-D array (T[][],range.toArray(), therange.valueof multiple cells, a 2-Dredim) becomes an array of arrays of rows; strings, numbers, and booleans stay as they are; a date becomes"2026-04-01"("2026-04-01T09:30:00"if there is a time; in local time, with no time zone offset); andnull,dbNull,Nothing, and cell error values becomenull. Specifying a number of spaces inindentadds line breaks and indentation. Other objects, such as structs and class instances, are an error (naming the type). Strings escape",\, control characters, andU+2028/U+2029, and Japanese and similar text is written as is.json.read(p, encoding = "auto"): any/json.write(p, value, indent = 2, encoding = "utf8"): Reads a file andparses it /stringifys and writes it (with a line break at the end).- VBA: Reading is recursive descent, and strings are extracted by jumping to the delimiter with
InStr. Writing collects partial strings into an array (doubling it when it runs out) andJoins them at the end (so long JSON does not get slow from repeated&).
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 & 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
}
XmlNode:type("element","text","cdata","comment"); for an element,name(ns:itemif there is a prefix),attributes(Map<string, string>; in the order written),children(a copy of the array of child nodes), andchildCount; for text, CDATA, and comments,value; andisElement.- Attributes:
attr(name, fallback = ""),hasAttr(name),setAttr(name, value)(returns this node),removeAttr(name). - Text:
textis the descendants' text and CDATA joined together (comments are not included; for a node that is not an element,value). Assigning to it replaces the children with that one string.childText(path, fallback = "")iselement(path).text(fallbackif there is no such element). - Searching:
elements(path = "*")is an array of child elements, andelement(path)is the first of them (nullif none).pathcan be joined with/to specify grandchildren and below ("order/item").descendants(name = "*")returns the descendant elements in document order."*"matches any name, and a name without a prefix is also compared with the names with their prefixes removed ("item"also matches<ns:item>; namespace URIs are not examined). - Modifying:
addElement(name, text = "")(returns the added element),addText(text),addCData(text),addComment(text),append(node)(these return this node), andremove(node)(trueif it was removed).
- Attributes:
xml.element(name, text = ""): XmlNode: Creates an element (the root of a new document, or an element toappendlater).xml.parse(text): XmlNode: Parses and returns the root element. The XML declaration,<!DOCTYPE>(including the internal subset), processing instructions, and comments outside the root are skipped. The entity references<>&"'and the character references&#…;/&#x…;are turned back into characters (other entity references, and character references beyond the Unicode range (0x10FFFF), are left as they are). Text nodes that consist only of whitespace (line breaks and indentation) are discarded. Errors such as a mismatched end tag are errors with the line and column.xml.stringify(node, indent = 2, declaration = false, encoding = "utf8"): string: Writes out.indentis the number of indentation spaces (0 means no line breaks). Inside an element that has text or CDATA as children, no indentation is added so that the text does not change (<name>a<b>b</b>c</name>is one line). An element with no children is<a/>.&<>in text, and", line breaks, and tabs in attribute values, are turned into references. Withdeclaration, an XML declaration is added at the start (encodingis the name forencoding:UTF-8,Shift_JIS,EUC-JP,ISO-2022-JP,UTF-16).xml.read(p, encoding = "auto"): XmlNode: Withencoding"auto", the encoding is decided in this order: the BOM, theencodingof the XML declaration (Shift_JIS, etc.), and whether the bytes are valid UTF-8.xml.write(p, node, indent = 2, encoding = "utf8"): Writes with an XML declaration.- VBA:
XmlNodeis a class module (children are held in an array whose capacity doubles, andchildrenreturns a copy of it), and the functions are emitted toRAS_Xml.
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)
- If the label is omitted, it is
"default". The time elapsed sinceconsole.timeis written in the form "label: 12.3ms" to the Immediate window (Debug.Print; the debug console in debug runs).timeEndends that label. For a label that was not started: "Timer 'label' does not exist". - In VBA, the runtime's
RAS_ConsoleTime/RAS_ConsoleTimeLogare used (measured withTimer; resolution of a few milliseconds; it works across midnight).
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) |
- JSDoc type annotations (the
{string}of@param {string} x) are ignored. The type annotations in the code are authoritative for types. - A warning is given when the name in
@paramdoes not match the actual argument name. - The warning for an
exported declaration without a documentation comment is disabled by default (enable it with[lint] require-docs = trueinras.toml).
16.1.3 Output to VBA
- The summary of a function's or class's documentation comment is emitted as a
'comment immediately before the declaration in the generated VBA (characters that the code page cannot represent are converted by the rules in §13.7). - For a
Publicprocedure,Attribute <name>.VB_Description = "<summary>"is emitted so that the description also appears in the VBE's Object Browser. However,AddFromStringin live sync (§14.6) does not acceptAttributelines, so it is not emitted in live sync. It is emitted when going throughImportand in offline writing (§14.9). - Ordinary comments (
//,/* */) are emitted as'comments at positions that the source map can map ([build] keep-commentsinras.toml; defaulttrue).
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
- Order: The type's members are shown first, then extension methods. Extension methods get an icon and an "(extension)" label.
- Candidates that are not imported: The
exported functions and extension methods of modules in the project that are not yet imported are also offered, and committing one adds theimportstatement automatically. any/objecttypes: They have no static type, so no member list is shown (a hint says that this will be late binding).- Enum constants: Constants of COM enums such as
xlUpare shown first at argument positions where the expected type is the enum. - Named arguments: In the argument list of a function, method, constructor, extension method, or Excel / VBA member that has a declaration, when the cursor is at the start of an argument (right after
(or,), the names of the arguments not yet specified are shown at the top of the list in the formname:, and committing insertsname:(§3.3). Arguments passed by position, arguments passed by name, rest parameters, and thethisargument of an extension method are excluded. After a named argument, only argument names are shown. The list is also opened by typing(and,(in that case, only argument names are shown). - Decorators: After
@, the decorators that can be put on the declaration that follows are shown (they differ for functions, functions ofdeclare module, classes, and loops; those that cannot be written in a test file or a form's code-behind are left out). Committing one that takes arguments (such as@on) inserts the parentheses too, as inon(""), puts the cursor inside them, and opens the list again. - Event names: Inside the string of
@on("…"), theTarget.Eventnames the file can receive are shown (in a sheet's file,Worksheetand the controls on the sheet; inThisWorkbook,Workbook; in a form's code-behind,UserFormand the controls; and also the module variables and class fields that hold objects with events; §12.2). Inside the string ofx.on("…")/x.addEventListener("…"), the events of the type ofxare shown (for an array or a collection, those of its elements; §12.2.3). Inside other strings and comments, nothing is shown. The list is also opened by typing@,", and'. - Lazy loading of documentation: At the list stage, only names and types are returned; the JSDoc body is returned by
completionItem/resolve.
16.2.2 Quick info details
- Functions: the signature in RAS syntax, the JSDoc, whether it is
inline, and whether it was selected for automatic inlining. - Variables: the inferred type. The emitted VBA type is also shown (for example,
int→Long). - Extension method calls: the defining module and the call form emitted to VBA (for example,
StrUtil.isBlank(name)). - Generics: the inferred type arguments and the emitted implementation name (for example,
maxOf__Long). - Members of COM types: the type library's help string and a link to Microsoft's reference (
@see). The VBA spelling is also shown (for example,// VBA: Worksheet.Cells).
16.2.3 Type definitions for Excel and others
- The bundled Excel / Office / VBA standard type definitions (
.d.ras, §15.3) carry JSDoc. The JSDoc content is generated byras typegen, which takes in the type library's help strings and member argument names and adds@seelinks to Microsoft's reference pages. The text of the reference itself is not bundled (for licensing reasons). - The same rules apply to type definitions for ADODB and others generated with
ras typegen.
16.2.4 Responsiveness
- So that completion works even on incomplete code while typing, the parser performs error recovery and always builds a syntax tree (lossless CST) (§17.1).
- Analysis is incremental computation (
salsain §17.1) and recomputes only the changed files and their dependents. - Goal: responses to completion, hover, and parameter info within 50 ms in a 100,000-line project (a target value).
- The optimizations (§8 to §10) are not run on IntelliSense's response path. The optimization results for CodeLens are computed in the background and updated when done.
16.2.5 Find references and rename details
- Targets: Functions, methods, accessors, extension methods,
declarefunctions; classes, interfaces, structs, enums, type aliases; fields, struct fields, enum values; module-level variables and constants; local variables and arguments (including lambda arguments). It can be started both from the declaration and from a use site. - What counts as a reference: Names and members in expressions; type names in type annotations,
new,as,implements, etc.;import { name }; argument names of named arguments; keys of struct object literals; and function names in@onError(function)/@fallback(function). A rename also rewrites@param namein the documentation comment of an argument. The shorthand{ x }of an object literal is rewritten to{ y: x }(renaming the field) /{ x: y }(renaming the variable). - Renamed together: A getter and setter; an interface member and the same-named members of the classes that implement it (including further implementations).
- Aliases at import: A rename cannot be started from a use of
binimport { a as b }(renaming from the original declaration givesimport { a2 as b }, and uses ofbstay as they are). - What cannot be renamed: Declarations in type definitions (
.d.ras) and in the RAS standard library (Excel / VBA names); form controls (change them informs/<name>.form.json);declarefunctions without@alias(the DLL's function name); constructors;this; fields of anonymous object types and tuples. - New names that are rejected: A name that is not an identifier; a RAS keyword or basic type name; a VBA reserved word (§13.6); a name starting with
RAS_; a name that differs from another identifier in the project only in case (§13.6, §6 rule 6); a name already declared in the same scope; and a name that after the change would hide another declaration or be hidden by one (a name that the module uses as an Excel / VBA global, the same name as a local variable of a function where it is used, etc.). When rejected, the reason is shown and nothing is rewritten.
16.2.6 Semantic tokens
- The token types are the LSP-standard
namespace/type/class/enum/interface/struct/typeParameter/parameter/variable/property/enumMember/function/method. The modifiers are the standarddeclaration/readonly/static/defaultLibrary(names from the bundled type definitions: Excel / VBA members and globals) /deprecated(declarations with@deprecatedin the JSDoc), plus RAS's ownbyref(an argument passed by reference) /extension(an extension method). - An extension method called with
.getsextensiononmethod. The VS Code extension has default settings that showbyrefunderlined anddeprecatedstruck through.
16.2.7 Candidates that are not imported
- The candidates are names
exported by other modules of the project (excluding form code-behind) that are not yet in the scope of the current module. Extension methods are offered after a., and only those that apply to the receiver's type. - The
importadded on commit goes at the end of the list of names if there is already animport { … }from the same module; otherwise on the line after the lastimport(or at the top of the file if there is noimport), using a path from the project folder (src/util,src/lib/str; §12.1.3). - By the same rules, a quick fix that adds an
importis offered for the errors "name not found" (functions, variables, classes, enums), "type not found", and a member not found as an extension method.
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
- The implementation language is Rust (§7.2).
- Excel for Mac is out of scope (§1).
- Offline writing is supported from the first release (§14.9).
- 2-D arrays that come from a Range are 0-based, and are rebased with zero copy (§9.2.1).
- Numeric types are C#-style (
short/int/long/float/double).numberis removed (§2). - C#-style extension methods are supported (§3.2).
DoEventsis inserted automatically, with thinning, in long-running loops (§10.4).- Access / Word are not supported for the time being (§1).
- Generics are emitted as separate functions and classes for each type argument used in the project (§2.4).
- The basic container for data is a struct that is converted to a
Type. Object literals, tuples, and destructuring are provided as struct syntax, and aMapwhose values are structs is replaced by a class by the compiler (§2.5). - Excel / VBA / Office members and globals are referenced in camelCase, and the generated VBA uses the type library's spelling. The VBA spelling is also accepted, but gives a warning and can be rewritten automatically (§15.3.1).
- Array methods on host collections are expanded into
For Each, and the result is returned as an array (§4.4). - The code-behind of a user form is written in RAS (
forms/<Name>.ras) and compiled into the form's code module. Events are received with@on("<control>.<event>"), andthisrepresents the form.ras form pullconverts the VBA code to RAS (§14.11.2, §14.11.6). - Sync (live sync and
ras pack) converts the workbook's hand-written standard modules, sheet /ThisWorkbookcode, and forms made in the VBE to RAS and imports them, and replaces whatever could be converted completely with RAS-generated code (§14.7.1). The approach of moving to RAS management is implemented before the approach of syncing unmanaged modules two-way invba/(§14.7). - Tests are written in vitest style (
describe/test/expect) intest/*.test.ras, separate from the main code. The annotation (@test) approach is not adopted.describe/testare allowed only at top level and insidedescribe, and their names are string literals so that they can be enumerated without running. The default run target is the Excel stand-in, and for each test the workbook is returned to the state afterbeforeAll(§14.12). - RAS files and VBA modules correspond one to one (§12.1.1). The code of sheets and
ThisWorkbookis written in<code name>.rasandThisWorkbook.rasunderobjects/, which corresponds to "Microsoft Excel Objects" in the VBE, and the whole document module is generated from that file. Events are received with@on("Worksheet.<event>")/@on("Workbook.<event>"), andthisrepresents the sheet (workbook). Anything VBA cannot place in a document module is an error (§12.2). As before, a file can contain multiple classes, and a class module is generated for each class. - Events of ActiveX controls on a sheet are received with
@on("<control name>.<event>")in that sheet's file (§12.2.1). No syntax corresponding toWithEventsis provided; a variable or field that has an@on("<variable name>.<event>")handler is emitted asWithEvents(§12.2.2). - When a RAS-generated module is edited in the VBE, it is compared with the last-written code per procedure, and added procedures are imported into the RAS file. Rewriting or deleting generated code is treated as drift (§14.7.3).
- Adding, duplicating, deleting, and renaming sheets is not done by creating or deleting files in
objects/, but with commands that change the workbook and the files together (ras sheet, the VS Code commands). This is because the heading name and position can be specified, and a sheet is never created by a typo in a file name (§14.16). The code of a sheet duplicated in Excel is not deleted; sync duplicates the source file (§14.7.2).