Google-sheets – How to create dynamic text which include values from cells for alert in Google Sheets script

google sheetsgoogle-apps-script

I wrote the script which transfer values from one sheet to another sheet.
I added message of confirmation (alert) which is showing list of values before their transfer:

var response = ui.alert('Confirm', 'Вы уверены что хотите внести следующую продукцию в базу данных склада?' +'\n'+op2[0]+'\n'+op2[1], ui.ButtonSet.YES_NO);

Question: How to correct write script for any dymension of values list [op2], because array op2 can has various size?
Full script you can find bellow:

function dataTransfer1() {
 var cs = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Детали");
  var csVal = cs.getRange(2, 1, cs.getLastRow(), cs.getLastColumn());
  var op = csVal.getValues();
  var csVal2 = cs.getRange(2, 1, cs.getLastRow(), 2);
  var op2 = csVal2.getValues();
  

 var ui = SpreadsheetApp.getUi();
 var response = ui.alert('Confirm', 'Вы уверены что хотите внести следующую продукцию в базу данных склада?' +'\n'+op2[0]+'\n'+op2[1], ui.ButtonSet.YES_NO);

// Process the user's response.
if (response == ui.Button.YES) {
    
  var copyFile = SpreadsheetApp.openById("1dRMdqpvWU01KGgeBgDuF8FzYYr2SNsqAhPpGrWAjzx0")
  .getSheetByName("Приход");
  
  var tar = copyFile.getRange(copyFile.getLastRow()+1, 1, cs.getLastRow(), cs.getLastColumn())
  .setValues(op);
  ui.alert('Детали внесены в базу даных склада');
   csVal.clearContent();
} else {
  
}
 
}

Best Answer

You want to list all the values in Columns A & B; not just the first two rows.

This snippet shows the extra code and/or changes to you own code. There are seven new lines of code, and var response is changed.


var op2 = csVal2.getValues();  // existing line


// create a temporary variable to hold the results 
var op2data = ""; 

// loop through each row of op2 to get all the values
// as "i" increments, it adds the data for that row to the temporary variable. 
for (var i = 0;i<+cs.getLastRow()-1;i++){  
  op2data = op2data+'\n'+op2[i];  
}  
  
var ui = SpreadsheetApp.getUi(); // existing line

// note:  the variable holding all the row values is included in the alert
var response = ui.alert('Confirm', 'Вы уверены что хотите внести следующую продукцию в базу данных склада?' +op2data, ui.ButtonSet.YES_NO);  // changed line