Find and Replace on row1 google sheets function - google-apps-script

Very new to this, I am trying to Find and Replace on row1 only
I want to find aa and replace it with ZZZ
I am trying two different ways but neither work
Thanks
first way:
function replace3() {
var sheet = SpreadsheetApp.getActiveSheet();
var lc = sheet.getMaxColumns();
var range = sheet.getRange("a1:z1");
var values = range.getValues();
for (var col in values[1]) {
if (values[0][col] ='aa') {
values[0][col] = 'ZZZ';
}
}
range.setValues(values);
}
Second Way:
function replace2() {
var sheet = SpreadsheetApp.getActiveSheet();
var lc = sheet.getMaxColumns();
var range = sheetname.getRange(1, 1, 1, lc);
var values = range.getValues();
for (var i = 0; i <= lc; i++) {
if (values[0][i] ='aa') {
values[0][i] = 'ZZZ';
}
}
range.setValues(values);
}

How about the following modofications?
For replace3()
The index of array starts 0.
When values are compared at if, please use ==.
Modified script :
function replace3() {
var sheet = SpreadsheetApp.getActiveSheet();
var lc = sheet.getMaxColumns();
var range = sheet.getRange("a1:z1");
var values = range.getValues();
for (var col in values[0]) { // Modified
if (values[0][col] =='aa') { // Modified
values[0][col] = 'ZZZ';
}
}
range.setValues(values);
}
For replace2()
sheetname is not declared.
When values are compared at if, please use ==.
Modified script :
function replace2() {
var sheet = SpreadsheetApp.getActiveSheet();
var lc = sheet.getMaxColumns();
var range = sheet.getRange(1, 1, 1, lc); // Modified
var values = range.getValues();
for (var i = 0; i <= lc; i++) {
if (values[0][i] == 'aa') { // Modified
values[0][i] = 'ZZZ';
}
}
range.setValues(values);
}
Other method :
Also you can achieve it using map().
Sample script :
function sample() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("a1:z1");
var values = range.getValues();
var data = values[0].map(function(e){return e == 'aa' ? 'ZZZ' : e});
range.setValues([data]);
}
If I misunderstand your question, please tell me. I would like to modify.

Related

Google script function works when it runs separately, but when I run all the functions together it doesn't work

I've got a question about my script. I've got a script where when running together only 2 out of 3 functions run, the other function does not run. The one function that does not work when running together is the "medewerkerLijst" function. When I run that function on it's own it works perfectly as it should, when running it together with the other 2 functions it does not work. I can't figure out why it's not working.
The functions "nieuwDossier" & "sorteerDossiers" do work when running together. Sorry if my code is a mess, I'm still learning how to code.
function Aanmaken(){
medewerkerLijst();
nieuwDossier();
sorteerDossiers();
}
function medewerkerLijst() {
var ss5 = SpreadsheetApp.getActiveSpreadsheet();
var copySheet2 = ss5.getSheetByName("-Dossier");
var pasteSheet2 = ss5.getSheetByName("-Medewerkers");
// get source range
var source2 = copySheet2.getRange(2,7,1,1);
// get destination range
var destination2 = pasteSheet2.getRange(pasteSheet.getLastRow()+1,1,1,1);
// copy values to destination range
source2.copyTo(destination2, {contentsOnly:true});
}
function nieuwDossier() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheetByName('-Template');
sheet.copyTo(source).setName('Nieuw');
var sheet2 = source.getSheetByName('-Dossier');
var cell = sheet2.getRange("G2");
var value = cell.getValue();
var sheet3 = source.getSheetByName('Nieuw');
sheet3.setName(value);
sheet3.setTabColor(null);
}
function sorteerDossiers () {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetNameArray = [];
var sheets = ss.getSheets();
for (var i = 0; i < sheets.length; i++) {
sheetNameArray.push(sheets[i].getName());
}
sheetNameArray.sort();
for( var j = 0; j < sheets.length; j++ ) {
ss.setActiveSheet(ss.getSheetByName(sheetNameArray[j]));
ss.moveActiveSheet(j + 1);
}
}
This runs just fine
function main() {
var ss = SpreadsheetApp.getActive();
var sh1 = ss.getSheetByName("Sheet1");
var sh2 = ss.getSheetByName("Sheet2");
var rg1 = sh1.getRange(2, 7, 1, 1);
var rg2 = sh2.getRange(sh2.getLastRow() + 1, 1, 1, 1);
rg1.copyTo(rg2, { contentsOnly: true });
var sh3 = ss.getSheetByName('Sheet3');
var sh4 = sh3.copyTo(ss).setName('Sheet4');
var cell = sh1.getRange("G2");
var v1G2 = cell.getValue();
sh4.setName(v1G2);
sh4.setTabColor(null);
var shts = ss.getSheets().map(sh => sh.getName()).sort().forEach((n, i) => {
ss.setActiveSheet(ss.getSheetByName(n));
ss.moveActiveSheet(i + 1)
});
}

data transfert based on cell value on google sheet

I'm not good with coding and i tried to mix some codes that i found and made what i needed, but now i face a difficult problem for me, so I'm trying when to press the button that i created to run the script to send the data that have for example an 'X' in the last column. i successfully made the sending from one sheet to another but it send all the data for now i want to be sent only the chosen ones with an 'X'.
any help I'll be grateful.
this is my code
thank you
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("Sheet1");
var url = "https://docs.google.com/spreadsheets/d/15nIAXcP0a14OvvBr5lww4tO23stQD4PEu0QDAcgaFyE/edit#gid=0";
var ss2 = SpreadsheetApp.openByUrl(url);
var pasteSheet = ss2.getSheetByName("Sheet2");
// get source range
var max = copySheet.getMaxRows().toString();
var range = copySheet.getRange(2,1,max,4);
var dataValues = range.getValues();
for(var i = 1; i < dataValues.length; i++)
{
if(dataValues[i][5] === 'X')
{
copySheet.appendRow([dataValues[i][0],
dataValues[i][1],
dataValues[i][2],
dataValues[i][3],
dataValues[i][4]]);
}
}
for(var i = 1; i < dataValues.length; i++)
{
if(dataValues[i][5] === 'X')
{
var clearRow = i+1;
dataSheet.getRange('A' + clearRow + ':F' + clearRow).clear();
}
}
// get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,max,1);
// clear source values
Browser.msgBox('Commande Confirmer');
}
This is all that your function does
dataSheet is undefined so I assume it was csh
function lfunko() {
const ss = SpreadsheetApp.getActive();
const csh = ss.getSheetByName("Sheet1");
const ss2 = SpreadsheetApp.openByUrl("ssurl");
const psh = ss2.getSheetByName("Sheet2");
var vs = csh.getRange(2, 1, csh.getLastRow() - 1, csh.getLastColumn()).getValues();
vs.forEach((r,i) => {
if (vs[i][5] === 'X') {
csh.appendRow([vs[i][0], vs[i][1], vs[i][2], vs[i][3], vs[i][4]]);
csh.getRange(i + 1, 1, 1, 6).clear();
}
});
}

Import 3 google spreadsheet at same time into another

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);
}
});
});
}

Converting my script to use getRangeData instead of using an iterative loop (GoogleAppScript)

