Question:
Good night / day everyone. I am dealing with a google app script, and I have a task in front of me:
In the Arkush1 table, in the "C" column, make a button that, when pressed, creates a Template document (I called it newDocTemplate ) (template), where fields with information about the map and the car are automatically taken from Arkush1 Strictly speaking, newDocTemplate is a copy of template, but with filled with some cells taken from the LIST table
I kind of did it, but only for the 1st client. But I need that when I click on the line (with the button) C5, C6, etc. a document was created with the relevant clients. I implemented the button as a menu.
Can anyone help me with this issue.
Here is the code:
var activeSreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // получаем активный документ(все листы) var template = activeSreadsheet.getSheetByName("template"); // выносим в переменную базовцй шаблон заявки var newTable = activeSreadsheet.setActiveSheet(template).copyTo(activeSreadsheet).activate(); // создаем шаблон в новый лист, и кладем в активный документ и сразу его делаем активным var dataSheet = activeSreadsheet.getSheetByName("Аркуш1"); // берем таблицу с данными function addNewTable(rIndx){ var data = { // решил создать объект с данными model: dataSheet.getRange("D" +rIndx).getValue(), cantact: dataSheet.getRange("E" +rIndx).getValue() } newTable.getRange("A9").setValue("Замовник, тел.: "+data.cantact).setFontWeight("bold"); newTable.getRange("A10").setValue("Марка і модель авто: " + data.model).setFontWeight("bold"); } function onOpen(){ var ui = SpreadsheetApp.getUi(); ui.createMenu("myMenu") .addItem("Generate new Tamplate", "addNewTable") .addSeparator() .addItem("ID", "onEdit") .addToUi(); } function onEdit(event){ var sheet = event.source.getActiveSheet(); var sheetName = event.source.getActiveSheet().getSheetName() // Получаем имя листа который активен var actRng = event.source.getActiveRange();//Ячейка в которой произошло изменение var rowIndex = actRng.getRowIndex(); var ss = SpreadsheetApp.getActiveSpreadsheet(); //var _sheet = ss.getSheets()[0];//Лист где нужно изменения отлавливать var activeCELL = dataSheet.getActiveCell(); var activeCELL_index = i.getRowIndex(); addNewTable(activeCELL_index); // Logger.log(rowIndex) }
Answer:
I would do like:
-
would move the global variables at the beginning inside the
addNewTable
function. Copying the template and activating it in the global context "knocks down" the selection of the active cell – it will always be cell A1 of the newest sheet, which, of course, does not have the required values. -
the
onEdit
function is not needed here; As far as I understand, calling from the menu does all the work.
It turns out something like this:
function addNewTable() {
var activeSreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// получаем активный документ(все листы)
var template = activeSreadsheet.getSheetByName("template"); // выносим в переменную базовцй шаблон заявки
var newTable = template.copyTo(activeSreadsheet); // создаем шаблон в новый лист, и кладем в активный документ
var dataSheet = activeSreadsheet.getSheetByName("Аркуш1"); // берем таблицу с данными
var rIndx = dataSheet.getActiveRange().getRow(); //считываем номер активной строки
var data = { // решил создать объект с данными
model: dataSheet.getRange("D" +rIndx).getValue(),
cantact: dataSheet.getRange("E" +rIndx).getValue()
}
newTable.getRange("A9").setValue("Замовник, тел.: "+data.cantact).setFontWeight("bold");
newTable.getRange("A10").setValue("Марка і модель авто: " + data.model).setFontWeight("bold");
newTable.activate(); //активируем скопированный лист
}
function onOpen(){
var ui = SpreadsheetApp.getUi();
ui.createMenu("myMenu")
.addItem("Generate new Tamplate", "addNewTable")
.addToUi();
}
UPD If you still need to simulate pressing a button by changing the value of a cell in a certain column, you can do this:
function onEdit(event){
Logger.log(event);
//если была изменена колонка «С» в нужном листе, вызвать выполнение функции addNewTable
if (event.range.getColumn() === 3 && event.range.getSheet().getName() === 'Аркуш1') {
addNewTable(event.range.getRow());
}
}