web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

Community site session details

Community site session details

Session Id :
Power Platform Community / Forums / Power Automate / My excel script (that ...
Power Automate
Suggested Answer

My excel script (that works - I've tested) doesn't work in Power Automate - WHY?

(2) ShareShare
ReportReport
Posted on by 10

I've built an automation to download an email attachment, save to onedrive, open and clean the file using script, then updating the data in the table into hubspot.

 

I get the attached errors and the flow.

 

I've already checked, the file does save in onedrive.

 

The excel script works on excel online.

 

It's not a timing/connection issues; I've increased the delay to 45seconds and the file is small.

 

What would possibly go wrong here?

 

Asking the humans here because AI couldn't work it out either.

 

Categories:
Screenshot 2025-0...
Screenshot 2025-0...
Screenshot 2025-0...

Your file is currently under scan for potential threats. Please wait while we review it for any viruses or malicious content.

I have the same question (0)
  • ronaldwalcott Profile Picture
    3,847 Super User 2025 Season 2 on at
    The attachments are not showing
  • NA-17040412-0 Profile Picture
    10 on at
    Reattached the attachments, are they showing now?
    Screenshot 2025-0...
    Screenshot 2025-0...
    Screenshot 2025-0...

    Your file is currently under scan for potential threats. Please wait while we review it for any viruses or malicious content.

  • NA-17040412-0 Profile Picture
    10 on at
    Screenshot 2025-0...
    Screenshot 2025-0...
    Screenshot 2025-0...

    Your file is currently under scan for potential threats. Please wait while we review it for any viruses or malicious content.

  • NA-17040412-0 Profile Picture
    10 on at
  • w.p Profile Picture
    8,339 Super User 2025 Season 2 on at
    Can you show us how you configured this script?
  • NA-17040412-0 Profile Picture
    10 on at
    The code for the step:
    {
    "type": "OpenApiConnection",
    "inputs": {
    "parameters": {
    "source": "me",
    "drive": "b!wrWuiDZB8UiTuRAQuKP4Mv1qEpiK9HxHiVklMZJoMbh5WxOX9G9NQZGw0Kppc2_d",
    "file": "@outputs('Get_file_metadata')?['body/Id']",
    "scriptId": "ms-officescript%3A%2F%2Fonedrive_business_itemlink%2F01QILFB7UU3VO6IGARSBBLEU6S3UCDSRCD"
    },
    "host": {
    "apiId": "/providers/Microsoft.PowerApps/apis/shared_excelonlinebusiness",
    "connection": "shared_excelonlinebusiness",
    "operationId": "RunScriptProd"
    }
    },
    "runAfter": {
    "Delay_for_20_seconds": [
    "Succeeded"
    ]
    }
    }

     
    PARAMETERS:

     
  • NA-17040412-0 Profile Picture
    10 on at
    THE SCRIPT:

     
    function main(workbook: ExcelScript.Workbook) {
        let sheet = workbook.getWorksheets()[0];
        // Read headers from row 1 (Explicitly specify columns A:AH - Cell by Cell)
        const headers: string[] = [];
        for (let colIndex = 0; colIndex < 34; colIndex++) { // Loop through columns A to AH (0 to 33 index)
            const cellValue = sheet.getCell(0, colIndex).getValue(); // Get the value of each cell in the first row
            headers.push((cellValue ?? "").toString().trim().toLowerCase()); // Add the lowercase, trimmed header to the array
        }
        console.log("✅ Explicit Headers (A1:AH1 - Cell by Cell):", headers); // Log the extracted headers
        // Function to find the index of a column based on its title (case-insensitive)
        const getColumnIndex = (title: string): number =>
            headers.findIndex((h: string) => h === title.trim().toLowerCase());
        // Function to rename a column
        const renameColumn = (sourceTitle: string, newTitle: string): void => {
            const index: number = getColumnIndex(sourceTitle); // Get the index of the column to rename
            if (index !== -1) { // If the column is found
                sheet.getRangeByIndexes(0, index, 1, 1).setValues([[newTitle]]); // Set the new header value
                headers[index] = newTitle.toLowerCase(); // Update the headers array
            } else { // If the column is not found
                console.log(`⚠️ Column '${sourceTitle}' not found for renaming.`);
            }
        };
        // Function to delete a column by its title
        const deleteColumnByTitle = (title: string): void => {
            const index: number = getColumnIndex(title); // Get the index of the column to delete
            if (index !== -1) { // If the column is found
                sheet.getRangeByIndexes(0, index, sheet.getUsedRange().getRowCount(), 1).delete(ExcelScript.DeleteShiftDirection.left); // Delete the entire column
                headers.splice(index, 1); // Remove the header from the array
            } else { // If the column is not found
                console.log(`⚠️ Column '${title}' not found for deletion.`);
            }
        };
        // Array of column titles to delete
        const columnsToDelete: string[] = [
            "PMS ID", "New Patient", "Telehealth", "SEM Credit", "Not New Credit",
            "Stripe Charge ID", "Payment Date", "Refund Date", "Transaction line type",
            "Amount", "Application Fee", "Net", "Service", "Resource", "Booking Form", "Appointment type", "Payment method",
            "Consent received", "Voucher code", "Marked Attended", "External Payment Id",
            "External Payment Amount", "External Payment Refunded"
        ];
        columnsToDelete.forEach((title: string) => deleteColumnByTitle(title)); // Loop through and delete each specified column
        // Function to duplicate a column and rename the duplicate
        const duplicateAndRenameColumn = (sourceTitle: string, newTitle: string): void => {
            const sourceIndex: number = getColumnIndex(sourceTitle); // Get the index of the column to duplicate
            if (sourceIndex !== -1) { // If the column is found
                const values: (string | number | boolean)[][] = sheet
                    .getRangeByIndexes(0, sourceIndex, sheet.getUsedRange().getRowCount(), 1) // Get all values in the source column
                    .getValues();
                const insertIndex: number = sheet.getUsedRange().getColumnCount(); // Get the index of the next empty column
                sheet.getRangeByIndexes(0, insertIndex, sheet.getUsedRange().getRowCount(), 1).setValues(values); // Insert the values into the new column
                sheet.getRangeByIndexes(0, insertIndex, 1, 1).setValues([[newTitle]]); // Set the header of the new column
                headers.push(newTitle.toLowerCase()); // Add the new header to the array
            } else { // If the column is not found
                console.log(`⚠️ Column '${sourceTitle}' not found for duplication.`);
            }
        };
        // Rename specific columns
        renameColumn("Booking ID", "booking_id");
        renameColumn("Appointment Date", "appointment_date");
        renameColumn("Appointment Time", "appointment_time");
        renameColumn("Location", "he_vision_clinic_booked_at____");
        renameColumn("Patient Name", "full_name_");
        renameColumn("Patient Email", "email");
        renameColumn("Patient Phone", "phone");
        renameColumn("Cancelled", "cancelled");
        renameColumn("Cancelled Time", "cancelled_time");
        // Duplicate and rename specific columns
        duplicateAndRenameColumn("appointment_date", "he_free_assessment_date");
        duplicateAndRenameColumn("appointment_time", "he_free_assessment_time");
        duplicateAndRenameColumn("Cancelled", "he_cancelled");
        duplicateAndRenameColumn("Booking Date", "he_booking_date");
        duplicateAndRenameColumn("Booking Time", "he_booking_time");
        duplicateAndRenameColumn("cancelled_time", "he_cancelled_time");
        // Create a table from the used range (at the end)
        let currentUsedRange = sheet.getUsedRange(); // Get the final used range of the sheet
        let table = sheet.addTable(currentUsedRange.getAddress(), true); // Create a table from the used range with headers
        table.setName("ContentData"); // Name the table "ContentData"
        console.log("✅ Table 'ContentData' created from used range (at the end)."); // Log the table creation
    }
  • Suggested answer
    Michael E. Gernaey Profile Picture
    53,488 Super User 2025 Season 2 on at
     
    My suggestion is that you aren't waiting (delaying) long enough.
     
    set your delay to 10 minutes, then back it down to 3ish minutes (as you test).
     
     Can you please share how does the file get to where you want to run the script?
     
    Is this personal or business and specifically, did you create/mode/edit it then want to run the Script?
     
    You cannot update DataSources this way, (use Graph API instead) just in case you are doin ghtat.
  • w.p Profile Picture
    8,339 Super User 2025 Season 2 on at
     
    Check the run script output; it will show more details.
    For this case, the error was caused by a blank worksheet.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Forum hierarchy changes are complete!

In our never-ending quest to improve we are simplifying the forum hierarchy…

Ajay Kumar Gannamaneni – Community Spotlight

We are honored to recognize Ajay Kumar Gannamaneni as our Community Spotlight for December…

Leaderboard > Power Automate

#1
Michael E. Gernaey Profile Picture

Michael E. Gernaey 519 Super User 2025 Season 2

#2
Tomac Profile Picture

Tomac 296 Moderator

#3
abm abm Profile Picture

abm abm 232 Most Valuable Professional

Last 30 days Overall leaderboard