I am trying to use a Google script that retrieves 2 securities fields from GOOGLEFINANCE
and saves the output to a Google Sheet file. I need the script to also add the datetime to the first column of the Sheet.
I have created a basic Google Sheet with 3 columns:
Here is my function:
function myStocks() {
var sh = SpreadsheetApp.getActiveSpreadsheet();
sh.insertRowAfter(1);
sh.getRange("A2").setValue(new Date());
sh.getRange("C2").setFormula('=GOOGLEFINANCE("GOOG", "price")');
sh.getRange("D2").setFormula('=GOOGLEFINANCE("GOOG", "pe")');
}
Here is the output:
Date price pe
12/10/2017 22:44:31 1037.05 34.55
12/10/2017 22:43:24 1037.05 34.55
The output of columns C and D is correct. The output of column A is wrong. Every time I run the function, each new row is added ABOVE the last row:
12/10/2017 22:43:24
and it added that row first.12/10/2017 22:44:31
BUT it added that row ABOVE the last row in the sheet - I wanted it to add the new row BELOW the last row.Is there a way to auto fill the datetime downwards in a single column in GoogleSheets, using a script function?
How about the following modifications?
sh.insertRowAfter(1)
means that a row is inserted between 1 row and 2 row.
getLastRow()
.getRange("A2").setValue()
, getRange("C2").setFormula()
and getRange("D2").setFormula()
mean that the values are imported to "A2", "C2" and "D2", respectively.
setValues()
and setFormulas()
.The script which was reflected above points is as follows.
function myStocks() {
var sh = SpreadsheetApp.getActiveSheet();
var lastrow = sh.getLastRow() + 1; // This means a next row of last row.
sh.getRange(lastrow, 1).setValue(new Date());
var formulas = [['=GOOGLEFINANCE("GOOG", "price")', '=GOOGLEFINANCE("GOOG", "pe")']];
sh.getRange(lastrow, 3, 1, 2).setFormulas(formulas);
}
If I misunderstand your question, please tell me. I would like to modify.