Error message (7027) detected when attempting to clear cells in Excel Office Script due to unreachable code

I'm encountering an issue with a script that is working fine, except for the part where it's supposed to clear the B4:B120 area in the "// Clear the Margin Updates column" section - which is mysteriously greyed out:

function main(workbook: ExcelScript.Workbook): ReportImages {
  // Make sure all tables and charts are updated by recalculating the workbook.
  workbook.getApplication().calculate(ExcelScript.CalculationType.full);

  // Grab data from the "Target Margins - FHM" table. (name of Excel tab, not name of table)
  let sheet1 = workbook.getWorksheet("Sheet1");
  const table = workbook.getWorksheet('Target Margins - FHM').getTables()[0];
  const rows = table.getRange().getTexts();

  // Select only Product Type and Margin Update columns, excluding the Total row.
  const selectColumns = rows.map((row) => {
    return [row[0], row[1]];
  });

  // Remove existing "ChartSheet" worksheet if present, then add a new one.
  workbook.getWorksheet('ChartSheet')?.delete();
  const chartSheet = workbook.addWorksheet('ChartSheet');

  // Add selected data to the new worksheet.
  const targetRange = chartSheet.getRange('A1').getResizedRange(selectColumns.length - 1, selectColumns[0].length - 1);
  targetRange.setValues(selectColumns);

   // Get images of the chart and table, and return them for use in a Power Automate flow.
  const tableImage = table.getRange().getImage();
  return { tableImage };

  // The goal here is to clear the Margin Updates column.
  const targetSheet = workbook.getActiveWorksheet();
  const getRange = targetSheet.getRange("B4:B120");
  getRange.clear(ExcelScript.ClearApplyTo.contents);`

}

// Interface for table and chart images.
interface ReportImages {
  tableImage: string
}

This code copies data from sections of the A and B columns into a table, then sends an email via a Power Automate flow. However, I am stuck on clearing the values in the B column after this process.

Your assistance would be greatly appreciated.

Thank you.

@cybernetic.nomad: When attempting Range ("B4:B120").Clear, I encounter:

unreachable code detected (7027)

and

"cannot find name 'Range' (2304)

Office Script Range Clear Error

Answer №1

When working with JavaScript, it's important to remember that the function will exit as soon as the return keyword is encountered. This can result in your code being marked as unreachable if not structured correctly. To avoid this issue, make sure the return statement occurs at the end of your code block. Here's an example of how you can refactor your code:

// Clearing the "Margin Updates" column.
const targetSheet = workbook.getActiveWorksheet();
const getRange = targetSheet.getRange("B4:B120");
getRange.clear(ExcelScript.ClearApplyTo.contents);

return { tableImage };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to implement lazy loading for child components in React's Next.js?

I am exploring the concept of lazy loading for children components in React Next JS. Below is a snippet from my layout.tsx file in Next JS: import {lazy, Suspense} from "react"; import "./globals.css"; import type { Metadata } from &quo ...

How can I dynamically append content to the DOM when a user clicks?

On my form, I have an input field that allows users to click an add button and a new input field will appear below it, with the option to repeat this process indefinitely. However, I am facing an issue with adding an input field to the DOM upon a click eve ...

Diverse Selection of Font Awesome Icons

In my React project with TypeScript, I have a header component that accepts an Icon name as prop and then renders it. I am trying to figure out the best way to ensure that the icon prop type matches one of the existing FontAwesome Icons. import { FontAwe ...

Setting dynamic values within the constructor of a TypeScript class to the object instance

Can you help me troubleshoot an issue in this simplified class code snippet? I'm attempting to dynamically assign values to this by looping over key values in the constructor, but it's not working as expected. Could this be a syntax problem or is ...

How should JSON files stored on the server side be properly utilized in Next.js?

Currently, I have a collection of JSON files that I expose through an API endpoint on my web application for global access. This allows different parts of the application to retrieve the data by sending a fetch request to itself... However, since this inf ...

Retrieve information from an XML document

I have some XML content that looks like this: <Artificial name="Artifical name"> <Machine> <MachineEnvironment uri="environment" /> </Machine> <Mobile>taken phone, test when r1 100m ...

What is the reason behind Typescript's discomfort with utilizing a basic object as an interface containing exclusively optional properties?

Trying to create a mock for uirouter's StateService has been a bit challenging for me. This is what I have attempted: beforeEach(() => { stateService = jasmine.createSpyObj('StateService', ['go']) as StateService; } ... it(& ...

What is the best method to remove a value from a JSON object in a CSV file?

I received a JSON response like this: xxx: ["fsd,das"] I am looking for a way to remove the value "fsd" from the JSON object. The issue is that the response inside the JSON is not actually an array, but rather a CSV format. How can I go about deleting it ...

How can I redirect a page using an axios interceptor in Next.js?

Is there a way to redirect the page in an axios interceptor when dealing with server-side rendering limitations? Unfortunately, I am unable to access the server side context in the axios interceptor. I have tried using next/router but it only works on the ...

Unable to retrieve data from localStorage in Next.js

Unable to access localStorage in Nextjs. Code works as expected without errors, but the terminal throws: ReferenceError: localStorage is not defined at MainGrid (./app/components/WeightDisplay/MainGrid.tsx:17:96) 8 | // Initialize states for prefe ...

Angular 8 Observable: Managing User Objects

I recently developed a new service and attempted to call an API method (HTTP GET) to retrieve data, but I'm encountering an issue where not all the data objects from the API GET request are being displayed. angular-component.ts public allUsers$: Obs ...

Is there a way to access the value of an IPC message beyond just using console log?

I am developing an app using electron and angular where I need to send locally stored information from my computer. I have successfully managed to send a message from the electron side to the angular side at the right time. However, I am facing issues acce ...

Locate a user within an array in Angular 5 by inputting a specific character into a textarea before initiating the search

I'm currently facing a situation with my textarea component... <textarea [(ngModel)]="message" id="commentBox" placeholder="Add your comment here..."></textarea> Additionally, I have a user list that retrieves data from an external API l ...

Could you lend a hand in figuring out the root cause of why this Express server is constantly serving up error

I am encountering a 404 error while running this test. I can't seem to identify the issue on my own and could really use another set of eyes to help me out. The test involves mocking a request to the Microsoft Graph API in order to remove a member fro ...

Input for uncomplicated changing identifier

I am looking to create types for dynamic keys that will be of type number. I have two similar types defined as follows: type UseCalculatePayments = () => { totalPayments: number; aggregate: number; condition: boolean; }; type UseCalculateCommissio ...

One method of extracting an object from an array using a parameter function is by utilizing the following approach

I am searching for a specific object in an array based on the user-provided ID. var laptops = [{ "name": "Firefox", "age": 30, "id": "ab" }, { "name": "Google", "age": 35, "id": "cd", "date": "00.02.1990" }, { "na ...

Embedding Globalize.js into an Angular component

Hey there! I'm currently working on building an Angular 4 application that needs to support L10n. I've decided to incorporate globalize into my project. Below is a snippet of my App component: import { Component, OnInit } from '@angular/c ...

Transform text into clickable URL references

I have developed a unique component in NextJS that transforms a specified string within a text into a link of my choosing. export const StringToLink = ({ href, initialText, stringToReplace, useAnchorTag = false, }: { initialText: string; string ...

Unable to connect to web3 object using typescript and ethereum

Embarking on a fresh project with Angular 2 and TypeScript, I kicked things off by using the command: ng new myProject Next, I integrated web3 (for Ethereum) into the project through: npm install web3 To ensure proper integration, I included the follow ...

Complete set of keys within a type

In my TypeScript project, I am working with an API (specifically OData API) to retrieve data. This API allows the selection of specific fields to retrieve. For example, api/some/getbyid(42)?$select=x,y,z can be used to get fields x, y, and z, along with s ...