我遇到了 OfficeScript 的问题(我认为)。
我写了这个脚本:
async function main(context: Excel.RequestContext) {
var RowCt = 0;
var sheetName = "";
let workbook = context.workbook;
let worksheets = workbook.worksheets;
let MyNames = workbook.names;
MyNames.load("name, formula, visible");
let selectedSheet = worksheets.getItemOrNullObject("Names list");
await context.sync();
if (selectedSheet.isNullObject) {
selectedSheet = workbook.worksheets.add("Names list");
}
await context.sync();
//This seems to work but omits names scoped to the worksheet
for (let i = 0; i < MyNames.items.length; i++) {
RowCt++
selectedSheet.getCell(RowCt, 0).getResizedRange(0, 3).values = [
["Workbook", MyNames.items[i].name, "'" + MyNames.items[i].formula, "'" + MyNames.items[i].visible]
];
}
worksheets = workbook.worksheets;
worksheets.load("items/name");
await context.sync();
//This appears to work, but wrongfully includes ALL names scoped to the workbook:
for (let i in worksheets.items) {
sheetName = worksheets.items[i].name;
await context.sync();
//If I omit this sheetName test, it loops through all worksheets (expected) and lists all
//workbook-level names as many times as there are worksheets (unexpected)
if (sheetName == "Sheet1") {
var myNames = worksheets.items[i].names;
await context.sync();
myNames.load("name, formula, visible");
await context.sync();
//console.log(myNames.items[0].name);
for (let j in myNames.items) {
RowCt++;
selectedSheet.getCell(RowCt, 0).getResizedRange(0, 3).values = [
[sheetName, myNames.items[j].name, "'" + myNames.items[j].formula, "'" + myNames.items[j].visible]
];
}
}
}
}
如果我对同时具有工作簿级别范围名称和工作表级别范围名称的工作簿运行此操作,我会两次获得所有工作簿级别范围名称。一次用于全局列表(首先循环遍历名称),一次用于“本地定义”名称(在所有工作表选项卡中查找循环,其中我只通过 Sheet1 的名称工作)。列出全局定义名称的循环省略了范围为工作表“Sheet1”的名称,但如果我枚举 Sheet1 的名称集合,我会得到本地定义的名称,并且我也会得到所有全局名称。这是错误的。