Search code examples
google-apps-script

Add a last row variable into a range variable in Google App Script


I'm using the Google App Script I'm trying to add the last Row(N) variable into a range variable(rngForForm) so that the range will be dynamic instead of being hardcoded. The left,sprLeft & setLeft variables are working, I just cannot get the rngForForm variable to accept the N value so I need it to be something like this: var rngForForm = "$B$3:$B(N variable here)";

function usingFunction2() {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheetName = 'sprintuniquename';

  var selectedSheet = activeSpreadsheet.getSheetByName(sheetName);
  var mySheet = selectedSheet;
  var lastRow = mySheet.getLastRow();
  var N = lastRow;

  for (var i = 2; i <= N; i++) {
    var left = 'LEFT($A$3:$A' + N + ',3)';
    var sprLeft = 'LEFT($A$3:$A' + N + ',9)';
    var setLeft = 'LEFT($A$3:$A' + N + ',12)';
    var rngForForm = "$B$3:$B$1000";
  }

  var trimData = mySheet.getRange(rngForForm).setFormula(left);
  var sourceVals = trimData.getValues();```

Solution

  • You can use a template literal:

    var rngForForm = `$B$3:$B$${N}`;
    

    You could also use R1C1 notation:

    var trimData = mySheet.getRange(3, 2, N-2).setFormula(left);
    

    P.S. Your for loop is totally useless; just do this instead:

    // [...]
    var N = lastRow;
    
    var left = 'LEFT($A$3:$A' + N + ',3)';
    var sprLeft = 'LEFT($A$3:$A' + N + ',9)';
    var setLeft = 'LEFT($A$3:$A' + N + ',12)';
    var rngForForm = "$B$3:$B$1000";
    
    var trimData = mySheet.getRange(rngForForm).setFormula(left);
    // [...]
    

    P.S. 2: I'm assuming that you later reassign different values to mySheet and N, while still needing to use the original values of selectedSheet and lastRow. Otherwise, why not just do this:

    // ...
    var mySheet = activeSpreadsheet.getSheetByName(sheetName);
    var N = mySheet.getLastRow();
    // ...