I'm looking for input on a small random string generator project.
I'm trying to create a random string generator that puts three words together, where I can then save strings that I like to another sheet.
I'm using a basic script to assign a RANDBETWEEN formula to 3 specific cells, which works great to generate the strings, but it keeps recalculating with each additional step in the script it seems. I'd like to run one function then if I like the string I would run another function to store the string. However, when I try that it has already recalculated the RANDBETWEEN formulas and it saves something completely different.
I have an example sheet here:
https://docs.google.com/spreadsheets/d/1TWziyjjLQJJApkHCqrLzNGMFU0sf-vNEOOSatuhHURo/edit?usp=sharing
And here is the code I'm using for the "Go" and "Save" buttons, respectively:
function generateString() {
var ss = SpreadsheetApp.openById('1b9rP39sgZDOZqu7AmZhOxX9J8CMukmUw7NPY3Qzuq78');
var sheet = ss.getSheetByName('Randomizer');
var cell = sheet.getRange('D4');
var cell2 = sheet.getRange('E4');
var cell3 = sheet.getRange('F4');
cell.setValue('=INDEX(A:A,RANDBETWEEN(1,counta(A:A)))');
cell2.setValue('=INDEX(A:A,RANDBETWEEN(1,counta(A:A)))');
cell3.setValue('=INDEX(A:A,RANDBETWEEN(1,counta(A:A)))');
var cell4 = sheet.getRange('P4');
cell4.copyTo (sheet.getRange ('P5'), {contentsOnly: true}); //an attempt to paste values to record the random string
}
function saveString() {
var ss = SpreadsheetApp.openById('1b9rP39sgZDOZqu7AmZhOxX9J8CMukmUw7NPY3Qzuq78');
var sheet = ss.getSheetByName('Randomizer'); //replace with source Sheet tab name
var range = sheet.getRange('P4'); //assign the range you want to copy
var data = range.getValues();
var tss = SpreadsheetApp.openById('1b9rP39sgZDOZqu7AmZhOxX9J8CMukmUw7NPY3Qzuq78');
var tsheet = tss.getSheetByName('Saved Strings'); //replace with destination Sheet tab name
tsheet.getRange(tsheet.getLastRow()+1, 1, 1, 1).setValues(data);
}
Please let me know if anyone has some ideas on how to make this work properly. Thanks!
RANDBETWEEN the same as RAND are volatile functions. That means that their results changes every time that spreadsheet is recalculated.
If you need to keep the randomized to result be "freezed" for a while instead of this functions one alternative to consider is the use of a custom function as they are recalculated only when at least one of its arguments changes.
Related
Refresh data retrieved by a custom function in Google Sheet
Related
sure I had this down but just can't get it right. Had a script set up to get data from one sheet and put it into another one, which I have done but it leaves gaps when copying and I can't figure out how to solve it. I'm sure in the code, its where I have put a question mark, is where the problem lies.
I have tried put i, last, last+1, 10, 12 but none of these work, feel like i'm missing something small to get this right. Below is the code a link to view the sheet if needed (the sheet is just for me to learn from, a basic example if you will).
Thanks in advance and also if the code could be better written, please just let me know as still learning this :)
function copyInfo() {
var app = SpreadsheetApp;
var copySheet = app.getActiveSpreadsheet().getSheetByName("Copy");
for (var i = 2; i <12; i++) {
var getInfo = copySheet.getRange(2,2,i,2).getValues();
// get the info from range above - start at row 2 on column 2 (b), get number of rows i , number of columns = 2, b,c
var last = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Paste").getLastRow();
var pasteSheet = app.getActiveSpreadsheet().getSheetByName("Paste");
// Tell it where you want the info to go to
pasteSheet.getRange(last+1,1,?,2).setValues(getInfo);
var clearIt = copySheet.getRange(2,2,i,2).clearContent();
// this clears the copy range aka getInfo
}}
link to sheet
You can copy whole range at once using copyTo, so your function could be rewritten as:
function copyInfo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("Copy");
var pasteSheet = ss.getSheetByName("Paste");
// get source range
var source = copySheet.getRange(2,2,12,2);
// get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,2,12,2);
// copy values to destination range
source.copyTo(destination);
// clear source values
source.clearContent();
}
Sorry for the long subject line, but this site wouldn't accept a more concise statement.
I have a Google Sheet, that has nothing more than my name in Cell A1.
Then I went to Tools / Script Editor, and have a "Code.gs" script that says:
function onEdit(e) {
Logger.log("We're in the function.");
var ss = Spreadsheet.App.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var valueOfCell = sheet.getRange(1,1).getDisplayValue();
Logger.log("Value of Cell is '" + valueOfCell + "'.");
}
When I edit my very simple sheet, and check the log (View / Logs), I get:
[19-02-28 08:58:10:182 CST] We're in the function.
That's it. I've tried every permutation I can think of or suss from three days of web-searching, and I simply can not make the .getValue() (or .getDisplayValue()) work.
What am I doing wrong?
Thanks!
/Kent
"Spreadsheet.App" should be "SpreadsheetApp".
Additional permutations that work:
Logger.log("We're in the function.");
var ss = SpreadsheetApp.getActiveSheet();
var valueOfCell = ss.getRange(1,1).getDisplayValue;
and
Logger.log("We're in the function.");
var valueOfCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(1,2).getDisplayValue();
and
Logger.log("We're in the function.");
var valueOfCell = SpreadsheetApp.getActiveSheet().getRange(1,2).getDisplayValue();
After four days, I think I finally understand some of this. For others as dense as I, I leave this documentation here:
Spreadsheet is the "workbook", the collection of Sheet tabs
Sheet is the individual tab'd sheet in a Spreadsheet "workbook".
Seems like simple enough information, but I couldn't find this documented anywhere.
SpreadsheetApp is the Class, the "parent" of all the Spreadsheets. While probably not technically accurate, for purposes of my thinking, I think of "SpreadsheetApp" as being the "Sheets" application within Google Docs, as opposed to "Docs" or "Slides".
So,
var ThisApp = SpreadsheetApp;
// Sets the variable "ThisApp" to "SpreadsheetApp", which I guess is the name/identification of the spreadsheet app.
var TheActiveWorkBook = SpreadsheetApp.getActive();
// Sets "TheActiveWorkBook" to the identifier for the current collection of sheets (collection of tabs within a spreadsheet).
var TheActiveWorkBook = SpreadsheetApp.getActiveSpreadsheet();
// Identical to above; just a different name for it.
var ActiveWorkBookName = SpreadsheetApp.getActive().getName();
// Sets the variable to the *name* of the workbook/spreadsheet (like, "Fred's Spreadsheet").
var ActiveSheetInWB = SpreadsheetApp.getActiveSpreadsheet();getActiveSheet();
// Sets the variable to the identifier of the active tab in the spreadsheet.
var ActiveSheetInWB = SpreadsheetApp.getActive();getActiveSheet();
// Identical to above.
var ActiveSheetInWB = SpreadsheetApp.getActiveSheet();
// Identical to above. The active sheet is the active sheet, regardless of whether we know the active spreadsheet, so the extra step of including the active spreadsheet, as we did in the previous two examples, is unnecessary. (The system knows that the active spreadsheet is the one that contains the active sheet.)
var ActiveSheetInWB = SpreadsheetApp.getActiveSheet().getName();
// Gets the *name* of the sheet, as it shows on that sheet's tab.
var sheet = SpreadsheetApp.getActiveSheet();
var ActiveSheetInWB = sheet.getName();
// Shortens the long "SpreadsheetApp.getActiveSheet()" to a short reference to save typing in subsequent uses. Otherwise identical to above example.
I think I'm finally getting the hang of this....
I'm trying to create a script to copy data from sheet 1 to sheet 2 and at the same time reorder it. I get my data from a Google form, so data is constantly updating.
Here are two images as examples. N°1 is how I have my data, N°2 is how I want it to be in sheet 2.
The idea is to have the script copying the data every time a new row appears.
Data from Forms.
This is how I would like it to be.
This is my initial code:
function copyrange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Ingreso'); //source sheet
var testrange = sheet.getRange('J:J');
var testvalue = (testrange.getValues());
var csh = ss.getSheetByName('Auxiliar Ingreso'); //destination sheet
var data = [];
var columnasfijas = [];
var cadena = [];
//Condition check in G:G; If true copy the same row to data array
for (i=1; i<testvalue.length;i++) {
data.push.apply(data,sheet.getRange(i+1,1,1,9).getValues());
if ( testvalue[i] == 'Si') {
data = (sheet.getRange(i+1,1,1,9).getValues()).concat (sheet.getRange(i+1,11,1,9).getValues()); // this beaks up into 2 rows Idon't know why
/*cadena = (columnasfijas);
data.push.apply(data, columnasfijas);*/
}
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
//Copy data array to destination sheet
//csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
In this line, I'm also having trouble concatenating different lengths of data. It should be: (i+1,1,1,6). concat.....(i+1,11,1,3)
data = (sheet.getRange(i+1,1,1,9).getValues()).concat (sheet.getRange(i+1,11,1,9).getValues()); // this beaks up into 2 rows Idon't know why
When I run it as it should by I receive an error that the length should be 9 instead of 3.
This can be accomplished more simply using formulas instead of app scripts:
=sort(importrange("spreadsheetURL", "Sheet1!A2:AA10000"),sort_col#,TRUE/FALSE,[sort_col2#],[TRUE/FALSE]...)
Documentation on importrange function: https://support.google.com/docs/answer/3093340
Documentation on sort function: https://support.google.com/docs/answer/3093150
Once you input the formula, there will likely red triangle on the cell, be sure to click on the cell and click the Allow Access button to give one spreadsheet access to the other.
Having trouble with very simple code, I have successfully copied cells and ranges of cells to other sheets, but I cannot get the multiplication of a value to copy, I am sure this is very simple so apologize up front.
The error I get is "TypeError: Cannot find function getcopyTo in objec"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[1];
var nextsheet = ss.getSheets()[4];
var lastColumn = nextsheet.getLastColumn()+1;
var newData = sheet.getRange("D35").getValue()*100;
newData.getcopyTo(nextsheet.getRange(9,lastcolumn), {contentsOnly:true});
var newData = sheet.getRange("D35").getValue()*100;
This returns a number, like 4200. Then you try newData.getcopyTo which can't possibly work, there is no method "getcopyTo" in the number 4200. (Actually, there is no such method in Apps Script, it looks like some mix of getValues and copyTo). What you should do is
nextsheet.getRange(9,lastcolumn).setValue(newData);
The method copyTo is used in the form sourceRange.copyTo(targetRange) but that's direct copying from one range to another, without any manipulation like multiplying by 100.
I'm trying to make a copy of one spreadsheet using a (time driven) Google App Script. I found a very useful piece of code here, but my concern is that the range varies frequently (new rows are added). How can I copy the entire spreadsheet no matter if the range changes?. because as you can see in the code below I have defined the range, but when this changes the information out of the defined range will be discarded. What can I do?
Thanks in advance.
Here the code I'm using:
function saveAsSpreadsheet(){
var timestamp = new Date();
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange('sheetName!A1:AO158');
sheet.setNamedRange('sheetName', range);
var TestRange = sheet.getRangeByName('sheetName').getValues();
Logger.log(TestRange);
var destFolder = DriveApp.getFolderById("folderID");
DriveApp.getFileById(sheet.getId()).makeCopy("FileName:"+ timestamp, destFolder);
}
If you need to get the range object defined by the first cell of column A and the last cell in column A that contains data, use this code:
var range = sheet.getRange(1, 1, sheet.getLastRow(), 1);
The getRange() method has several overloads and can accept numerical values defining the boundaries of the range as well. More on this here https://developers.google.com/apps-script/reference/spreadsheet/sheet#getRange(Integer,Integer)
If you need to copy everything, use getDataRange() method.