Dynamically Copy data from one sheet using OfficeScripts

Here’s an example of an OfficeScript that copies data from one sheet and pastes it into a new row in another sheet, dynamically finding the new row using the last used range:

 
function main(workbook: ExcelScript.Workbook, sourceSheetName: string, targetSheetName: string) {
  // Get the source and target sheets
  let sourceSheet = workbook.getWorksheet(sourceSheetName);
  let targetSheet = workbook.getWorksheet(targetSheetName);

  // Get the used range of the source sheet
  let sourceRange = sourceSheet.getUsedRange();

  // Find the last used row in the target sheet
  let targetLastRow = targetSheet.getRange("A:A").getSpecialCells(ExcelScript.SpecialCellType.LastCell).getRow();

  // Compute the new row for pasting
  let newPasteRow = targetLastRow + 1;

  // Copy the values from the source range
  let valuesToCopy = sourceRange.getValues();

  // Paste the values into the new row in the target sheet
  let targetRange = targetSheet.getRangeByIndexes(newPasteRow, 1, valuesToCopy.length, valuesToCopy[0].length);
  targetRange.setValues(valuesToCopy);
}

To use this OfficeScript, follow these steps:

  1. Open Excel Online or Excel for the web.
  2. Open an existing workbook that contains the source and target sheets.
  3. Note down the names of the source sheet and the target sheet.
  4. Click on the “Automate” tab in the ribbon.
  5. Click on the “Script Lab” button.
  6. In the Script Lab pane, create a new script or open an existing one.
  7. Replace the default code in the script editor with the code provided above.
  8. In the main function call, provide the names of the source sheet and target sheet as arguments.
  9. Click the “Run” button to execute the script.

This script copies the data from the used range of the source sheet. Then, it finds the last used row in the target sheet by searching for the last cell in column A. The new row for pasting is computed as the last used row + 1. Finally, the values are pasted into the new row in the target sheet using the setValues function.

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.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech