简体   繁体   English

Office 脚本中 function 上下文的问题

[英]Issues with function context in Office Scripts

I am having an issue calling a function into the main script whilst maintaining the excel context我在维护 excel 上下文的同时将 function 调用到主脚本中时遇到问题

async function main(context: Excel.RequestContext){ findMD(1) }

The function findMD(test) contains various ranges which draw from context.workbook and due to the function being defined outside of main I'm getting a cannot find name 'context' error. function findMD(test)包含从context.workbook中提取的各种范围,并且由于 function 是在main之外定义的,因此我遇到了cannot find name 'context'错误。 To try and solve this I changed function findMD(test){ to async function findMD(context: Excel.RequestContext,test){ .为了尝试解决这个问题,我将function findMD(test){更改为async function findMD(context: Excel.RequestContext,test){ However whilst it has solved the context errors I can still not run the script because the function call findMD(1) is now getting an error message of Expected 2 arguments but got 1但是,虽然它已经解决了上下文错误,但我仍然无法运行脚本,因为 function 调用findMD(1)现在收到错误消息Expected 2 arguments but got 1

Would seriously appreciate any assistance one could offer as this is killing me!非常感谢任何人可以提供的帮助,因为这正在杀死我! Thanks!谢谢!

When you define the findMD() function to take context as an input parameter, you also need to supply that parameter whenever you call it.当您定义 findMD() function 以将上下文作为输入参数时,您还需要在调用它时提供该参数。 Here is an example of a helper function which takes as input the context object, as well as a second parameter, much like what you are attempting to do.这是帮助程序 function 的示例,它将上下文 object 以及第二个参数作为输入,就像您尝试做的那样。

async function helper(context: Excel.RequestContext, test) {
  let workbook = context.workbook; 
  let worksheets = workbook.worksheets;
  let selectedSheet = worksheets.getActiveWorksheet();

  selectedSheet.load("name");
  await context.sync();

  console.log( selectedSheet.name);
  console.log( test);
}

async function main(context: Excel.RequestContext) {
  helper(context,"test parameter");
}

Inside of main(), when I call helper(), I pass in both the context object, as well as the value for the test parameter which I want the function to see.在 main() 内部,当我调用 helper() 时,我传入了上下文 object 以及我希望 function 看到的测试参数的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM