Hello I am currently working on a time tracking system. With the following code I track the time how long a value was in a cell. This time is recorded in another worksheet and this is done continuously by appendRow ().
function onEdit(e) {
addTimestamp(e);
}
function addTimestamp(e) {
var ui = SpreadsheetApp.getUi();
var ws = "Tabellenblatt2";
var ss = e.source;
var targetSheet = ss.getSheetByName("Tabellenblatt1");
var range = targetSheet.getRange(3, 2, 1000, 1);
var currentDate = new Date();
var scriptProperties = PropertiesService.getScriptProperties();
if (e.source.getActiveSheet().getName() === ws) {
var cell = ss.getActiveCell();
var val = cell.getValue();
var sourceRowIndex = cell.getRow();
if (val != "") {
let rowToAdd = [val, "", currentDate, ""]
targetSheet.appendRow(rowToAdd);
scriptProperties.setProperty(sourceRowIndex, targetSheet.getLastRow());
} else {
var rowIndex = Number(scriptProperties.getProperty(sourceRowIndex));
if (rowIndex) targetSheet.getRange(rowIndex, 4).setValue(currentDate);
}
}
}
Now one Picture to show my Problem:
The problem is that the cells should start in row 1, is that possible with getLastRow ()?
Determine the last row with content based on another column (e.g. column A):
function onEdit(e) {
addTimestamp(e);
}
function addTimestamp(e) {
var ui = SpreadsheetApp.getUi();
var ws = "Tabellenblatt2";
var ss = e.source;
var targetSheet = ss.getSheetByName("Tabellenblatt1");
var range = targetSheet.getRange(3, 2, 1000, 1);
var currentDate = new Date();
var scriptProperties = PropertiesService.getScriptProperties();
if (e.source.getActiveSheet().getName() === ws) {
var cell = ss.getActiveCell();
var val = cell.getValue();
var sourceRowIndex = cell.getRow();
if (val != "") {
let rowToAdd = [val, "", currentDate, ""]
let rowA=targetSheet.getRange("A1:A").getValues().filter(String).length+1; // new code
targetSheet.getRange(rowA,1,1,rowToAdd.length).setValues([rowToAdd]); // new code
scriptProperties.setProperty(sourceRowIndex, targetSheet.getLastRow());
} else {
var rowIndex = Number(scriptProperties.getProperty(sourceRowIndex));
if (rowIndex) targetSheet.getRange(rowIndex, 4).setValue(currentDate);
}
}
}
it would be easier to change the formula for Time to not display anything at all unless there was an entry, then getLastRow() will work just fine. For help with that, share the formula that's calculating the time.
Related
I feel like today I'm not able to do anything with my script.
I'm trying to do a simple test, if the date in cell1 is equal to the date in cell2 then I will copy and paste the data into another file, in a specific sheet. If cell1 is different than cell2, I will copy the data in the same other file but in a different sheet.
I can't make it work. What am I doing wrong? thanks for the help,
j.
function copytransactionTodispatchN() {
var sss = SpreadsheetApp.getActiveSpreadsheet();; // sss = source spreadsheet
var ss = sss.getSheetByName("Nouveau Client - Transaction du jour"); // ss = source sheet
var ssn = sss.getSheetByName("Nouveau Client"); // ss = source sheet
//Get full range of data
var SRange = ss.getRange('A2:f2');
var SData = SRange.getValues();
var dateachat = ssn.getRange('c20').getValues;
var datelivraison = ssn.getRange('e31').getValues;
if(dateachat == datelivraison){
var tss = SpreadsheetApp.openById("idoftheotherfile"); // tss = target spreadsheet
var ts = tss.getSheetByName("sheet1"); // ts = target sheet
ts.getRange("b"+(getLastDataRow(ts)+1)+":i"+(getLastDataRow(ts)+1)).setValues(SData);
}
else {var tss = SpreadsheetApp.openById("idoftheotherfile"); // tss = target spreadsheet
var ts1 = tss.getSheetByName("Sheet2"); // ts = target sheet
//set the target range to the values of the source data
ts1.getRange("a"+(getLastDataRow(ts)+1)+":h"+(getLastDataRow(ts)+1)).setValues(SData);
}
}
function getLastDataRowN(sheet) {
var lastRow = sheet.getLastRow();
var range = sheet.getRange("b" + lastRow);
if (range.getValue() !== "") {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
}
}
Ok, the mistakes were :
getlastrow function was not working for condition 2
the test of the date was not woking, I had to replace if(dateachat == datelivraison.) by if(dateachat.valueOf() == datelivraison.valueOf())
And now it is all good. Thank you all!!
var sss = SpreadsheetApp.getActiveSpreadsheet();; // sss = source spreadsheet
var ss = sss.getSheetByName("Nouveau Client - Transaction du jour"); // ss = source sheet
var ssn = sss.getSheetByName("Nouveau Client"); // ss = source sheet
//Get full range of data
var SRange = ss.getRange('A2:h2');
var SData = SRange.getValues();
var dateachat = ssn.getRange('c20').getValues;
var datelivraison = ssn.getRange('e31').getValues;
if(dateachat.valueOf() == datelivraison.valueOf()){
var tss = SpreadsheetApp.openById("IDtarget"); // tss = target spreadsheet
var ts = tss.getSheetByName("Sheet1"); // ts = target sheet
ts.getRange("b"+(getLastDataRowb(ts)+1)+":i"+(getLastDataRowb(ts)+1)).setValues(SData);
}
else {var tss = SpreadsheetApp.openById("IDtarget"); // tss = target spreadsheet
var ts = tss.getSheetByName("Sheet 2"); // ts = target sheet
//set the target range to the values of the source data
ts.getRange("a"+(getLastDataRowa(ts)+1)+":h"+(getLastDataRowa(ts)+1)).setValues(SData);
}
}
function getLastDataRowb(sheet) {
var lastRow = sheet.getLastRow();
var range = sheet.getRange("b" + lastRow);
if (range.getValue() !== "") {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
}
}
function getLastDataRowa(sheet) {
var lastRow = sheet.getLastRow();
var range = sheet.getRange("a" + lastRow);
if (range.getValue() !== "") {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
}
}```
var dateachat = ssn.getRange('c20').getValues;
Variable ssn isn't defined anywhere, which is likely causing dateachat to be undefined or null.
I tried to fill it with my sheet data, but that
var dataRange = sheet.getDataRange();
get an error. What should I do?
function RefreshImports() {
var lock = LockService.getScriptLock();
if (!lock.tryLock(5000)) return; // Wait up to 5s for previous refresh to end.
var id = "1r7TgCWXfjmcjufT0yz9qcFDlr482SdHDHlZYblXyAt0"; // [YOUR SPREADSHEET ID]
var ss = SpreadsheetApp.openById(id);
var sheet = ss.getSheetByName("crypto"); // sheet name
var dataRange = sheet.getDataRange();
var formulas = dataRange.getFormulas();
var content = "";
var now = new Date();
var time = now.getTime();
var re = /.*[^a-z0-9]import(?:xml|data|feed|html|range)\(.*/gi;
var re2 = /((\?|&)(update=[0-9]*))/gi;
var re3 = /(",)/gi;
for (var row=0; row<formulas.length; row++) {
for (var col=0; col<formulas[0].length; col++) {
content = formulas[row][col];
if (content != "") {
var match = content.search(re);
if (match !== -1 ) {
// import function is used in this cell
var updatedContent = content.toString().replace(re2,"$2update=" + time);
if (updatedContent == content) {
// No querystring exists yet in url
updatedContent = content.toString().replace(re3,"?update=" + time + "$1");
}
// Update url in formula with querystring param
sheet.getRange(row+1, col+1).setFormula(updatedContent);
}
}
}
}
// Done refresh; release the lock.
lock.releaseLock();
// Show last updated time on sheet somewhere
sheet.getRange(7,2).setValue("Rates were last updated at " + now.toLocaleTimeString())
}
I set up the trigger.
Not sure what you trying to do and you explanation leaves a lot to be desired.
So this is a simple way to put your formulas into a sheet named "Destination".
function RefreshImports() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("crypto");
const rg = sh.getDataRange();
const formulas = rg.getFormulas();
sh.getRange(1,1,formulas.length,formulas[0].length).setFormulas(formulas);
}
I have an issue with this google sheet macro. Error message is: Exception: Range not found
I am trying to perform this script in order to copy recipient string (that can change according to data in P2 cell.
Can you help me?
Thanks
function macro()
{
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:L1000");
var data = dataRange.getValues();
for (i in data)
{
var rowData = data[i];
var recipient = rowData[0];
var parameter1 = rowData[1];
if (parameter1 == "OK")
{
sheet.getRange('P2').activate();
sheet.getRange(recipient).copyTo(sheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
}
}
}
Perhaps this is what you want:
function macro() {
var sh = SpreadsheetApp.getActiveSheet();
var rg = sh.getRange("A2:L1000");
var data = rg.getValues();
data.forEach((r,i)=>{
if(r[1] == "OK") {
sh.getRange(r[0]).copyTo(sh.getRange(i + 2, 16),SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
}
})
}
I have made something like this but it is only copy/paste first row (copy B2 to P2 works fine).
If I try to copy B3 to P2 it does not work..
function macro()
{
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:L1000");
var data = dataRange.getValues();
for (i in data)
{
var rowData = data[i];
var parameter1 = rowData[10];
if (parameter1 == "OK")
{
sheet.getRange('P2').activate();
sheet.getRange("B" +(i+2)).copyTo(sheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
}
}
}
I want to compare two dates and see what is similar but the if doesn't
work. I want to create a comparison with a cell value and a column of values.
function jobLogSchedule () {
var ss = SpreadsheetApp.getActiveSpreadsheet();/// Activate Sheet Application
var formSS = ss.getSheetByName("Form"); //Form Sheet
var dataBase = ss.getSheetByName("Data"); //Data Sheet
var viewSchedule = formSS.getRange("H2").getValue();
var firstDate = new Date(viewSchedule);
formSS.getRange("H2").setValue(firstDate);
formSS.getRange("H4").setValue(firstDate);
var lastRow = dataBase.getLastRow();
for(i=1; i<lastRow; i++){
var workingCell = dataBase.getRange(i,6,lastRow);
var dateDataBase = workingCell.getValue();
if (dateDataBase == viewSchedule) {
}
else {
}
}
}
try this:
function jobLogSchedule () {
var ss=SpreadsheetApp.getActive();
var fsh=ss.getSheetByName("Form");
var dsh=ss.getSheetByName("Data");
var lastRow=dsh.getLastRow();
var drg=dsh.getRange(1,6,lastRow,1);
var vA=drg.getValues();
var firstDate = new Date(fsh.getRange("H2").getValue());
fsh.getRange("H2").setValue(firstDate);
fsh.getRange("H4").setValue(firstDate);
for(i=0;i<vA.length;i++){
if (new Date(vA[i][0]).valueOf()==firstDate.valueOf()) {
//true
}
else {
//false
}
}
}
I have written a script to clean up and move data between 3 different sheets. A user first paste a data extract on to the "Extract" page, and then runs the script.
When a user paste the data into cell A1 on the "Extract" page, I would like a prompt box to ask the user if they would like to run the script; if Yes, run script, if No, don't run script and show message. How would I go about doing this?
This is what I have so far...everything after the first function works.
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Extract");
if(ss.s().getRange("A1").getValue() != ""){
var ui = SpreadsheetApp.getUi()
var response = ui.alert('Would you jbot to find new claims for you?', ui.ButtonSet.OK_CANCEL);
if (response == ui.Button.OK) {
jbot();
} else {
Logger.log('The user clicked "No" or the close button in the dialog\'s title bar.');
}
}
}
function jbot(){
movetobot();
deleteRows();
removeDupesInOtherSheets();
deleteCol();
cleanup();
movetoqueue();
message();
};
function movetobot() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Extract");
var ts = ss.getSheetByName("bot");
s.getRange("A1:BW").moveTo(ts.getRange("A1"));
}
function deleteRows() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("bot");
var r = s.getRange("BO:BO");
var v = r.getValues();
for(var i=v.length-1;i>=0;i--)
if(v[0,i]=='#POSTLESSEE' || v[0,i]=='#TDI CRC_OANKURA' || v[0,i]=='#Partpaymentoffer' || v[0,i]=='#TDI_CRC_DVANKURA' || v[0,i]=='#partpaymentdupe' )
s.deleteRow(i+1);
}
function removeDupesInOtherSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s1 = ss.getSheetByName("bot").getDataRange().getValues();
var s2 = ss.getSheetByName("Queue").getDataRange().getValues();
// iterate 'Queue' and check in 'bot' if duplicate values exist
var nS1 = [];
var s2Col1 = [];// data in column1 of Queue
for(var n in s2){
s2Col1.push(s2[n][0]);
}
for(var n in s1){ // iterate '180418970' and test col 1 vs col 1 in 'Queue'
var noDup1 = checkForDup(s1[n],s2Col1)
if(noDup1){nS1.push(noDup1)};// if not present in 'Queue' then keep
}
Logger.log(nS1);// view result
ss.getSheetByName("bot").getDataRange().clear();// clear and update sheets
ss.getSheetByName("bot").getRange(1,1,nS1.length,nS1[0].length).setValues(nS1);
}
function checkForDup(item,s){
Logger.log(s+' = '+item[0]+' ?')
if(s.indexOf(item[0])>-1){
return null;
}
return item;
}
function deleteCol() {
var spread = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spread.getSheetByName("bot");
var lastCol = sheet.getLastColumn();
var keep = [1,2,3,4,45,53,74, 75]; // array of column numbers to keep
for (var col=lastCol; col > 0; col--) {
if (keep.indexOf(col) == -1) {
// This isn't a keeper, delete it
sheet.deleteColumn(col);
}
}
}
function cleanup() {
var spread = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spread.getSheetByName("bot");
sheet.getRange("B1:B").moveTo(sheet.getRange("H1"));
sheet.deleteColumn(2)
sheet.deleteRow(1)
var cell = sheet.getRange("D:D");
cell.setNumberFormat("m/d/yy");
var cell = sheet.getRange("F:F");
cell.setNumberFormat("m/d/yy");
var cell = sheet.getRange("A:A");
cell.setHorizontalAlignment("center");
var cell = sheet.getRange("C:D");
cell.setHorizontalAlignment("center");
var cell = sheet.getRange("F:G");
cell.setHorizontalAlignment("center");
sheet.autoResizeColumn(2)
sheet.autoResizeColumn(5)
sheet.autoResizeColumn(7)
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spread.getSheetByName("bot");
var cell = sheet.getRange("BW1");
cell.setFormula("=COUNT(A:A)");
var spread = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spread.getSheetByName("bot");
var range = sheet.getRange("A1:G");
range.sort({column: 4, ascending: true})
}
function movetoqueue() {
var spread = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spread.getSheetByName("bot");
// skip row 1 (header) and beyond column G
var range = sheet.getRange(1,1,sheet.getLastRow()-1,7);
sheet = spread.getSheetByName("Queue");
var rows = sheet.getRange(1,1,sheet.getLastRow(),1).getValues();
// search for first blank row column 1
for( var i=0; i<rows.length; i++ ) {
if( rows[i][0] === "" ) {
var offset = sheet.getRange(1,1).offset(i,0);
range.copyTo(offset);
break;
}
}
}
function message() {
SpreadsheetApp.getActive().getSheetByName("Queue").activate();
var spread = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spread.getSheetByName("bot");
var range = sheet.getRange("bot!BW1:BW1");
var data = range.getValue();
Browser.msgBox(data + " new claims have been added to the queue. Thank you for using jBot!");
}
Your onEdit(e) will trigger the alert regardless of which cell is edited. You need to check the event range to limit it to cell A1 of Extract like this.
function onEdit(e) {
if( e.range.getSheet().getName() === "Extract" ) {
if( e.range.getA1Notation() === "A1" ) {
if( e.value !== "" ) {
var ui = SpreadsheetApp.getUi();
// Do the rest of your stuff here
}
}
}
}