Office script to create a new date column

Cody Talley 0 Reputation points
2025-01-30T17:16:10.2966667+00:00

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

JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
1,042 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.