I have this script, tell me how to make sure that the first page is not affected? Thank you very much
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menubuttons = [ {name: "Сleaning" , functionName: "CleanAllSheets"},];
ss.addMenu("Сleaning", (menubuttons));
}
function CleanAllSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.getSheets().forEach((sheet) => {CleanSheet(sheet);})
}
function CleanSheet(sheet) {
sheet.getRange('A2:Z100').clearContent();
}
You can use slice to shorten the array of sheets to be deleted:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menubuttons = [ {name: "Сleaning" , functionName: "CleanAllSheets"},];
ss.addMenu("Сleaning", (menubuttons));
}
function CleanAllSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var l = ss.getSheets().length;
ss.getSheets().slice(1,l).forEach((sheet) => {CleanSheet(sheet);})
}
function CleanSheet(sheet) {
sheet.getRange('A2:Z100').clearContent();
}
Include the index in your forEach and skip if zero.
ss.getSheets().forEach((sheet, i) => { if (i != 0) CleanSheet(sheet); })
Related
I have a macro running through a forEach loop that works but always ends on the last sheet in my workbook.
How do I get it to finish on a specified sheet?
I tried a few variations of getSheetbyname
but I don't really know where to put it.
This is the code:
function ResetPage() {
var sheet = SpreadsheetApp.getActive();
var racenumber = sheet.getRange('B2');
var venue = sheet.getRange('E2');
venue.clearContent();
racenumber.activate();
sheet.getCurrentCell().setValue('1');
}
function doForAllTabs() {
var spreadsheet = SpreadsheetApp.getActive();
var allsheets = spreadsheet.getSheets();
allsheets.forEach(function(workbook) {
if(workbook.getSheetName() !== "Venues") {
workbook.activate();
ResetPage();
}
});
}
You don't need to set each sheet active to change the values. The macro recorder does it but it makes the process slower.
This should do the updates without changing your active cell:
function ResetPage(sheet) {
var racenumber = sheet.getRange('B2');
var venue = sheet.getRange('E2');
racenumber.setValue(1);
venue.clearContent();
}
function doForAllTabs() {
var spreadsheet = SpreadsheetApp.getActive();
var allsheets = spreadsheet.getSheets();
allsheets.forEach(function(workbook) {
if(workbook.getSheetName() !== "Venues") {
ResetPage(workbook);
}
});
}
function doForAllTabs() {
SpreadsheetApp.getActive().getSheets().forEach(sh => {
if (sh.getName() != "Venues") {
sh.getRange('B2').setValue(1);
sh.getRange('E2').setValue('');
}
});
}
At first I had the error of my rows being out of bounds? Then I get this error with "TypeError: SpreadsheetApp.getActiveSpreadSheet is not a function" after I tampered a bit.
I'm not sure why my script isn't working. I have one function to just autoresize all my rows and another function to resize my rows a specific amount (this one keeps saying my rows are out of bounds) Both of these functions use to work for my rows, so I'm not sure what changed.
function onOpen() {
SpreadsheetApp.getUi().createMenu('Scripts')
.addItem('Hide columns', 'hideCols')
.addItem('Show Columns', 'show')
.addItem('Auto Resize Rows', 'autoResizeRows')
.addItem('Resize Rows', 'resizeRows')
.addToUi()
}
function hideCols() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var cells = sheet.createTextFinder("Pictures").matchEntireCell(true).findAll();
cells.map(x => sheet.hideColumns(x.getColumn()));
}
function show() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var cells = sheet.createTextFinder("Pictures").matchEntireCell(true).findAll();
cells.map(x => sheet.showColumns(x.getColumn()));
}
function autoResizeRows() {
var ss = SpreadsheetApp.getActiveSpreadSheet();
var dataRange = ss.getDataRange();
var lastRow = dataRange.getLastRow();
ss.autoResizeRows(2, lastRow);
}
function resizeRows() {
var sss = SpreadsheetApp.getActiveSpreadsheet();
var cellss = sss.getSheetByName('Sheet1');
var responseData = cellss.getDataRange().getValues();
cellss.setRowHeights(2,responseData.length, 300);
}
Fixed:
function onOpen() {
SpreadsheetApp.getUi().createMenu('Scripts')
.addItem('Hide columns', 'hideCols')
.addItem('Show Columns', 'show')
.addItem('Auto Resize Rows', 'autoResizeRows')
.addItem('Resize Rows', 'resizeRows')
.addToUi()
}
function hideCols() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var cells = sheet.createTextFinder("Pictures").matchEntireCell(true).findAll();
cells.map(x => sheet.hideColumns(x.getColumn()));
}
function show() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var cells = sheet.createTextFinder("Pictures").matchEntireCell(true).findAll();
cells.map(x => sheet.showColumns(x.getColumn()));
}
function autoResizeRows() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssname = ss.getActiveSheet()
var lastRow = ssname.getDataRange().getLastRow();
ssname.autoResizeRows(2, lastRow-2);
}
function resizeRows() {
var sss = SpreadsheetApp.getActiveSpreadsheet();
var cellss = sss.getSheetByName('Sheet1');
var responseData = cellss.getDataRange().getValues();
cellss.setRowHeights(2,responseData.length-2, 300);
}
Because you've a typo in this function:-
function autoResizeRows() {
var ss = SpreadsheetApp.getActiveSpreadSheet();
var ssname = ss.getActiveSheet()
var lastRow = ssname.getLastRow();
ssname.autoResizeRows(1, lastRow);
}
It's getActiveSpreadsheet not getActiveSpreadSheet that's why your code is breaking, change that S to s.
Reference:-
getActiveSpreadsheet
With this script, I can import one spreadsheet into another spreadsheet in a tab.
function importA() {
var values1 = SpreadsheetApp.openById('xxxurl').
getSheetByName('xxxname').getRange('A1:DE300').getValues();
SpreadsheetApp.getActive().getSheetByName('TAB').
getRange(1,1,values1.length,values1[0].length).setValues(values1)
}
Now, I would like to import 3 spreadsheets one below the other (in the same tab), preserving any increase in the rows of each sheet at the same time.
How could I proceed?
You can try this code and see if it works for you:
function collectAll() {
createNew(); //this can be removed for instances that you would need to run the two functions separately.
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ["TAB1","TAB2","TAB3"];
for( var i=0; i<sheets.length; i++ ) {
if (sheets[i] == "TAB1"){
var sh = ss.getSheetByName('TAB1');
var range1 = sh.getRange(1,1, sh.getLastRow(), sh.getLastColumn()).getValues();
Logger.log(range1);
}
else if (sheets[i] == "TAB2"){
var sh = ss.getSheetByName('TAB2');
var range2 = sh.getRange(1,1, sh.getLastRow(), sh.getLastColumn()).getValues();
Logger.log(range2);
}
else if (sheets[i] = "TAB3"){
var sh = ss.getSheetByName('TAB3');
var range3 = sh.getRange(1,1, sh.getLastRow(), sh.getLastColumn()).getValues();
Logger.log(range3);
}
}
var range = range1.concat(range2,range3);
Logger.log(range);
ss.getSheetByName('TAB').getRange(1,1, range.length, sh.getLastColumn()).setValues(range);
}
function createNew() { //This function creates the Tabs from 3 different sheets using Sheet ID
var sheets = ["ID1","ID2","ID3"]; //Spreadsheet ID goes here
for (i=0; i<sheets.length; i++ ) {
var ssh = SpreadsheetApp.openById(sheets[i]);
var values = ssh.getSheetValues(1,1, ssh.getLastRow(), ssh.getLastColumn());
var create = SpreadsheetApp.getActive().insertSheet('TAB'+(1+i));
create.getRange(1,1, ssh.getLastRow(), ssh.getLastColumn()).setValues(values);
Logger.log(create);
}
}
What this does is that it assigns all of the values of each tab to its own variable range1, range2 and range3 and then it concatenates all values in a single range, then sets the value to the sheet named "TAB".
I've used getSheetByName instead of openByID but you can get the idea.
function test() {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ["Sheet1","Sheet2","Sheet3"];
for( var i=0; i<sheets.length; i++ ) {
importA(sheets[i]);
}
}
catch(err) {
console.log(err);
}
}
function importA(name) {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh1 = ss.getSheetByName("TAB");
sh1.clear() // if you want to erase old data in TAB
var sh2 = ss.getSheetByName(name);
var r1 = sh1.getDataRange();
var r2 = sh2.getDataRange();
// to prevent a blank line at the top
var i = r1.getNumRows() === 1 ? 0 : 1;
sh1.getRange(r1.getNumRows()+i,1,r2.getNumRows(),r2.getNumColumns()).setValues(r2.getValues());
}
catch(err) {
console.log(err);
}
}
Merge all spreadsheets sheets into one sheet
function mergeSpreadsheetsAllIntoOneSheet() {
const ss = SpreadsheetApp.getActive();
['id1', 'id2', 'id3'].forEach((id, i) => {
let sss = SpreadsheetApp.openById(id);
sss.getSheets().forEach(sh => {
let vs = sh.getDataRange().getValues();
let a = [...Array.from(new Array(vs[0].length).keys(), x => (x == 0)?sss.getName():sh.getName())];
vs.unshift(a);
let ash = ss.getSheets()[0];
if (vs && vs.length > 0) {
ash.getRange(ash.getLastRow() + 1, 1, vs.length, vs[0].length).setValues(vs);
}
});
});
}
The error I am receiving:
Exception: The parameters (String,number) don't match the method signature for SpreadsheetApp.Spreadsheet.getRange.
function onOpen() {
var ui = SpreadsheetApp.getUi();
var VALUE = "Hide";
var COLUMN_NUMBER = 11;
ui.createMenu('Hidden Rows')
.addItem('Hide Rows w/Status = Hidden', 'menuItem1')
.addSeparator()
.addItem('Unhide Rows w/Status = Hidden', 'menuItem2')
.addToUi();
}
function menuItem1() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet();
var cell = ss.getActiveCell()
var cellValue = cell.getValue();
for (r=1; r<lastRow; r++) {
ss.getRange(r,11);
if(cellValue == VALUE){
activeSheet.hideRow(cell);
};
}
}
function menuItem2() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.alert('Second menu item!');
}
Try this:
var VALUE = "Hide";//global
function menuItem1() {
var ss = SpreadsheetApp.getActive();
var activeSheet = ss.getActiveSheet();
var cell = ss.getActiveCell()
var cellValue = cell.getValue();
for (let r=1;r<lastRow;r++) {
if(cellValue==VALUE){
activeSheet.hideRow(cell.getRow());//this hides the row of the activeCell() not the row of the iteration index
}
}
}
These two values are not global scope in your script:
var VALUE = "Hide";
var COLUMN_NUMBER = 11;
They cannot get hoisted into global from function scope.
Interestingly enough that very line that caused the error does nothing.
ss.getRange(r,11);
You might have r defined to be a string some where so I declared r to have section scope in the loop. You should probably review const,var and let in a JavaScript reference.
It's not clear to me from your script what you had it mind but perhaps this is it.
function runOne() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getActiveSheet();
const rg=sh.getDataRange();
const vs=rg.getValues();
const cell=ss.getActiveCell()
const cellValue=cell.getValue();
vs.forEach(function(r,i){
if(cellValue==r[10]){
sh.hideRows(i+1);
}
});
}
I'm trying to get a button to fire more than once(I.e. multiple clicks) but it seems to not be working. Any help would be greatly appreciated. Theoretically it should fire multiple times but it only fires once when I check it in the logs
function a
{
...
var addcolumnspanel = app.createHorizontalPanel().setId("addcolumnspanel");
var addbuttonhandler = app.createServerHandler("addcolumn");
var addbutton = app.createButton().setId("btnaddcolumn").setText("Add another column").addClickHandler(addbuttonhandler);
...
return app;
}
function addcolumn()
{
...//Do some stuff
return app;
}
Here is a more precise code example
//set global var
var counter = 1;
var ss = SpreadsheetApp.getActiveSpreadsheet();
//Set up the Menu bar
function onOpen() {
// Logger.clear();
var menuEntries = [ {name: "demo", functionName: "myFunction"}];
ss.addMenu("Demo", menuEntries);
}
function myFunction() {
var myapp = UiApp.createApplication().setHeight(430).setWidth(800);;
var button = myapp.createButton("Clicky");
var myhandler = myapp.createServerHandler("secondfunction");
var myhandler = button.addClickHandler(myhandler)
myapp.add(button);
ss.show(myapp);
}
function secondfunction()
{
counter++;
Logger.log(counter);
}
OK. The problem is with the counter variable. You cannot use global variables that way in Apps Script. See this answer for more information. You can use ScriptProperties or CacheService as an alternative.
var ss = SpreadsheetApp.getActiveSpreadsheet();
//Set up the Menu bar
function onOpen() {
// Logger.clear();
var menuEntries = [ {name: "demo", functionName: "myFunction"}];
ss.addMenu("Demo", menuEntries);
// Store your counter in CacheService as a string.
CacheService.getPrivateCache().put('counter','1',3600);
}
function myFunction() {
var myapp = UiApp.createApplication().setHeight(430).setWidth(800);;
var button = myapp.createButton("Clicky");
var myhandler = myapp.createServerHandler("secondfunction");
var myhandler = button.addClickHandler(myhandler)
myapp.add(button);
ss.show(myapp);
}
function secondfunction()
{
var cache = CacheService.getPrivateCache();
var counter = parseInt(cache.get('counter'));
counter ++;
cache.put('counter', counter.toString());
Logger.log(counter);
}