Trouble with modifying a cell in a TypeScript office script

Hello everyone.

I am in need of a code that can track which cells are active or selected, and then block them once a user is no longer interacting with them. I understand that there may be some issues, especially if the user selects a cell but does not make any changes. Unfortunately, we do not currently have support for an 'onChange' event handler to address this issue. The main problem I am facing is when the user starts editing a cell, the getActiveCell/getSelectedRange method fails and causes the script to stop running, even though it is enclosed within a try block. The code snippet below illustrates the core concept, where it identifies which cell the user is in and detects when they leave that cell. My next step would be to replace the console.log function with setLock to enhance functionality.

function main(workbook: ExcelScript.Workbook)
{
  while(true){
    try{
      let cell = workbook.getSelectedRange().getAddress();
    }
    catch(e){}
    console.log(cell)
    while(workbook.getSelectedRange().getAddress() == cell){}
  }
}

Answer №1

If you're looking to secure a cell after a user has finished editing it and moved on, one approach could be as follows:

function main(workbook: ExcelScript.Workbook) {
  let lastSelectedCell = "";
  let cell = "";
  let errorCaughtBefore = false;
  let worksheet = workbook.getActiveWorksheet();
  if (!worksheet.getProtection().getProtected()) {
    worksheet.getProtection().protect();
  }
  while (true) {
    try {
      cell = workbook.getSelectedRange().getAddress();
      if (errorCaughtBefore && lastSelectedCell) {
        console.log(lastSelectedCell);
        worksheet.getProtection().unprotect();
        worksheet.getRange(lastSelectedCell).getFormat().getProtection().setLocked(true);
        worksheet.getProtection().protect();
        errorCaughtBefore = false;
      }
    }
    catch (e) {
      errorCaughtBefore = true;
      lastSelectedCell = cell;
    }
  }
}

Important note:

  • It's worth noting that without proper event support, this workaround may not be very reliable.
  • Additionally, based on this source, using try/catch within a loop can impact the performance of your script.

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 could be the reason behind the for loop not running within a typescript function?

My confusion lies in the for loop within this function that seems to never run. Each console log is set up to return a specific value, but the looping action doesn't trigger. Can someone provide insight into what might be causing this issue? export fu ...

Defining TypeScript class events by extending EventEmitter

I have a class that extends EventEmitter and is capable of emitting the event hello. How can I properly declare the on method with a specific event name and listener signature? class MyClass extends events.EventEmitter { emitHello(name: string): void ...

Using redux action in the onPaginationChange function instead of setPaginationState in the given example for the TanStack table - is there a way to

Provided this sample Is there a way to utilize by dispatching a redux action rather than using useState - setPaginationState? onPaginationChange: state => dispatch(browseItemModalActions.setPagination(state)) An error is appearing in the console: ...

Visibility of Input-properties in Angular 2

I am encountering an issue where a component parent is calling another component child with an input-property. Although the property is available in the child's template, it does not seem to be accessible within the constructor or OnInit functions. I ...

Issue with implicitly assigning 'any' type to overloaded variadic generic function

We have some code snippets for you to review: export type actions = { abort: () => void; back: () => void; next: () => void; resume: () => void; }; class Sabar { public use<T1>(fn: (arg1: T1, ctx: object, actions: actions) =&g ...

It is not always a guarantee that all promises in typescript will be resolved completely

I have a requirement in my code to update the model data { "customerCode": "CUS15168", "customerName": "Adam Jenie", "customerType": "Cash", "printPackingSlip": "true", "contacts": [ { "firstName": "Hunt", "lastName": "Barlow", ...

Blending ASP.NET Core 2.0 Razor with Angular 4 for a Dynamic Web Experience

I am currently running an application on ASP.NET Core 2.0 with the Razor Engine (.cshtml) and I am interested in integrating Angular 4 to improve data binding from AJAX calls, moving away from traditional jQuery methods. What are the necessary steps I need ...

Warning: Potential spacing issues when dynamically adjusting Material UI Grid using Typescript

When working with Typescript, I encountered an error related to spacing values: TS2322: Type 'number' is not assignable to type 'boolean | 7 | 2 | 10 | 1 | 3 | 4 | 5 | 6 | 8 | "auto" | 9 | 11 | 12'. No lint errors found Version: typesc ...

Using Google Fonts in a Typescript React application with JSS: A step-by-step guide

How can I add Google fonts to my JSS for use in styling? const styles = ({palette, typography}: Theme) => createStyles({ time: { flexBasis: '10%', flexShrink: 0, fontSize: typography.pxToRem(20) }, guestname: ...

The value of type 'X' cannot be assigned to type 'Y' or 'undefined'

In my code, there is a component that requires a prop with an enum value: export enum AType { some = "SOME", word = "WORD", } const MyComponent = (arg: AType) => {} When I try calling this component like so: <MyComponent ar ...

correct usage of getServerSideProps with Typescript in a next.js project using i18n

I'm encountering challenges with integrating next-i18next into a Typescript NextJS project. There are very few recent examples available for reference. I have successfully set up internationalized routing, but I am facing difficulties in configuring i ...

Can you explain the distinction between "parser" and "parserOptions.parser" in an ESLint configuration?

For a considerable amount of time, I have been using the TypeScript and Vue presets provided below. While it has been functional, I realize that I do not fully comprehend each option and therefore seek to gain a better understanding. Firstly, what sets apa ...

Performing a series of Http Get requests in Angular 2 with an array that can

Seeking assistance with an Observable http sequence that involves making two dependent http calls to an api. The first call returns an Array of Urls, and the second call makes get requests for each url in the array and then returns the responses on the str ...

What is the process for passing information to a nested component structure with parent-child-child relationships?

I am facing an issue with three nested components (C1, C2, C3) where C2 is called within C1 and C3 is called within C2. My goal is to pass data from C1 to C3 using property binding. In the template of C1, I successfully bound a variable that I can access ...

Include quotation marks around a string in C# to convert it into JSON format

I am utilizing a service that operates with JSON format. However, the JSON data I am receiving does not include double quotes around keys and values. Here is an example of the data I have: [{name:{buyerfirstname:Randy, buyermiddlename:null, buyerlastnam ...

Error message: The database query function is encountering an issue where the property 'relation.referencedTable' is undefined and cannot be accessed

Currently, I am working with two schemas named products.ts and category.ts. The relationship between these files is defined as one-to-many. In the products.ts file: import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core"; import ...

When renaming a Vuex module, the system mistakenly believes the old module is still present

After attempting to rename my modules, I encountered a perplexing error. Originally, I had a module named "speed" which I decided to change to "team". Despite updating all references accordingly, I am now facing the following error message: Error: Missing ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...

react-query: QueryOptions not functioning as expected when utilizing userQueries()

When passing certain "query options" while using useQueries() to fetch multiple queries simultaneously, these specified "query options" do not get applied during query executions (e.g. refetchOnWindowFocus has a value of true but I want it to be false). F ...

Angular: sending the user input to the component

I'm trying to link the value of an HTML input field to a variable 'numToAdd' in my component, and then increment the 'numToAdd' variable by 1. However, I'm facing difficulties passing the input value to the component variable. ...