Hi could someone help me with this script im trying to insert a formula in all the blank cell from (J15) to (J38) here is what ive got but I just cant seem to get it the proper way any help would be greatly appreciated.
function test() {
var ssA = SpreadsheetApp.getActive(); //changed from openById() for my convenience
var ss = ssA.getActiveSheet(); //change from getSheetByName() for my convenience
var range = ss.getRange(15,10,24,1); //row 2 column 7 (G) lastRow 1 column
var data = range.getValues(); //Gets all data
for(var i=0;i<data.length;i++) //this runs over entire selected range
{
if(!data[i][0]) //If true then it's blank
{
data[i](('=Iferror(If(G15="",, if($B$5 = Iferror(query(\'Client
List\'!$A$2:$A, "select A where A =\'"&$B$5&"\'"),""),VLOOKUP($B$5,Client_Rate,2,False),VLOOKUP(D15,Config_Rate_List
,2,False))),"")');)
}
}
range.setFormula(data); //Sets all data.
}
You want to put the formula to "J15:J38". If my understanding is correct, how about this modification?
I thought that it is possible that the cells of "J15:J38" have the values and formulas. So in this modified script, the formula is put to the empty cells which don't have both. The flow of script is as follows.
Retrieve values and formulas from "J15:J38".
Create range list.
Put the formula using setFormula().
I think that there are several solutions for your situation. So please think of this as one of them.
Modified script :
function test() {
var ssA = SpreadsheetApp.getActive(); //changed from openById() for my convenience
var ss = ssA.getActiveSheet(); //change from getSheetByName() for my convenience
var range = ss.getRange(15,10,24,1); //row 2 column 7 (G) lastRow 1 column
var data = range.getValues(); //Gets all data
// The following script was modified.
var formulas = range.getFormulas();
var rangeList = [];
var offset = 15;
for(var i=0;i<data.length;i++) {
if(!data[i][0] && !formulas[i][0]) {
rangeList.push("J" + (offset + i));
}
}
var formula = '=Iferror(If(G15="",, if($B$5 = Iferror(query(\'Client List\'!$A$2:$A, "select A where A =\'"&$B$5&"\'"),""),VLOOKUP($B$5,Client_Rate,2,False),VLOOKUP(D15,Config_Rate_List,2,False))),"")';
ss.getRangeList(rangeList).setFormula(formula);
}
Note :
I was not sure whether the sheet name is Client List or ClientList, because of the line break in your script.
I'm not sure about the formula which was put to cells.
About your title, "black" of "Google Script insert formula in 1 column where cell are black" is "blank"?
Reference :
getRangeList(a1Notations)
If this was not what you want, I'm sorry.
Edit :
Unfortunately, the formulas in an array cannot be put the cells using the range list yet. I think that Sheets API can put various formulas once. But as a simple way, here, I would like to propose the following script.
function test() {
var ssA = SpreadsheetApp.getActive(); //changed from openById() for my convenience
var ss = ssA.getActiveSheet(); //change from getSheetByName() for my convenience
var range = ss.getRange(15,10,24,1); //row 2 column 7 (G) lastRow 1 column
var data = range.getValues(); //Gets all data
// The following script was modified.
var formulas = range.getFormulas();
var val = [];
var offset = 15;
for(var i=0;i<data.length;i++) {
if(!data[i][0] && !formulas[i][0]) {
ss.getRange("J" + (offset + i)).setFormula('=Iferror(If(G' + (offset + i) + '="",, if($B$5 = Iferror(query(\'Client List\'!$A$2:$A, "select A where A =\'"&$B$5&"\'"),""),VLOOKUP($B$5,Client_Rate,2,False),VLOOKUP(D' + (offset + i) + ',Config_Rate_List,2,False))),"")');
}
}
}
Related
I need to pull/import data from "sheet 1" to "sheet 2" based on column 4 being a specific text string. The script should not pull lines that already exist.
I have no idea if this is possible. I can pull the data but it just recopies everything so I have duplicates.
Any help would be super appreciated.
function onEdit() {
var ss = SpreadsheetApp.openById('1Ognzsi6C0DU_ZyDLuct58f5U16sshhBpBoQ8Snk8bhc');
var sheet = ss.getSheetByName('Sheet 1');
var testrange = sheet.getRange('D:D');
var testvalue = (testrange.getValues());
var sss = SpreadsheetApp.getActive();
var csh = sss.getSheetByName('Sheet 1');
var data = [];
var j =[];
for (i=0; i<testvalue.length;i++) {
if ( testvalue[i] == 'Dan') {
data.push.apply(data,sheet.getRange(i+1,1,1,11).getValues());
j.push(i);
}
}
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
Sheet 1
Sheet 2
Solution
You should be able to replace your code with this and it will work. You would put this script in the target sheet (Sheet 2), and replace the ID in the first line of the function with the origin (Sheet 1).
I'll leave it up to you to change to an onEdit or to make it a menu item. Right now it can be run from the script editor. onEdit doesn't make sense to me as an appropriate trigger. Maybe you prefer a Time-Driven Trigger. Though a custom menu would be the best way IMO.
function pullData() {
var sourceSs = SpreadsheetApp.openById('[YOUR_SPREADSHEET_ID]');
var sourceRange = sourceSs.getSheetByName('Sheet1').getDataRange();
var sourceHeight = sourceRange.getHeight();
var sourceWidth = sourceRange.getWidth();
var sourceData = sourceSs.getSheetByName('Sheet1').getRange(2, 1, sourceHeight - 1, sourceWidth).getValues();
var targetSs = SpreadsheetApp.getActive();
var targetRange = targetSs.getSheetByName('Sheet1').getDataRange();
var targetHeight = targetRange.getHeight();
var targetWidth = targetRange.getWidth();
var sourceDataChecker = [];
var targetDataChecker = [];
sourceData.forEach((row) => {
sourceDataChecker.push(row[0] + row[1] + row[2] + row[3]);
})
if (targetHeight != 1) {
var targetData = sourceSs.getSheetByName('Sheet1').getRange(2, 1, targetHeight - 1, targetWidth).getValues();
targetData.forEach((row) => {
targetDataChecker.push(row[0] + row[1] + row[2] + row[3]);
});
};
sourceData.forEach((row, i) => {
if (!(targetDataChecker.includes(sourceDataChecker[i]))) {
targetSs.appendRow(row);
};
});
}
Explanation
This script builds an "index" of each row in both sheets by concatenating all the values in the row. I did this because I noticed that sometimes you have "joe" in two rows, and so, you can't simply use column 4 as your index. You are basically checking for any row that is different from one in the target sheet (Sheet 2).
If the target sheet is blank, then all rows are copied.
References
Append Row to end of sheet
Get Data Range (range of sheet that contains data)
Get Range Height (to deal with headers)
Get Range Width
for Each
I have two sheets with unique IDs in one column. I need to make sure whenever a new ID is added in one sheet (Sheet1), it is copied to the last empty row in the other sheet (Sheet2). The IMPORTRANGE won't work as being dynamic any static information added in the other sheet would be irrelevant to the respective ID.
In another thread [1], I got help developing this script that will do exactly that. However, this script will insert the data in the other sheet in Column A. How can I modify the script so I can decide the specific range where I want the script to insert the data (in Sheet 2).
Update: I created this spreadsheet as an example. I'm trying to ensure that the script does the calculation (ie. adding vlaues that are not duplicated in the first available empty row), starting in cel C10 in "Sheet2". It would be also great if I can somehow change that range if I need to: https://docs.google.com/spreadsheets/d/1abESAXFrOHoqRQRNqQGfmAFxlbD10wlprAf1tca4y7o/edit#gid=132361488
Thanks!
function updateSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = "Sheet1";
var destinationSheet = "Sheet2";
var source_sheet = ss.getSheetByName(sourceSheet);
var target_sheet = ss.getSheetByName(destinationSheet);
var lastCol = target_sheet.getLastColumn();
var lastRow = target_sheet.getLastRow();
if (lastRow > 1) { // <--- Added
var r = target_sheet.getRange(2,1, lastRow - 1, lastCol);
r.sort([{column: 1, ascending: true}]);
}
_updateSpreadsheet(source_sheet, target_sheet);
}
function _updateSpreadsheet(source_sheet, target_sheet) {
var last_row = target_sheet.getLastRow();
var source_data = source_sheet.getRange("A4:A" + source_sheet.getLastRow()).getValues(); // <--- Modified
var target_data = target_sheet.getDataRange().getValues();
var resultArray = [];
for (var n = 0 ; n < source_data.length ; n++) { // <--- Modified
var keep = true;
for(var p in target_data) {
if (source_data[n][0] == target_data[p][0]) {
keep = false; break;
}
}
var columnsToKeep = [0];
var tempData = [];
if(keep){
for(var c in columnsToKeep){ tempData.push(source_data[n][columnsToKeep[c]])}
resultArray.push(tempData);
}
}
last_row++;
resultArray = resultArray.filter(String); // <--- Added
if(resultArray.length>0){
target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
}
[1] Google Script: Append new values in column to another sheet
target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length)
.setValues(resultArray);
This line
Takes the sheet stored in the variable target_sheet
Accesses the defined range
Sets values
The syntax to access a range used in your code is getRange(row, column, numRows, numColumns)
whereby the start column is numerical - in your case it's 1 which corresponds to column A.
If you want to modify the start column from A to B:
Just change your range definition from
getRange(last_row,1,resultArray.length,resultArray[0].length)
to
getRange(last_row,2,resultArray.length,resultArray[0].length)
I have the following problem with this function. It only deletes blank rows below but I want to delete the rows above.
function removeEmptyRows(){
var sh = SpreadsheetApp.getActive();
var sh1=sh.getSheetByName('name');
var range=sh1.getRange('A:A');
var maxRows = sh1.getMaxRows();
var lastRow = sh1.getLastRow();
sh1.deleteRows(lastRow+1, maxRows-lastRow);
}
I tried with the following function
function removeemptyrows(){
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName('name');
var range=sh1.getRange('A:A');
var values = range.getValues();
for( var i = values.length-1; i >=0; i-- ) {
for( var j = 0; j < values[i].length; j++ )
if( values[i][j] === "" )
sh1.deleteRow(i+1)
}
}
but it deletes rows too slowly - one by one.
You want to delete the rows that the cell of column "A" is empty in the range from 10 row to bottom of sheet.
You want to achieve this using Google Apps Script.
You want to reduce the process cost.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification point:
In this case, I would like to propose to use Sheets API. When Sheets API is used, the rows can be deleted by one API call, even when the rows are discreted.
Sample script:
When you use this script, please enable Sheets API at Advanced Google services.
function removeemptyrows() {
var sheetName = "name"; // Please set the sheet name.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
var sheetId = sheet.getSheetId();
var values = sheet.getRange('A10:A').getValues();
var requests = values.reduce(function(ar, [e], i) {
if (!e) ar.push({deleteDimension:{range:{sheetId:sheetId,dimension:"ROWS",startIndex:(i + 9),endIndex:(i + 10)}}});
return ar;
}, []).reverse();
if (requests.length > 0) Sheets.Spreadsheets.batchUpdate({requests: requests}, ss.getId());
}
In this case, the sample script is almost the same with the below script of https://stackoverflow.com/a/60613983/7108653 . As 2 modification parts, in your case, you want to delete the rows of empty cell at the column "A". So 'C6:C' + sheet.getLastRow() and if (e) were modified to 'A10:A' and if (!e), respectively.
References:
Method: spreadsheets.batchUpdate
Advanced Google services
If I misunderstood your question and this was not the direction you want, I apologize.
I stuck with this. Seems easy at first then I got lost!
What I am aiming for:
to insert a row(s) based on a cell value (Col C) -- insert row(s) below
after a new row(s) is inserted, copy the data from previous row + string value from previous row, removing that value as well from the previous row.
I am trying to use this formula but I got lost...
function addRows(){
var ss = SpreadsheetApp.getActive();
var sheet1 = ss.getSheets()[1];
var dataRange = sheet1.getDataRange();
var dataValues = dataRange.getValues();
for (var i = 0; i<dataValues.length; i++) {
for (var j= 0; j<dataValues.length; i++) {
/* If blank or 0 - zero, skip */
if (dataValues[i][3] == "" || dataValues[i][3]== 0) {continue;}
/* If value is >=1, insert new row(s) below the active row */
if (dataValues[i][3] >=1) {
sheet1.insertRowAfter(i);
sheet1.getRange(...) // copy the data from previous + string
}
}
}
}
In your shared Spreadsheet, you want to convert from the values of "A2:B3" to the values of "A6:B11".
In your shared image, you want to achieve as follows.
From
Data1 A0HD, B0DP
Data2 C12X, D0B1, E2C1, F6H1
To
Data1 A0HD
Data1 B0DP
Data2 C12X
Data2 D0B1
Data2 E2C1
Data2 F6H1
You want to achieve this using Google Apps Script.
I could understand like above. If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Sample script:
In order to test the script, please use the following script to your shared Spreadsheet. And run the script.
function myFunction() {
var sourceSheetName = "Sheet6";
var destinationSheetName = "Sheet6";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sourceSheetName);
// Retrieve source values.
var values = sheet.getRange("A2:B3").getValues();
// Convert values.
var result = values.reduce(function(ar, [a, b]) {
var temp = b.split(",");
for (var i = 0; i < temp.length; i++) {
ar.push([a, temp[i].trim()]);
}
return ar;
}, []);
// Put values.
var dstSheet = ss.getSheetByName(destinationSheetName);
dstSheet.getRange(dstSheet.getLastRow() + 1, 1, result.length, result[0].length).setValues(result);
}
In above script, when the script is run, the values of "A2:B3" from the "Sheet6" are retrieved and the converted values are put to the last row of "Sheet6".
If only input values are put to the source sheet, you can also use var values = sheet.getRange(2, 1, sheet.getLastRow() - 1, 2).getValues(); instead of var values = sheet.getRange("A2:B3").getValues();.
Note:
This is a simple sample script. So please modify this for your actual Spreadsheet.
Reference:
reduce()
I am working on a google app script to fetch a range, multiply one column in the range by another column in the range, then output to a different column within the original range. This should be simple, but I can't figure it out.
function myFunction() {
var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var data = sheet.getRange("A1:B22").getValues();
var newData = []
for (i in data){
var row = data[i];
var multiply = row[0] * row[1]
newData.push(multiply)
}
sheet.getRange(1,3,22,1).setValues(newData)
}
Thanks for the recommendation, but that didn't work unfortunately. The reason I'm not using the arrayformula function is because this is actually a small piece of a larger, more complicated function.
What did end up working is pushing the "multiply" variable into newData as an array by putting it in brackets.
function myFunction() {
var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var data = sheet.getRange("A1:B22").getValues();
var newData = []
for (i in data){
var row = data[i];
var multiply = row[0] * row[1]
newData.push([multiply])
Logger.log(newData)
}
sheet.getRange(1,3,22,1).setValues(newData)
}