Search code examples
exceloffice365office-scriptsexcel-onlinems-office-script

Excel online Office-Scripts . Copy Range A1:J10 from worksheet2 and paste it on last row of column A of another sheet


I need some help I can do it in Excel VBA but can't find out how in Excel Online. I have the below example 1 work but it is not dynamic I need it to paste under the last row. If you can help please provide an example or edit the code and resend. Thank you.

//Example 1
  function main(workbook: ExcelScript.Workbook) {
    let data_sheet = workbook.getWorksheet("Data")
    let progr_sheet = workbook.getWorksheet("Programming");
// Paste to range A1 on progr_sheet from range A4:L19 on data_sheet
  progr_sheet.getRange('A4').copyFrom(data_sheet.getRange("A4:L19"), ExcelScript.RangeCopyType.all, false, false);
}

//Example 2 [Below doesn't work just and example of what I am trying to do.]
// function main(workbook: ExcelScript.Workbook) {
//   let data_sheet = workbook.getWorksheet("Data")
//   let progr_sheet = workbook.getWorksheet("Programming");
//   let myUsedRange = progr_sheet.getUsedRange();
//   let lastRow = myUsedRange.getRowCount();
//   console.log(lastRow) +1;
//   // Paste to range column A (lastRow) on progr_sheet from range A4:L19 on data_sheet
//   progr_sheet.getRange('A & lastRow').copyFrom(data_sheet.getRange("A4:L19"), ExcelScript.RangeCopyType.all, false, false);
//}

Solution

  • I think you may be working with Office Scripts, not Office JS Add-ins.

    If I'm right then try this ...

    function main(workbook: ExcelScript.Workbook)
    {
      let data_sheet = workbook.getWorksheet("Data")
      let progr_sheet = workbook.getWorksheet("Programming");
    
      // Get the last row in the programming worksheet.
      // We add another 1 because it returns the index which starts from 0 and 
      // I'm not using getRowCount() because if your worksheet doesn't start using
      // from cell A1, your row count may not equal the last actual row.
      let lastRow = progr_sheet.getUsedRange().getLastCell().getRowIndex() + 1;
    
      console.log(lastRow);
    
      // Add 1 to the last row so we start from the next blank.
      lastRow = lastRow + 1
    
      progr_sheet.getRange("A" + lastRow).copyFrom(data_sheet.getRange("A4:L19"));
    }
    

    ... I couldn't pinpoint all of the issues but this line ...

    progr_sheet.getRange('A & lastRow')
    

    ... will not work for you. That will literally come out as the string A & lastRow.