JS API apply cell number formatting

76 Views Asked by At

Within an Office Excel JavaScript Add in, I would like to change the cell format to a specific "number format".

I have written the following code:

function CFNumber() {
    Excel.run(function (ctx) {
        var selectedRange = context.workbook.getSelectedRange();
        selectedRange.format.numberFormat = "#,##0.0";
        return ctx.sync();
    }).genericErrorHandler(error)
}

Although the code is running and I do not get an error, the format is not applied to the cell. Any idea what could be the reason for this?

I already tried various different formats (incl. percentages), however, none of them were applied to the cell.

1

There are 1 best solutions below

0
On

numberFormat is a direct property of the Range object, not the format property, so you should be assigning a value to selectedRange.numberFormat. Also, you don't assign a string to it, you assign an array of arrays. When the range is a single cell, the assignment looks like this:

selectedRange.numberFormat = [["#,##0.0"]];

These two syntax mistakes are the kind that AIs like ChatGPT, Google Bard, or Bing Chat make. AIs are frequently wrong. You must always test what they give you in the Script Lab tool. If you do that with your code, you'll see compiler errors right in the tools code editor.