Define the cell type as value using an office script in an excel report

Coming from macro, I got confused about the use of the cell value for a script at the beginning. In macro, it is quite simple as you know, for instance, I have this value in B1:

script excel

And with the VBA, I want to sum it with another value like that:


Sub test()
Dim mainvalue
mainvalue = Range("B1")
Range("B3") = mainvalue + 9
End Sub             
              

The result is:

script excel

If I do the same logic for the script:


function main(workbook: ExcelScript.Workbook) {
  let mainvalue = workbook.getActiveWorksheet().getRange("B1").getValue();
  workbook.getActiveWorksheet().getRange("B4").setValue(5 + mainvalue);
}              
              

It will work but in the code, I will get a red highlight as an error:

script excel script excel

To avoid it, I have to define the cell type. In Office script, when I am using a cell value, it's important to tell the script what value I am expecting to get from a cell or range. A cell contains one of the following types:

  • string: a sequence of one or more characters that may consist of letters, numbers, or symbols
  • number: a numerical value
  • Or boolean: a result that can be defined as TRUE or FALSE

In order for my script to treat the returned values as one of those types, I must declare the type. For my example, it will be like that:


function main(workbook: ExcelScript.Workbook) {
  let mainvalue = workbook.getActiveWorksheet().getRange("B1").getValue() as number;
  workbook.getActiveWorksheet().getRange("B4").setValue(5 + mainvalue);
}              
              

NOTE: I added “as number” at the end of “mainvalue”

Don’t mix up with “as String”, “as Number” or “as Boolean” with a capital letter which are treated as an “interface” versus “as string”, “as number” or “as boolean” without a capital letter which are treated as a “value”.

An interface allows to define the expected structure of an object providing a way to describe the shape of objects, including their properties and methods, without implementing any functionality.

To resume, based on what I want to do and for my script to work correctly, I don’t have to forget to define the cell as string, number or boolean.

Interesting Topics