I am having issues converting my last script to work with getDataRange. I got some help converting my original functions, seen below:
function twentyDKP() {
alertBox20DKP()
}
function alertBox20DKP() {
var sh=SpreadsheetApp.getUi();
var response=sh.alert("Add 20 DKP to all raiders?", sh.ButtonSet.YES_NO);
if(response==sh.Button.YES) {
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet();
var raiders = activeSheet.getRange(1, 12).getValue();
// In your situation, the range is the same. So "range" is declared here.
var range = activeSheet.getRange(4, 2, raiders);
// Create values for putting to the range.
var values = range.getValues().map(function(row) {return [row[0] + 20]});
// Put the created values to the range.
range.setValues(values);
// Update the cells. Before "alert" is shown.
SpreadsheetApp.flush();
var complete=sh.alert("20 DKP has been added to all raiders.", sh.ButtonSet.OK);
}
}
However, I now want to do the same with my subtraction script that would rely on two ranges of data. I'm still very new to coding, and am basically getting by on youtube tutorials and advice from this forum. How would I implement the same change to the below code?
function spentDKP() {
alertBoxSpentDKP()
}
function alertBoxSpentDKP() {
var sh=SpreadsheetApp.getUi();
var response=sh.alert("Subtract spent DKP of all raiders?", sh.ButtonSet.YES_NO);
if(response==sh.Button.YES) {
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet();
var raiders = activeSheet.getRange(1, 12).getValue()+4;
for(var i=4;i<raiders;i++){
var DKP = activeSheet.getRange(i,2).getValue()
var spentDKP = activeSheet.getRange(i,4).getValue();
if(spentDKP>0){
activeSheet.getRange(i,2).setValue(DKP-spentDKP)
}
}
var complete=sh.alert("All DKP has been subtracted, please clear the loot window to reset values.", sh.ButtonSet.OK);
}
}
Many thanks in advance.
Try replacing this
var raiders = activeSheet.getRange(1, 12).getValue()+4;
for(var i=4;i<raiders;i++){
var DKP = activeSheet.getRange(i,2).getValue()
var spentDKP = activeSheet.getRange(i,4).getValue();
if(spentDKP>0){
activeSheet.getRange(i,2).setValue(DKP-spentDKP)
}
}
with this
var raiders = activeSheet.getRange(1, 12).getValue();
var range = activeSheet.getRange(4, 2, raiders, 3); // Get the range with the data to be processed
var inputValues = range.getValues(); // Get the data from that range
var outputValues = inputValues.map(Subtract); // Use a function to subtract the spent DKP from the DKP balance available
range.setValues(outputValues); // post the calculated values back to the sheet
And add a helper function for map:
// Helper function for map
function Subtract(inputValuesRow) {
if (inputValuesRow[2] > 0) {
inputValuesRow[0] -= inputValuesRow[2];
}
return inputValuesRow; // This has now been change where column 4 value has been subtracted from the column 2 value
}
Edit
To preserve the formulas in the middle column, remove the Subtract helper function. And use this as the replacement:
var raiders = activeSheet.getRange(1, 12).getValue();
var range = activeSheet.getRange(4, 2, raiders, 3); // Get the range with the data to be processed
var inputValues = range.getValues(); // Get the data from that range
var outputValues = [];
for (var r = 0; r < inputValues.length; r++) {
if ( inputValues[r][2] > 0 ) {
outputValues.push([inputValues[r][0] - inputValues[r][2]])
} else {
outputValues.push([inputValues[r][0]])
}
}
activeSheet.getRange(4, 2, raiders, 1).setValues(outputValues);

compare rows on google spreadsheets

I want to identify equal rows in two different sheets on same spreadsheet. I tried below code, it doesn't work.
function getMyEqualRows()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheets()[0];
var sheet2 = ss.getSheets()[1];
var sheetOneValues = sheet1.getRange('A1:G20').getValues();
var sheetTwoValues = sheet2.getRange('A1:G20').getValues();
var equalRows = [];
for (var i = 0; i <= sheetOneValues.length; i++) {
for(var j = 0; j <= sheetTwoValues.length; j++){
if(sheetOneValues[i] == sheetTwoValues[j]) {
equalRows.push(sheetOneValues[i]);
}
}
return equalRows;
}
}
You can't compare two arrays for equality with ==. Instead you can use .join() method. It concatenates all elements in these arrays to a string. This check string arrays for equality. I'm not sure if this is the best way.
function getMyEqualRows()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheets()[0];
var sheet2 = ss.getSheets()[1];
var sheetOneValues = sheet1.getRange('A1:G20').getValues();
var sheetTwoValues = sheet2.getRange('A1:G20').getValues();
var equalRows = [];
for(var i in sheetOneValues)
{
var anEqualRow = false;
for(var j in sheetTwoValues)
{
if(sheetOneValues[i].join() == sheetTwoValues[j].join()){
anEqualRow = true;
}
}
if(anEqualRow){
equalRows.push(sheetOneValues[i]);
}
}
return equalRows;
}
Hope this would work!