Calling copyValuesToRange method twice - google-sheets

I want to copy some columns to another sheet. When i call the copyValuesToRange method twice, one is working, but the other is not.
function myFunction() {
var s = SpreadsheetApp.getActiveSpreadsheet();
var target = SpreadsheetApp.openById("f3y53y54y45h45jh454");
var target_sheet = target.getSheetByName("Sheet2");
var sheet = s.getSheetByName("Sheet1");
var sheet_last_row = sheet.getLastRow() + 1;
var source_range = sheet.getRange("B1:H"+sheet_last_row);
var source_range2 = sheet.getRange("K1:P"+sheet_last_row);
var sWidth=source_range.getWidth() + 1;
var sHeight=source_range.getHeight() + 1;
var sWidth2=source_range2.getWidth() + 1;
var sHeight2=source_range2.getHeight() + 1;
var last_row=target_sheet.getLastRow();
source_range.copyValuesToRange(target_sheet , 1, sWidth, last_row + 1, last_row + sHeight );
source_range2.copyValuesToRange(target_sheet , 8, sWidth2, last_row + 1, last_row + sHeight2 );
}
How can i fix this problem or is there another solution for copying cells the another sheet.

Shift the width of the second range from the starting point to (the end point of the first range+1) by sWidth2, as it should be the column number of the target range right border:
source_range2.copyValuesToRange(target_sheet , sWidth1+1, sWidth1+1+sWidth2, last_row + 1, last_row + sHeight2 );

Related

Google sheets copy and paste row 120 times in the same sheet

So I have a sheet with about 800 rows. What I need to do is copy and paste each one 120 times. Instead of doing this manually I am hoping there is an automated way to do this in one shot. I have searched for a few things but everything I found had to do with copying the rows conditionally.
I don't need conditions. I just need all, each one of the 800 rows to be duplicated 120 times.
Any help or ideas is greatly appreciated.
Cheers
Modified #SpiderPig code to clone in a interleaved fashion
function duplicateRows() {
var sheet = SpreadsheetApp.getActiveSheet()
var numRows = sheet.getLastRow()
var numColumns = sheet.getLastColumn()
var numberOfClones = 120
for(var i = 0; i < numRows; i++) {
range = sheet.getRange((i*numberOfClones)+ 1, 1, 1, numColumns);
sheet.insertRows((i*numberOfClones)+ 2, numberOfClones-1)
range.copyTo(sheet.getRange((i*numberOfClones)+ 2 , 1, numberOfClones-1, numColumns));
}
}
Also instead of using a loop with range.copyTo(destination) to paste 120 times, you can expand the destination range to 120 rows. It will automatically paste the same value over the entire range.
So instead of this
for(var i = 1; i <= 120; i++) {
range.copyTo(sheet.getRange(numRows * i + 1, 1, numRows, numColumns));
}
you can do this once
range.copyTo(sheet.getRange(numRows * i + 1, 1, 120*numRows, numColumns));
Here is a script that will copy all the rows in the current sheet 120 times.
function duplicateRows() {
var sheet = SpreadsheetApp.getActiveSheet(),
numRows = sheet.getLastRow(),
numColumns = sheet.getLastColumn(),
range = sheet.getRange(1, 1, numRows, numColumns);
for(var i = 1; i <= 120; i++) {
range.copyTo(sheet.getRange(numRows * i + 1, 1, numRows, numColumns));
}
}

swift- get exc_bad_instruction (code=exc_i386_invop, subcode=0x0) with array value replacement in while loop

I am making a note writing app. In this app I am turning the lines into a bezier curve. At the moment I am getting an error when I try to put new values into a matrix that was defined outside of the while loop. I have tried the expression by itself when put into a dummy variable and it works in the loop. When I use the format for replacing a value of the two dimensions variable it works outside the loop, however, when I do both those actions together in the loop it does not work.
//: Playground - noun: a place where people can play
import UIKit
var x2 = 6.0
var y2 = 5.0
var x1 = 1.0
var y1 = 1.0
var p1x = 2.0
var p1y = 3.0
var B = 6.5
var Ba = 2.2
var percentall = Ba/B
var yall = 5.0
var xall = 1.0
var A = 4.0
var C = 5.0
var Ct = 0.0
var At = 0.0
var Aall = Int(A) * 10
var Call = Int(C) * 10
var thelistx = [[Double]](count: Call, repeatedValue: [Double](count: Call, repeatedValue: 0.0 ))
var thelisty = Array(count: Aall, repeatedValue: Array(count: Call, repeatedValue: 0.0 ))
var theAt = 0
var theCt = 0
while At <= A {
var Apercent = percentall * At
var Aend = y1 + At
var yslope = (A - At) * percentall + Aend
var lefty = (yslope - Apercent) * percentall + Apercent
var righty = ( y2 - yslope) * percentall + yslope
while Ct <= C {
var Cpercent = percentall * Ct
var Cend = x2 - Ct
var xslope = (C - Ct) * percentall + Cend
var leftx = (xslope - x1) * percentall + x1
var rightx = (x2 - xslope) * percentall + xslope
thelistx [theAt] [theCt] = (rightx - leftx) * percentall + left
*********************Execution was interrupted, reason exc_bad_instruction (code=exc_i386_invop, subcode=0x0) ***************
thelisty [theAt] [theCt] = (righty - lefty) * percentall + lefty
Ct += 0.1
theCt += 1
}
At = At + 0.1
theAt += 1
}
The console shows what your error is:
fatal error: Index out of range
You're going out of bounds with thelistx [theAt] [theCt]
Changing while Ct < C to Ct < C - 1 keeps your calls in the bounds of the array.

