Choose particular spreadsheets from the office software

My workbook contains sheets that may have the title "PL -Flat" or simply "FLAT"

I currently have code specifically for the "PL -Flat" sheets, but I want to use an if statement so I can choose between either sheet since the rest of the code is identical for both. Sometimes, both types of sheets are present in the workbook. I am open to various solutions to address this issue.

function main(workbook: ExcelScript.Workbook) {
        // Select the worksheet named "PL -FLAT"
        let flatSheet = workbook.getWorksheet('PL -FLAT');
        flatSheet.activate();

I've attempted to use the ternary operator (?) and write an if statement without success

Answer №1

Based on the documentation provided in this link, utilizing the if statement should resolve the issue. Here is an example of how it can be implemented:

let flatSheet = workbook.getWorksheet('PL -Flat');
  
if (!flatSheet) {
  flatSheet = workbook.getWorksheet('FLAT');
}

if (flatSheet) {
  flatSheet.activate();
}

Alternatively, you can use the getWorksheets method to retrieve a list of all sheets and then select the correct one based on its name.

let allSheets = workBook.getWorksheets();
let flatSheet = allSheets.find(s => s.getName() === 'PL -Flat');
if (!flatSheet) {
  flatSheet = allSheets.find(s => s.getName() === 'Flat');
}

if (flatSheet) {
  flatSheet.activate();
}

Answer №2

To handle the possibility of both sheets not existing, utilizing a try/catch block can offer an effective solution.

function main(workbook: ExcelScript.Workbook) {
  let sheetNames = ['PL -FLAT', 'FLAT'];
  sheetNames.forEach(sheetName => {
    try{
      let flatSheet = workbook.getWorksheet(sheetName);
      flatSheet.activate();
      // your code
    } catch(error) {
      console.log(`Sheet ${sheetName} does not exist.`);
    }
  })
}

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

How to retrieve an object's property within a component

Currently, my goal is to retrieve the email property from the user object {"name":"test", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c7620">[email protected]</a>"} I want to achie ...

Other options besides re-flowing and repainting

After doing some research on various platforms like Stack Overflow, I've come across information stating that re-paints and re-flows can be quite taxing on a browser's resources. I am interested in learning about alternative CSS/JS techniques to ...

Tips for concealing the values within a selected dropdown list using jQuery

Hello, I'm currently working on a jQuery application that involves a dropdown list box and a gridview. The first column of the gridview has checkboxes with a check all button at the top. My goal is to disable corresponding values in the dropdown list ...

Creating a Bottom-Up Menu in React Native: A Step-By-Step Guide

Need help figuring out how to create a menu that pops up from the bottom when a button is clicked. Any advice on where to start? If you have any guidance or insights, they would be highly appreciated. ...

React blank state - State remains undefined after calling setState

I took out the imports because they are not causing any issues When I render, I set my state and it logs correctly in the console. However, when I try to map it, it comes back as null and gives me an error stating that there are no elements in the "allInf ...

Attempted to identify whether an item exists in an array, and if it does, then add the item to the array; if not, then perform

Allow me to make some clarifications as it might be a bit confusing initially. This project I'm working on is for school. I don't expect anyone to do it for me, but I need help with a specific part. I'm creating a simple shopping cart using ...

Sending data in chunks using Vue.js

I'm interested in sending the data in chunks. Currently, what I send to the server looks like this: for loop - 1, 2, 3. However, the server receives it asynchronously as 3, 1, 2 and I need it to be received synchronously in the order of my for loop: 1 ...

Is it possible for me to include the id attribute in an HTML element that has been generated using React

While working with Selenium to create end-to-end tests for a React-based web application, I noticed that very few HTML elements have the id property set. Since our development team is preoccupied with other tasks, I've taken it upon myself to address ...

How to toggle element visibility when hovering in Angular?

I've set up an angular material card that includes a close button (marked with an "x"). My goal is to initially hide the "x" button and only display it when hovering over the card. Here is the code snippet for the card: <mat-card> <mat- ...

Angular route fails to load the HTML file

In the process of developing a route within an Angular application, I have successfully implemented 3 routes. However, one particular route is giving me trouble. I have three folders that need to redirect HTML based on the option chosen. In Angular, I cre ...

Relaying event arguments from client-side JavaScript to server-side code-behind through ClientScript.GetPostBackEventReference

My goal is to initiate a postback using JavaScript and also pass event arguments. While I have managed to trigger the postback successfully, I am facing issues with passing event args. The function below is not functioning as expected. It seems to be enco ...

Changing SVG containing image tags into HTML canvas

I'm attempting to convert an SVG file to an HTML canvas, and everything works perfectly until I introduce the image element in the SVG. When I include image elements, the canvg function stops working. Below is the code I used to convert the SVG to ca ...

Combining GET and POST requests in ExpressJS on a single route

As I work on setting up a questionnaire in Express JS with EJS as the renderer, I have already created individual pages for each question. These pages are accessible through static links using the app.get('/question/:number?', routes.questions) f ...

Angular: Error when TypeScript object returns an array object value

I have encountered a strange issue where the array value returned as [object Set] when I console log it. It's unclear whether this problem is occurring in the component or the service, but the object values are not being displayed. This issue arises ...

Guide on adding pictures to an ExpressJS server

Working on this project has been quite a challenge for me as I delve deeper into web development. As a relatively new developer, creating a one-page application with image upload functionality has proven to be quite the task, especially considering this is ...

Retrieve the element located within a "block" element that is relative to the user's click event, without the

I'm pondering whether it's feasible, but here's my concept: Within my page, there are multiple identical blocks with the same classes, differing only in content. I am unable or unwilling to assign IDs because these blocks are dynamically g ...

Jest does not recognize AnimationEvent as a defined element

I am currently facing an issue while attempting to simulate an animationEvent for a test within my Angular application. The error message I receive is: ReferenceError: AnimationEvent is not defined. Given that this feature is experimental, it seems like ...

What is the best way to implement function chaining in TypeScript?

I'm interested in implementing function chaining in typescript. Let's consider a sample class: export class NumberOperator { private num; constructor(initialNum) { this.num = initialNum; } public add(inc = 1) { this.num += inc ...

Using Generic Types in TypeScript Files for React Components

I have encountered an issue that I haven't been able to find a solution for online. When I define a function in a ts file like this: const lastGeneric = <T>(arr: Array<T>): T => { return arr[arr.length - 1]; } But when I try to do ...

Comparison between SSD and HDD animation speed in web hosting environments

I am currently in search of a web hosting provider for a website I have created. The site features some performance-heavy animations, particularly due to a fullscreen slider with filter and scaling transitions. I need a provider that can ensure optimal per ...