
Issue with async methods inside Custom Functions
Hello,
We are developing an Office add-in for Excel. In the add-in we write custom functions in cells and send API requests to fetch data from another system and write them to the cells. We would like to develop a logging feature where the custom function calls, cell addresses, and configurations are logged to a new sheet. While logging, we need to figure out the next free cell that we can write to. To my knowledge this is done the following way:
let sheets = await context.workbook.worksheets;
await context.sync();
let sheet;
let sheetCreated;
if (await isLoggingSheet() == false) {
sheet = sheets.add("Log");
sheetCreated = true;
} else {
sheet = sheets.getItem("Log");
sheetCreated = false;
}
await sheet.load("name, position");
let dataRange = await sheet.getUsedRange(false);
await dataRange.load()
await context.sync();
const dataRangeLength = await dataRange.values.length
let nextFreeCellIndex = 1;
if (sheetCreated) {
nextFreeCellIndex = 1;
} else {
if (dataRangeLength === 1 && dataRange.values[0][0] === '') {
nextFreeCellIndex = 1;
} else {
nextFreeCellIndex = dataRangeLength + 1;
}
}
let writeRange = await sheet.getRange(`A${nextFreeCellIndex}:A${nextFreeCellIndex}`)
const logData = [[`${getDateTime()} | ${data} |`]]
writeRange.values = logData
await context.sync()
So we need to fetch the sheet and its values. If the sheet is empty, for some reason the returned data is [[""]], an empty string inside a matrix. For this reason we need to do the horrific if else part. This method should be run async. However, the Excel calls the custom functions from the cells synchronously. Due to this reason, it would not matter even if our custom functions are async and await the logging method. Currently the logging results in the logs overwriting each other randomly and not writing correctly to the next free cell.
Is there another way to handle this or could it be possible to call the cells async?
Microsoft 365 and Office | Development | Other