SOLVE function better solution

I have a spreadsheet where a lot of cells are multiplied with a CONSTANT value and added and the result (SOLL) differs from the expected (IST) value and the only way I was able to find, was to make 10 iterations modifying each time the CONSTANT value till the SOLL and IST are pretty equal.
My method looks too stupid and I am just asking a beautiful and intelligent way to solve it...
thanks
function costante()
{
var ss = SpreadsheetApp.getActiveSpreadsheet(); //spreadsheet "options"
SpreadsheetApp.setActiveSheet(ss.getSheets()[0]); //sheet nr.1
var sheet = SpreadsheetApp.getActiveSheet();
for(var i=0; i<10; i++){
var dataRange = sheet.getRange("o5:o5"); //marge ist
var mist = dataRange.getValues();
var dataRange = sheet.getRange("o4:o4"); //marge soll
var msoll = dataRange.getValues();
var dataRange = sheet.getRange("n1:n1"); //costante
var costante = dataRange.getValues();
var minus = 1;
if(mist - msoll < 0) { minus = -1};
costante = mist / msoll * minus * costante;
sheet.getRange("n1:n1").setValues([[costante]]);}
}
Maybe what you want, assuming your "lot of cells" are in A1:A10 and the IST value is in E1 is:
=E1/sum(A1:A10)
but please note the tag wiki.
thanks, I was first surprised by the simple method and I checked it:
10 values and their addition gives for instance = 10 (sum(a1:a10))
the IST value that I would like to have is 500 (E1)
E1/sum(A1:A10) = 500/10 = 50 = C (COSTANTE)
E1 = Sum(A1:A10) x C
if I multiply each A(y) value with 50, I have 500 and the proposed formula would perfectly work
BUT I forgot to mention that the values of A(y) are formulas that include already my COSTANTE it means that in reality each A(y) value is a formula that contains C
E1 = Sum( A(y) x C ) x C
a) for that reason the solution proposed does not give the needed value, and I was obliged to repeat the calculation ca.10 times
b) I also added a delay of 1 second because I was not sure if the spreadsheet is able to calculate so fast (please tell me if it is necessary)
c) and I said that if the result is +/- 2 from expected value, to stop to calculate
It works but is still not beautiful...
function costante()
{
var ss = SpreadsheetApp.getActiveSpreadsheet(); //spreadsheet "options"
SpreadsheetApp.setActiveSheet(ss.getSheets()[0]); //sheet nr.1
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("o5:o5"); //marge ist
var mist = dataRange.getValues();
for(var i=0; i<20; i++)
{
var dataRange = sheet.getRange("o4:o4"); //marge soll
var msoll = dataRange.getValues();
var dataRange = sheet.getRange("n1:n1"); //costante
var costante = dataRange.getValues();
var diff = msoll - mist;
if(diff < -2) { costante = costante * 1.005;}
else if (diff > 2) { costante = costante * 0.995;}
else {return;}
sheet.getRange("n1:n1").setValues([[costante]]);
Utilities.sleep(1000); //wait 1.5sec
}
}

Plotting a line using d3 and an JSON data object passed from rails

