Here’s an example of an OfficeScripts function to check if a named range exists in the workbook, with the range name passed as a parameter to the function:
function checkRangeExists(rangeName) { // Get the active workbook var workbook = context.workbook; // Get the named items collection var namedItems = workbook.names; // Check if the named range with the given name exists var namedRange = namedItems.getItemOrNullObject(rangeName); context.load(namedRange); // Execute the request and check if the named range exists return context.sync() .then(function () { return namedRange.isNullObject ? false : true; }); }
In this example, the checkRangeExists
function takes a parameter rangeName
, which represents the name of the range you want to check for existence. The function retrieves the active workbook using the context.workbook
object and the named items collection using workbook.names
. It then loads the named range object with the provided rangeName
using namedItems.getItemOrNullObject(rangeName)
. Finally, it executes the request using context.sync()
and checks if the named range exists by verifying if the namedRange
is a nullObject
.
To use this function, you can call it with the desired range name as an argument. For example:
checkRangeExists("MyRange") .then(function (rangeExists) { console.log("Range exists: " + rangeExists); }) .catch(function (error) { console.log("Error occurred: " + error); });
This will check if a named range with the name “MyRange” exists in the workbook and log the result to the console.
Please note that the provided example assumes you are working within an OfficeScript context and have access to the context
object. If you are using OfficeScripts in Excel, you can interact with the workbook, named ranges, and other related objects using the context.workbook
and related objects.
Keep in mind that OfficeScripts are only supported in Excel for the web and Excel Online, and they may have limitations compared to other programming environments.