Arithmetic operators.(Microsoft Excel Office Scripts)

04/14/2023

Japanese version.

This section introduces the basic use of arithmetic operators in Office scripts.

Operations

Arithmetic operators are used in formulas to perform basic calculations such as the four arithmetic operations.

OperatorContentsExampleresultPriority
(The smaller the number, the higher the priority)
+addition4+263
-subtraction5-233
/division5/22.52
%remainder of a division5%212
*multiplication4*3122
**power3**291
function main(workbook: ExcelScript.Workbook) {
  let n1 = 4 + 2;
  let n2 = 5 - 2;
  let n3 = 5 / 2;
  let n4 = 5 % 2;
  let n5 = 4 * 3;
  let n6 = 3 ** 2;
  
  workbook.getWorksheet("Test").getRange("B2").setValue(n1);
  workbook.getWorksheet("Test").getRange("B3").setValue(n2);
  workbook.getWorksheet("Test").getRange("B4").setValue(n3);
  workbook.getWorksheet("Test").getRange("B5").setValue(n4);
  workbook.getWorksheet("Test").getRange("B6").setValue(n5);
  workbook.getWorksheet("Test").getRange("B7").setValue(n6);
}

Calculation priority and reordering by ()

Basically, calculations are performed from left to right, However, multiplication and division have priority over addition and subtraction.
This order can be increased by enclosing the order in parentheses ().

function main(workbook: ExcelScript.Workbook) {
  let n1 = (4 + 2) * 10;
  let n2 = 4 + 2 * 10;
  
  workbook.getWorksheet("Test").getRange("B2").setValue(n1);
  workbook.getWorksheet("Test").getRange("B3").setValue(n2);
}

Integer part of division

There is no operator to produce the integer part of the division.

To calculate, the code would be as follows.

Math.floor(numeric/numeric)

Assignment operator

Adding = to the arithmetic operator performs the calculation on the variable on the left-hand side.

variable
+= numeric

Converts non-numeric values to numeric values and calculates

Non-numeric values cannot be calculated with arithmetic operators as is.

Use the Numer function to convert them to numeric values. (Values that cannot be considered numerical are not possible.)

Number(Value to be converted to numeric value)
function main(workbook: ExcelScript.Workbook) {
  let s1: string = "10";
  let n1 = 0;
  
  n1 = Number(s1) + 5;

  workbook.getWorksheet("Test").getRange("A2").setValue(n1);
}

For those who want to learn Office script effectively

The information on this site is now available in an easy-to-read e-book format.

Or Kindle Unlimited (unlimited reading).

You willl discover how to about basic operations.

By the end of this book, you will be equipped with the knowledge you need to use Excel Office Script to streamline your workflow.

Links

Office Scripts Articles