I'm pretty new to this, so I'm not even sure if this is the most efficient way to do this, but I'm trying to save some space in my Google Apps Script by using a cell value to define a Range List.
Here's the code that I have right now:
function myFunction()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var aItems = s.getRange('F1').getValue();
var aItemList = s.getRangeList([aItems.getValue]);
Logger.log(aItemList);
}
The variable aItems is getting the the value of cell F1 on my sheet, which is 'E2', 'E5' (I also tried removing the single quotes surrounding the cell numbers, but that didn't change the result)
With aItemList I am attempting to create a Range List using the value of aItems to define the range. I get an exception error when I run the script stating that the range is not found.
Ultimately the purpose of the aItemList variable will be to have a variable that is storing a list of cells containing checkboxes that I can alternate between being True and False. On the actual sheet that I plan on using this for, there will be hundreds of checkboxes, so I want to avoid having to list them all out in the script as part of the array. I mention this because I have tried variations of this code that have successfully logged aItemList as the correct string, but do not allow me to set the cells value to true or false using aItemList as a reference.
If someone could let me know if this is even possible or not, I would greatly appreciate it. And/or if there is an even better method of accomplishing this task of storing specific cells into a variable as an array that would also be highly appreciated.
Try this:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var aItems = s.getRange('F1').getValue().split(',');
Logger.log(aItems);
let rgl = ss.getRangeList(aItems);
Logger.log(rgl.getRanges().map(r => r.getA1Notation()));
}
Related
I'm trying to insert values into cells. Here is my code:
var values = [
["test1", "test2", "test3"]
];
var ss = SpreadsheetApp.getActiveSpreadsheet()
// var sheet = ss.getSheets()[0]
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var cellsToWriteTo = []
function testFunction() {
var activeCell = sheet.getActiveCell();
var firstRow = activeCell.getRow()
var firstColumn = activeCell.getColumn()
cellsToWriteTo = `["R${firstRow}C${firstColumn}:R${firstRow}C${firstColumn + 2}"]`
console.log(cellsToWriteTo)
var range = sheet.getRange(cellsToWriteTo)
range.setValues(values);
}
This gives me the error:
Exception: Range not found
However if I copy and paste cellsToWriteTo from the console log and put it into getRange.. it works perfectly every time..
Things i have tried so far:
Thought it was to do with not fetching the spreadsheet correctly (getActiveSpreadsheet().getActiveSheet()).
Fixed how my values were organised (into arrays within arrays)
Googled the error message and looked at how to properly getRange/setRange in the documentation and in tutorials. Apparently you cannot set arbitrary cells if you are calling them from the excel sheet itself. This is my suspicion as to what is going wrong here. However how can this be the case if when I put in a simple string it functions fine. I am simply doing string interpolation here.
I know this is rudimentary stuff, any help would be appreciated.
Removing both brackets and quotation marks should make it work
Modification:
cellsToWriteTo = `R${firstRow}C${firstColumn}:R${firstRow}C${firstColumn + 2}`
Execution:
Output:
This is definitely a pretty basic question, but I can't seem to find a solution by myself, nor the answer in the depths of the internet.
Java script skill: Newbie
I am getting Google Forms Item Id's so that I could then edit/delete etc. even after somebody edits outside of my script.
To get them Ids I am using a 'for loop', which comfortably gets them for me in a string. Unfortunately I don't know how to save that result in a variable - always getting a syntax error.
I am also not happy with saving the logger.log in my google sheet.
Any ideas?
This is my code:
function GetItems3(){
var formId = "your-id";
var Form = FormApp.openById(formId);
var ajtems = Form.getItems();
for(var i=0;i<items.length;i++)
{ajtems[i].getId().toString()
Logger.log(ajtems[i].getId().toString())
};
//That saves the logger log in my sheet (DMsheet is a global var)
var A = DMsheet.getRange(15, 6, ajtems.length, 1).setValue(A);}
Thanks in advanc3
There are several things wrong from your code.
1) There is no need to use the .toString() method because getId() already returns the id as a String.
2) You didn't define your ajtems var.
3) You can't declare a var like A and use it at the same line you are declaring it because it hasn't been set yet.
4) You didn't declare DMsheet, this variable should contain your sheet and you would get it using the Class Sheet.
5) You said in your post "Java skill: Newbie". Java and JavaScript are not the same.
This code will help you to solve your issue:
function GetItems3(){
var formId = "your-id";
var Form = FormApp.openById(formId);
var items = Form.getItems();
// Get a sheet from the Spreadsheet you are running your script
var dmSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
// Create an empty array to save the Form's items
var myArray = [];
for(var i=0;i<items.length;i++){
Logger.log(items[i].getId());
// Sotre the title items in the array
myArray.push(items[i].getTitle());
};
// Set the values in your sheet
dmSheet.getRange(1, 1, 1, items.length).setValues([myArray]);
}
I really recommend you to take your time to read the Apps Script docs. It will help you a lot to improve your coding and clear your doubts on how to use Apps Script in the best way possible.
I am working on a project where I take multiple column/row inventory sheets and turn them into a multi-row/2-column format for order picking.
I have a switch for selecting the appropriate inventory sheet and a map() function that copies the imported information from the inventory DataRange().
However, not all the data is in consistent columns. What I would like to do is find an expression that maps the next column in if the column it was mapping has a zero or "" value.
I won't give you the full body of code unless you need it, but hopefully just the important parts.
This is what I have:
var source = SpreadsheetApp.openById("1xixIOWw2yGd1aX_2HeguZnt8G_UfiFOfG-W6Fk8OSTs"); //This sheet
var srcSht = SpreadsheetApp.getActive();
var sourceMenu = srcSht.getRange('A1');//This is the cell cotaining the dropdown
var menuTest = sourceMenu.getValue();
// Variable for the vars sheet. If it doesn't exist, create it
var varsTest = source.getSheetByName('vars');
if (!varsTest){source.insertSheet('vars');}
var importedA1 = varsTest.getDataRange().getA1Notation();
varsTest.clearContents();
var t1Imp = '=ImportRange("test1_Id", "Stock!A1:F11")';
var varsData = varsTest.getRange('A1');// This is the cell we fill with the importRange formula
varsData.setValue(t1Imp);
var imported = varsTest.getDataRange().getValues();
var newOrder = imported.map(function(item) {
if (item[4] !== NaN){return [[item[0]],[item[4]]];};
if (item[4] === NaN){return [[item[0]],[item[3]]];};}
var orderRange = source.getSheetByName('Sheet1').getRange(10,1,newOrder.length, newOrder[0].length);
orderRange.setValues(newOrder);
Logger.log("\t" + newOrder);
Logger.log(newOrder):
[(timestamp omitted)] items1,order,caramel,6,c&c,2,mint,3,PB,0,,,items2,,caramel,,strawberry,,mint,,PB,
It seems to be skipping the if statements, or I told it that I mean to test the index as NaN, which will obviously never be true.
I also tried replacing 'NaN' with 'undefined'. Same result. I tried finding the item[4].Values, but it gave me an error. I also tried the same logic using filter() instead of map() but it copied the entire data set.
I pull these values onto a new 'vars' sheet in the workbook (to minimize calls to the web service):
test1
reduce them to the first and last columns, then output:
test
The cells in the 'order' column for the second set of items in the 'test' sheet are blank. The values for that order column should be in item[3] of that array, but I can't get the script to identify that that the blank cells are blank.
I am new to Google Apps Script and JS, but I am watching a lot of tuts and learning by doing. If I find a solution, I will post it.
Thank you StackOverflow, I could not have learned as much as I have without this community!
I have a working function that does what I want. In short:
I had to create a duplicate of the order column in a new column, so that all the values would line up. It's not technically a JS answer, but was the simplest and follows good spreadsheet rules.
function rmZeroOrderPS(item){
var source = SpreadsheetApp.openById("<sheetId>"); //This sheet
var varsTest = source.getSheetByName('vars');
var imported = varsTest.getDataRange().getValues();
var i=-1;
while (i <= imported.length){
if(item[8]!= 0) {return [item[0],item[8]]};
i+=1;
};
After around two to three hours of digging across many sites, I cobbled together this functioning script to watch an "input" column on a sheet and, using onEdit(), whenever data is put into that column, move the data further down the sheet to the next available cell in that specific row.
function onEdit(e) {
var s = e.source.getActiveSheet();
var sheetName = 'Pricing Chart';
var colToWatch = 5;
var copyFrom = 5;
var nextEmptyCol = colToWatch + 22;
var emptyCellCheck = s.getRange(e.range.rowStart, nextEmptyCol,1,1);
if (s.getName() !== sheetName || e.range.columnStart !== colToWatch) return;
while (emptyCellCheck.isBlank() !== true){
nextEmptyCol++;
var emptyCellCheck = s.getRange(e.range.rowStart, nextEmptyCol,1,1);
}
if (emptyCellCheck.isBlank()){
s.getRange(e.range.rowStart, copyFrom,1,1)
.copyTo(s.getRange(e.range.rowStart, nextEmptyCol,1,1), {contentsOnly: true}),
s.getRange(e.range.rowStart, copyFrom,1,1).clear({contentsOnly: true});
}
}
Specific example:
Into cell E5, type "222". If AA5 is empty, it will copy "222" into AA5, and then clear E5. If AA5 is not empty, it will check AB5, then AC5, etc until it finds an empty cell. On my specific sheet, it then uses all the data from the row and displays various calculations (average, max, etc) so that those data are visible, but all the individual inputs are tucked away behind the scenes. It's been useful for keeping a large list of data on many different variables in a format that's easy to look at and easy to share with others.
Problem is... sometimes it will do as intended at first, find the next available cell, copy the data, and erase the original input cell (e.g. E5). But, sometimes, it will also erase the cell the data was copied TO (e.g. AB5). Roughly once or twice every ten iterations of the script.
So, I was wondering if anyone could have a look at my script and give me tips on optimizing it or just doing things better so the script runs correctly consistently.
I am using Google Apps for Sheets. I am trying to use a defined variable within a string. I know the variable (lastRow) is the number I want (that number being "11") as I can see it in the logs. I have tried different ways of combining the letter "C" with the variable, but nothing works! I know it works as it is used in the "copyValuesToRange" method. Am I trying to do something that cannot be done, or is there a way to add the variable to the A1 notation so that the range will be read as C1:C11? Thanks from a relatively novice newbie!
var lastRow = sheet.getLastRow();
Logger.log(sheet.getLastRow());
// Inserts 1 column after column A=1 (Seq)
sheet.insertColumnsAfter(1,1);
// New column(s) due to added column(s)
var range = sheet.getRange("C1:ClastRow");
//Copied to Col A=1
range.copyValuesToRange(sheet,1,1,1,lastRow);
While writing this, the "Similar Question" box showed a link to "Google script string with a variable". I looked at that, but did not understand it "(!
You dont do it like that, you need to know concatenation.
var lastRow = 11;
console.log("C"+lastRow);
will output:
C11
which is what you're going for.
var range = sheet.getRange("C1:C"+lastRow);