简体   繁体   中英

Google Apps Script : How to use the copyTo function with a local string

I came across a problem with my code in Google Apps Script for Sheets. I want to get cell values from 3 different cells, concatenate them in a single string variable, and copy this string variable into a cell of my spredsheet, using the copyto function.

The problem is that Google Apps Script doesn't recognize copyto as a function, because it doesn't work with local string variables (it works fine with other function variables, such as getrange or else). Here is the part of my code that doesn't work:

 var prog = f1.getRange("A3"); var jour = f1.getRange("B1"); var heure = f1.getRange("B2"); var texte = prog+" - "+jour+" à "+heure; heure.copyTo(f2.getRange(1,2))

f1 is properly defined.

Where do I get this wrong? Is there a workaround for this?

Cheers

You say that f1 is properly defined and yet this example is complete and works as well.

function copy2test() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const sh2 = ss.getSheetByName('Sheet2');
  sh.getRange('A1').copyTo(sh2.getRange('A2'));
}

Your example is incomplete because I cannot copy it and put it into my code editor and reproduce the same result as you get. So you haven't met the requirement for reproducibility. In my own mind I simply look at your example and assume that you don't know what you're talking about when you say it's defined properly.

You placed it in a snippet. So just run it: It returns an error with the following:

{ "message": "Uncaught ReferenceError: f1 is not defined", "filename": "https://stacksnippets.net/js", "lineno": 12, "colno": 22 }

So you snippet result and I both agree. It's not defined properly.

For anyone coming across the same problem as I was, here is my solution. Because copyTo doesn't work with a string variable such as I had (or at least I don't know how to make it work), I used a different method which produces the same result.

Instead of heure.copyTo(f2.getRange(1,2)) I used f2.getRange(1,2).setValue([texte]); which does what I wanted and work with a string variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM