2

I just created this tiny Office script:

async function main(context: Excel.RequestContext) {
  context.workbook.names.getItem("Newname").delete;
}

The range name 'Newname' exists in the current workbook, the code runs without error but the name is not deleted. Why? I would expect to receive a runtime error if I'm not allowed to delete range names.

jkpieterse
  • 2,727
  • 1
  • 9
  • 18

2 Answers2

3

I think it missed the bracket:

  context.workbook.names.getItem("Newname").delete();

I just tried by this gist, you could have a try. https://gist.github.com/lumine2008/f55a6265a93b421112de210b22e9a48a

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
Raymond Lu
  • 2,178
  • 1
  • 6
  • 19
3

delete is a method. In JavaScript, a method requires opening and closing parentheses, even if there are no parameters to be passed:

context.workbook.names.getItem("Newname").delete();

My tests confirm this. Also, the code should include await.context.sync();

It's important to realize that JavaScript supports assigning a method to a variable (object), similar to assigning a function to an Excel Name, by leaving off the parentheses. This object can then be used at some point to execute the method. This is why no errors are thrown when the parentheses are omitted.

Example:

const deleteNewName = context.workbook.names.getItem("Newname").delete; 
deleteNewName();

(Thanks to Lumpenstein for this information about JS kindly provided in a comment.)

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43