I'm looking for a Javascript equivalent of the Excel VBA Intersect method. I need to find the active cell table. Basically everything I do with tables is based on which table the user currently has selected. IIRC, there is currently there is no way to do this directly. So what I'm trying to do is basically this:
- Get the selected range (still not perfect, as I really only want the ActiveCell, not the Selection).
- Get the worksheet.
- Loop through all tables on the worksheet.
- Check each table and see if the selected range is in the table range.
I've monkey'd around a bit, and this is what I currently have which doesn't work...
Excel.run(function(ctx) {
var Selection = ctx.workbook.getSelectedRange();
var Tables = ctx.workbook.tables;
var TableNames = ctx.workbook.tables.load("name");
for (var i = 0; i < TableNames.items.length; i++)
{
var Table = ctx.workbook.tables.getItem(TableNames.items[i].name);
Table.getRange().load('address');
var Intersect = Selection.getBoundingRect(Table.getRange().address);
if (Intersect != null) {return ctx.sync().then(function() {
TableNames.items[i].name;
})};
}
return ctx.sync();
}).catch(function(error) {
console.log(error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
This would be a major step forward for the API if it was native. ;)
Thanks, Zack
There are several ways to check whether the current selection intersects with a table. This snippet demonstrates two of them.
Both of the examples below are written with TypeScript 2.1+'s async/await syntax. The second method is made significantly simpler through the use of "await", but both are possible with just regular promise-chaining as well.
ExcelApi 1.4+ approach:
ExcelApi 1.1 approach:
Common errorHandler helper:
TRY IT LIVE: You can try the Excel 1.4+ approach live in literally five clicks in the new Script Lab (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following GIST URL: https://gist.github.com/Zlatkovsky/3ebdf5587cdc56d23b289fb6a5645030. See more info about importing snippets to Script Lab.