Office script to create a new date column
I need to reference a date column within an excel file, but create a new date column that is minus one day from the original referenced date column using office scripts in excel.
I have this script going so far:
function main(workbook: ExcelScript.Workbook) {
// Get the active worksheet
const sheet = workbook.getActiveWorksheet();
// Get the range with the original date column (e.g., column A)
const dateRange = sheet.getRange("A1:A" + sheet.getUsedRange().getRowCount());
const dateValues = dateRange.getValues();
// Create a new column for the modified dates (e.g., column B)
const modifiedDateRange = sheet.getRange("D1:D" + sheet.getUsedRange().getRowCount());
// Subtract one day from each date
const modifiedDates = dateValues.map(row => {
const originalDate = row[0];
if (originalDate instanceof Date) {
return [new Date(originalDate.getDate() - 1)]; // Subtract one day
}
return [originalDate]; // Keep non-date values unchanged
});
// Set the modified dates in the new column
modifiedDateRange.setValues(modifiedDates);
// Optionally, add headers for clarity
//sheet.getRange("A1").setValue("Original Date");
//sheet.getRange("B1").setValue("Modified Date");
}
However, I am getting two errors.
One occurs with "originalDate" in the code below:
if (originalDate instanceof Date) {
return [new Date(originalDate.getDate() - 1)]; // Subtract one day
}
And that error is this:
The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.
The second error is pertaining to "modifiedDates":
modifiedDateRange.setValues(modifiedDates);
And the error I get with that is this:
Argument of type '((string | number | boolean)[] | Date[])[]' is not assignable to parameter of type '(string | number | boolean)[][]'. Type '(string | number | boolean)[] | Date[]' is not assignable to type '(string | number | boolean)[]'. Type 'Date[]' is not assignable to type '(string | number | boolean)[]'. Type 'Date' is not assignable to type 'string | number | boolean'. Type 'Date' is not assignable to type 'number'.
Could anyone guide me in overcoming this scenario I am facing.
All the help would be greatly appreciated.
Thank you,
-Cody