getValues/setValues not putting anything in target cell - google-apps-script

I am trying to build a data logging workflow using Sheets. I've got a getValue/setValue pair that looks great, but isn't writing to the target cell, and I can't understand why. Here's the code I'm using:
function TESTcopy() {
var srcSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSht = srcSpreadsheet.getSheets()[0];
var tgtSpreadsheet = SpreadsheetApp.openById('1xjjXG-tK3DIkgJTQbkR6XFhOEP5nhaNfqqXiFyMu0AY');
var tgtSht = tgtSpreadsheet.getSheets()[0];
var data = srcSht.getRange(4,2,20,18).getValues();
tgtSht.getRange(345,5,20,18).setValues(data);
}
I've gone over the entire script letter-by-letter, and have Googled and searched on SO for several hours. I know that there's a simple explanation, but I just can't see it.
Does anybody else have any ideas? Thanks in advance!

Related

DriveApp.getFileById() throwing a server error [duplicate]

This question already has answers here:
DriveApp Error: "We're sorry, a server error occurred. Please wait a bit and try again."
(4 answers)
Closed 1 year ago.
I have a script that I am using to export a google sheet to a PDF. It has been working no problem up until now. I deployed it as a Web App so that it could be used by anyone. Since I deployed it, it has not worked. I tried archiving the Web App and that did not help.
The issue seems to be with the DriveApp.getFileById() function. I inserted numerous console.log() functions along the way of my code to try to narrow down where it actually fails and why. The execution log shows that the error is happening at the same spot that I derived, but the console.log() functions did not help me figure out why. The error I receive is:
Exception: We're sorry, a server error occurred. Please wait a bit and try again.
I have tried researching this for quite some time now, and have tried suggestions that I found. I double checked all my variables and code syntax. I also know that the pdfid is being pulled correctly, as verified by logging it. I have not altered this part of the code, or any part that it depends on, at all since it has been working. I believe the Web App deployment is the issue, but I'm not sure why or how I could fix it. It could also be something else I'm missing, as it still does not work even after archiving the Web App.
Here is the code, the last line shown is where it fails:
function exportLog(type) {
console.log('Starting Export');
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var realExp = sheet.getSheetByName('exportThis');
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
//console.log('Spreadsheet created');
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var sheet = realExp.copyTo(newSpreadsheet);
//console.log('Copied');
SpreadsheetApp.getActiveSpreadsheet().toast('Beginning export...','Loading...',-1);
//console.log('using new sheet');
newSpreadsheet.getSheetByName('Copy of exportThis').showSheet();
//console.log('successfully used new sheet');
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();
//console.log('deleted');
var pdfid = newSpreadsheet.getId();
console.log(pdfid); // Correctly logs ID
var pdf = DriveApp.getFileById(pdfid);
function exportLog(type) {
const ss1 = SpreadsheetApp.getActive();//this returns the active spreadsheet
const xsh = ss1.getSheetByName('exportThis');
const ss2 = SpreadsheetApp.create("Spreadsheet to export");
const nsh = xsh.copyTo(ss2);
nsh.showSheet();//you can't really show the sheet because ss2 is not the active spreadsheet
ss2.getSheetByName('Sheet1').activate();//again you can't activate this sheet because ss2 is not the active spreadsheet
ss2.deleteActiveSheet();//This is not the active spreadsheet
const pdfid = ss2.getId();//I don't know why you call this a pdf it's a spreadsheet
const pdf = DriveApp.getFileById(pdfid); //again ss2 is a newly created spreadsheet
}
//Input parameter is never used
You should get in the habit of referring to the documentation while you write your code and pay special attention to the types that are returned by methods.

Is it even possible to copy data from one sheet to another with a script? ImportRange style?

Ive searched for 2 days, can't seem to find the answer or anyone that is even doing something kinda like this. I am trying to bring my employees sheets over to my "Master sheet" with a script. I need to keep the formatting and the notes in the cells.
Best I can find is I can open their spread sheets and copy it to my master, but for 8 employees this will be a pain if I need to do this multiple times a day. I would like to just build a function that I can run my script from the "master sheet" and have it write over the last data in their tab. But I want to be able to do this from within my master sheet. I am the owner of all the sheets but this is becoming a pain.
function copyCell() {
var os = SpreadsheetApp.openById('1n4iFXGuC7yG1XC-UIbuT9VrQ7rJWngPkDCv0vsvDed4');
var sheets = os.getSheets();
var existingNote;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var jobnumber = sheets.getRange("C2:C").getValues();
for (var i = 0; i < jobnumber.length; i++)
if (jobnumber[i][0] == sheets){
existingNote = sheets.getRange("C" + (i+2)).getNote();
sheets.getRange("C" + (i+2)).ss.setNote(existingNote);
}
};
Someone please let me know if it is possible and maybe reference a script I can see to be able to modify to fit my needs. Thanks for any help.
This is a possible solution for copying the notes associated with a range of cells. And pasting them onto a similar-sized range of cells.
To copy the notes you can use getNotes(). Docs here.
To paste the notes you can use setNotes(). Docs here.
Ths sample code in this documentation is pretty good if you need to add it into your script.
If you have a script you'd like to share am happy to help you make it work properly.
Edit
Something like this:
function transferNotes() {
// Get notes (not comments) from the source spreadsheet
var sourceSpreadheet = SpreadsheetApp.openById('ID_of_source_spreadsheet');
var sourceTab = sourceSpreadheet.getSheetByName('Name_source_tab');
var sourceRange = sourceTab.getRange('Source_range_address'); // e.g. "A:D"
var notes = sourceRange.getNotes();
// Post the notes to the target spreadsheet
var targetSpreadheet = SpreadsheetApp.openById('ID_of_target_spreadsheet');
var targetTab = targetSpreadheet.getSheetByName('Name_target_tab');
var targetRange = targetTab.getRange('Target_range_address'); // Should be the same dimensions as sourceRange
targetRange.setNotes(notes);
}

Copy table from one Google Docs file to another

Can anyone provide an example script showing how to copy a table from one Google Doc to another? I have tried multiple variations of "Table.insertTable" and "Table.appendTable", but I cannot get it right.
Solved it! I realized that I had to use the "Copy()" function to get a proper handle to the table. So, the final code looks something like this:
var sourcedoc = DocumentApp.openById(sourceid);
var sourcebody = sourcedoc.getBody();
var tables = sourcebody.getTables();
var table = tables[0].copy();
var destdoc = DocumentApp.openById(destid);
var destbody = destdoc.getBody();
var x = destbody.appendTable(table)

Google App Script- Docs/images in tables?

I have searched and searched for the syntax to place an image in a table cell with Google App Script in a Google Doc (not Sheet). This is what I am trying to do:
var resp01 = UrlFetchApp.fetch("http://www.example.com/image01.png");
var resp02 = UrlFetchApp.fetch("http://www.example.com/image02.png");
var cells = [[resp01.getBlob()], [resp02.getBlob()]];
copyBody.appendTable(cells);
This yields simply the word "Blob" in my table.
I can do this all day long with a paragraph:
Body.getChild(x).asParagraph().appendInlineImage(resp01.getBlob());
But for some reason, the "parallel" syntax in a table won't cut it? Does anyone know what I am missing?
Thank You
You need to call TableCell's insertImage() method and provide the child index and the blob source of the image as parameters.
Hope that helps!
Thank You for the input KRR.
I was able to get my project where I wanted it to go, part of which involved inserting images in a table in a Google Doc using Google App Script. After much reading, I settled on the syntax that follows. I hope this helps anyone else trying to learn:
function createDoc() {
var doc = DocumentApp.create('Sample Document');
var body = doc.getBody();
var resp01 = UrlFetchApp.fetch("http://www.cincinnati-oh.gov/cityofcincinnati/assets/Image/Logos/cityofcincinnati.png");
var rowsData = [["City of Cincinnati IMAGE:", ""]];
table = body.insertTable(1, rowsData);
var row = table.getRow(0);
var cell = row.getCell(1);
cell.appendImage(resp01.getBlob());
}

error - "Method Range.getValue is heavily used by the script"

I posted this question previously but did not tag it properly (and hence why I likely did not get an answer) so I thought I would give it another shot as I haven't been able to find the answer in the meantime.
The below script is giving me the message in the title. I have another function which is using the same getValue method but it is running fine. What can I change in my script to avoid this issue?
function trashOldFiles() {
var ffile = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CtrlSht").getRange("B3:B3").getValue();
var files = DriveApp.getFilesByName(ffile);
while (files.hasNext()) {
var file = files.next();
var latestfile = DriveApp.getFileById(listLatestFile());
if(file.getId() ==! latestfile){
file.setTrashed(true);
}
}
};
Is it an error or an execution hint(the light bulb in the menu)?
are you using that method on other part of your code? probably in listLatestFile()?
I got the same execution hint by calling getRange().getValue() in listLatestFile() (using a loop)
and the hint always mentioned that the problem was when calling
var ffile = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CtrlSht").getRange("B3:B3").getValue();
in the function trashOldFiles() even when the actual problem was in other function.
Check if you are calling it in other place in your code, probably inside a loop.
OK, so Gerardo's comment about loops started to get me thinking again. I checked some other posts about how to re-use a variable and decided to put the listLatestFile() value in my spreadsheet -
var id = result[0][1];
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CtrlSht").getRange("B5:B5").setValue(id);
//Logger.log(id);
return id;
and then retrieved the latest file ID from the spreadsheet to use as a comparison value for the trashOldFiles() function which worked a treat.
function trashOldFiles() {
var tfile = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CtrlSht").getRange("B3:B3").getValue();
var tfiles = DriveApp.getFilesByName(tfile);
var lfile = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CtrlSht").getRange("B5:B5").getValue();
while (tfiles.hasNext()) {
var tfile = tfiles.next();
if(tfile.getId() !== lfile){
tfile.setTrashed(true);
}
}
};
Not sure if that approach was best practice but it did work for me. If anyone has suggestions for achieving this in a more elegant way, I'm all ears.