I'm pushing the boundaries of experience here and cant see what I am doing wrong.
I'm pulling a bunch of data from a DB in rails, converting it to JSON and trying to plot it in d3.
The data is a simple JSON of {date => number} and the data is fine.
I'm doing something wrong with d3 in the loop at the bottom of the code but cant see what.
The axes plot fine but I can't get the line to draw.
Here is my code:
var data = <%= #signups.to_json.html_safe %>;
var date, signups
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 500 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%Y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(date)
.y(signups)
.interpolate("linear");
var svg = d3.select(".container").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Find range of data for domain
var min_date = Infinity, max_date = -Infinity;
var min_signups = Infinity, max_signups = -Infinity;
var x;
$.each(data, function(key, value) {
temp = parseDate(key)
if( temp < min_date) min_date = temp;
if( temp > max_date) max_date = temp;
if( +value < min_signups) min_signups = +value;
if( +value > max_signups) max_signups = +value;
});
x.domain([min_date, max_date]);
y.domain([0, max_signups]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
svg.append("path")
$.each(data, function(key, value) {
date = parseDate(key);
signups = value;
d3.select("path")
.append("svg")
.attr("d", d3.svg.line()
.x(date)
.y(signups)
.interpolate("linear"));
});
Any help would be greatly appreciated
The D3 way would be to pass all your data to a suitable line generator. This is fairly simple in your case, you just need to convert the object that contains all the data to an array that D3 can work with using d3.entries().
var line = d3.svg.line()
.x(function(d) { return x(parseDate(d.key)); })
.y(function(d) { return y(d.value); });
svg.selectAll("path").data([d3.entries(data)])
.enter().append("path").attr("d", line);
As you have only a single line, you could also use .datum() to bind the data, but using .data() leaves you the option of passing in data for more lines later.
Complete jsfiddle here. When modifying this, make sure that you create the line before adding the axes, otherwise D3's data matching won't work with the default matching and you won't get any lines. To fix this, you could supply a matching function, but to start with it's much easier to keep to this order.

simplify and rearrange my google script for faster process this often stucks in the middle of the process

Can anyone simplify and rearrange my script such that it works faster without stucking . This script was made to extract spreadsheet data from 4 spreadsheets and deleting blank rows based on a column criteria, This script is working well but taking long time and suddenly/often breaks process saying that spreadsheet page needs to refresh thus stopping the entire process. which should follow with rerunning the script. - Thanks in advance.
my script is as follows :
function myFunction() {
// spreadsheets key to extract data.
//Bhaskar 0AjkkHlm3kCphdFh3M2dtRDdoZHhWZlg5UzFjSWZFcVE
//RAmohan 0AjkkHlm3kCphdGFlNTVhSDc5VXVTeS0xc2ZISDRGZlE
//Krishnareddy 0AjkkHlm3kCphdEhDWEllalpoM3VmNE5weUNLZkd4TVE
//Suni 0AjkkHlm3kCphdFUxTXJlN3lGYkRMY2NXUUkzSTVfbEE
var copieddata = SpreadsheetApp.openById('0AjkkHlm3kCphdFh3M2dtRDdoZHhWZlg5UzFjSWZFcVE').
getSheetByName('List').getDataRange().getValues();
//getSheetByName('List').getRange('I6:AT500').getValues();
var s1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
SpreadsheetApp.setActiveSheet(s1);
//getRange(StartingROWS(1,2,3,4,...),StartingCOLUMNS(A,B,C,D..),
s1.getRange(1,1,copieddata.length,copieddata[0].length).setValues(copieddata);
//var col1count = SpreadsheetApp.getActiveSheet().getRange(1,1,copieddata.length,copieddata[0].length).getNumColumns();
//var row1count = SpreadsheetApp.getActiveSheet().getRange(1,1,copieddata.length,copieddata[0].length).getNumRows();
SpreadsheetApp.flush(); //force the data to be written
// here ends sheet 1 -------
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var numRows = sheet.getLastRow();
var datasheet = sheet.getDataRange();
var data = datasheet.getValues();
//Browser.msgBox(" data lenght -" + data.length + " rage is " + datasheet);
for (var i = data.length; i > 0; --i){
var ii=i-1;
var row = data[ii];
var name = row[6];
var len = name.length;
//Browser.msgBox("row number" + i + " ->" + row[10] + "<- its length =" + len);
if(name.length!=3){
//Browser.msgBox("delete ." + i);
sheet.deleteRow(i);
}
SpreadsheetApp.flush(); //force the data to be written
}
SpreadsheetApp.flush(); //force the data to be written
// ------------------
var lrange = SpreadsheetApp.getActiveSheet().getLastRow();
//Browser.msgBox("l range - " + lrange);
var copieddata = SpreadsheetApp.openById('0AjkkHlm3kCphdGFlNTVhSDc5VXVTeS0xc2ZISDRGZlE').
getSheetByName('List').getDataRange().getValues();
var s1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
SpreadsheetApp.setActiveSheet(s1);
s1.getRange((lrange+1),1,copieddata.length,copieddata[0].length).setValues(copieddata);
//var col1count = SpreadsheetApp.getActiveSheet().getRange(1,1,copieddata.length,copieddata[0].length).getNumColumns();
//var row1count = SpreadsheetApp.getActiveSheet().getRange(1,1,copieddata.length,copieddata[0].length).getNumRows();
SpreadsheetApp.flush(); //force the data to be written
// here ends sheet 2 -------
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var numRows = sheet.getLastRow();
var datasheet = sheet.getDataRange();
var data = datasheet.getValues();
//Browser.msgBox(" data lenght -" + data.length + " rage is " + datasheet);
for (var i = data.length; i > 0; --i){
var ii=i-1;
var row = data[ii];
var name = row[6];
var len = name.length;
//Browser.msgBox("row number" + i + " ->" + row[10] + "<- its length =" + len);
if(name.length!=3){
//Browser.msgBox("delete ." + i);
sheet.deleteRow(i);
}
SpreadsheetApp.flush(); //force the data to be written
}
// ------------------
var lrange = SpreadsheetApp.getActiveSheet().getLastRow();
//Browser.msgBox("l range - " + lrange);
var copieddata = SpreadsheetApp.openById('0AjkkHlm3kCphdEhDWEllalpoM3VmNE5weUNLZkd4TVE').
getSheetByName('List').getDataRange().getValues();
var s1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
SpreadsheetApp.setActiveSheet(s1);
s1.getRange((lrange+1),1,copieddata.length,copieddata[0].length).setValues(copieddata);
//var col1count = SpreadsheetApp.getActiveSheet().getRange(1,1,copieddata.length,copieddata[0].length).getNumColumns();
//var row1count = SpreadsheetApp.getActiveSheet().getRange(1,1,copieddata.length,copieddata[0].length).getNumRows();
SpreadsheetApp.flush(); //force the data to be written
// here ends sheet 3 -------
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var numRows = sheet.getLastRow();
var datasheet = sheet.getDataRange();
var data = datasheet.getValues();
//Browser.msgBox(" data lenght -" + data.length + " rage is " + datasheet);
for (var i = data.length; i > 0; --i){
var ii=i-1;
var row = data[ii];
var name = row[6];
var len = name.length;
//Browser.msgBox("row number" + i + " ->" + row[10] + "<- its length =" + len);
if(name.length!=3){
//Browser.msgBox("delete ." + i);
sheet.deleteRow(i);
}
SpreadsheetApp.flush(); //force the data to be written
}
// ------------------
var lrange = SpreadsheetApp.getActiveSheet().getLastRow();
//Browser.msgBox("l range - " + lrange);
var copieddata = SpreadsheetApp.openById('0AjkkHlm3kCphdFUxTXJlN3lGYkRMY2NXUUkzSTVfbEE').
getSheetByName('List').getDataRange().getValues();
var s1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
SpreadsheetApp.setActiveSheet(s1);
s1.getRange((lrange+1),1,copieddata.length,copieddata[0].length).setValues(copieddata);
//var col1count = SpreadsheetApp.getActiveSheet().getRange(1,1,copieddata.length,copieddata[0].length).getNumColumns();
//var row1count = SpreadsheetApp.getActiveSheet().getRange(1,1,copieddata.length,copieddata[0].length).getNumRows();
SpreadsheetApp.flush(); //force the data to be written
// here ends sheet 4 -------
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var numRows = sheet.getLastRow();
var datasheet = sheet.getDataRange();
var data = datasheet.getValues();
//Browser.msgBox(" data lenght -" + data.length + " rage is " + datasheet);
for (var i = data.length; i > 0; --i){
var ii=i-1;
var row = data[ii];
var name = row[6];
var len = name.length;
//Browser.msgBox("row number" + i + " ->" + row[10] + "<- its length =" + len);
if(name.length!=3){
//Browser.msgBox("delete ." + i);
sheet.deleteRow(i);
}
SpreadsheetApp.flush(); //force the data to be written
}
}
spreadsheet link is as follows : Clik here to enter into my spreadsheet
here's my attempt:
function myFunction2() {
var source = ['0AjkkHlm3kCphdFh3M2dtRDdoZHhWZlg5UzFjSWZFcVE',
'0AjkkHlm3kCphdGFlNTVhSDc5VXVTeS0xc2ZISDRGZlE',
'0AjkkHlm3kCphdEhDWEllalpoM3VmNE5weUNLZkd4TVE',
'0AjkkHlm3kCphdFUxTXJlN3lGYkRMY2NXUUkzSTVfbEE'];
var copied = [];
for (var i = 0; i < source.length; i++) {
copied = copied.concat(SpreadsheetApp.openById(source[i]).getSheetByName('List').getDataRange().getValues());
}
for (var j = 0; j < copied.length; j++) {
if (copied[j][6].length != 3) {
copied.splice(j, 1);
j--;
}
}
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
sheet.clearContents();
sheet.getRange(1, 1, copied.length, copied[0].length).setValues(copied);
}
In this I create one big javascript array from the four spreadsheets, remove elements ("rows") from that array (rather than deleting rows in the spreadsheet itself which I presume is the reason why it's slow), clear the destination sheet, and set the values of the modified array in one go.
HTH
Adam

Resources