Here’s an example of an OfficeScript that loops through the items or cells in a selected range:
function main(worksheet: ExcelScript.Worksheet, rangeAddress: string) { // Get the selected range let selectedRange = worksheet.getRange(rangeAddress); // Get the values in the range let rangeValues = selectedRange.getValues(); // Loop through each row in the range for (let row = 0; row < rangeValues.length; row++) { // Loop through each column in the range for (let col = 0; col < rangeValues[row].length; col++) { let cellValue = rangeValues[row][col]; // Do something with the cell value console.log(`Cell (${row + 1}, ${col + 1}): ${cellValue}`); } } }
To use this OfficeScript, follow these steps:
- Open Excel Online or Excel for the web.
- Open an existing workbook or create a new workbook.
- Select the range of cells you want to loop through.
- Click on the “Automate” tab in the ribbon.
- Click on the “Script Lab” button.
- In the Script Lab pane, create a new script or open an existing one.
- Replace the default code in the script editor with the code provided above.
- In the
main
function call, provide the range address as an argument (e.g., “A1:C5”). - Click the “Run” button to execute the script.
This script retrieves the selected range based on the provided range address. It then retrieves the values in the range using getValues()
. The script then loops through each row and column in the range and performs an action with each cell value. In this example, it logs the cell address and value to the console using console.log()
.
Please note that OfficeScripts are currently only supported in Excel for the web and Excel Online. They are not available in the desktop version of Excel.