SetValue not working to set the value of a cell - google-apps-script

I am writing a very simple macro in Google Sheets to get the month value and write it in a cell on the sheet. But for some reason the month value is not getting written to the cell.
function Macro1() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet1'), true);
var today = new Date;
var prevMonth = Utilities.formatDate(today, 'GMT+1', 'MMMM yy');
var cell = spreadsheet.getRange('G12');
cell.setValue = prevMonth;
Logger.log(prevMonth);
Logger.log(cell.getValue());
};
I can see the value of prevMonth in the log. It is correct but no value is getting written in the actual cell and hence, the last line also returns blank.
And yes, I have read-write access on the sheet.

setValue is a function, so you need to pass parameter to it.
function Macro1() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet1'), true);
var today = new Date();
var prevMonth = Utilities.formatDate(today, 'GMT+1', 'MMMM yy');
var cell = spreadsheet.getRange('G12');
cell.setValue(prevMonth);
Logger.log(prevMonth);
Logger.log(cell.getValue());
}
cell.setValue(prevMonth);

Related

Google Sheets - Automatically record values from Sheet 1 to Sheet 2 on a specific day and time of the week

I have a form that gathers the amount hours each member of a team has dedicated to a specific task on one sheet, and it changes every week. These values are deleted every Monday I need to create a record of these values on a new sheet every Sunday, to keep a record. I have a code that would take the values from a cell and paste it in the first available row in that same sheet, But I need it to paste it in a different sheet.
The code I have is this:
function recordValue() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var date = new Date();
var value =sheet.getRange("K6").getValue();
sheet.appendRow([date, value]);
}
Any help would be appreciated.Thanks in advance!
Try
function recordValue() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var date = new Date();
var value =sheet.getRange("K6").getValue();
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("OtherSheetName").appendRow([date, value]);
}
or
function recordValue() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var values = [new Date()]
sheet.getRange("K6:K10").getValues().forEach(v => values.push(v[0]));
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("OtherSheetName").appendRow(values);
}
or
function recordValue() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("OtherSheetName");
var range = "K6:K10";
dest.getRange(range).setValues(sheet.getRange(range).getValues());
}

Running App Script with output on a different Sheet

I have found a script that pulls data from a cell and adds a row to the bottom of the Google Sheet, but I want to be able to have the output on a separate sheet called "Data". Here is the script:
function recordValue() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Channels");
var date = new Date();
var value =sheet.getRange("B9").getValue();
sheet.appendRow([date,value])
}
I know I need to change the sheet.appendRow but I don't know what I need to get it to another sheet, say in cell A2.
You must declare the second sheet.
function recordValue() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Channels");
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var date = new Date();
var value = sheet.getRange("B9").getValue();
dataSheet.appendRow([date,value])
}
See:
The Modern JavaScript Tutorial
Outputting on a different sheet
function recordValue() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Channels");
const dsh = ss.getSheetByName("Data")
dsh.getRange(dsh.getLastRow() + 1, 1, 1,2),setValues([[new Date(),sh.getRange("B9").getValue()]]);
}
setValues

TypeError: Cannot call method "insertChart" of undefined

I am trying to insert an embedded chart to a google sheet for data analytics. However, when I run the code it throws the following error:
TypeError: Cannot call method "insertChart" of undefined (line 87, file "Code").
This is my function for creating the chart:
function createBarGraph(activeSheet) {
var chart = activeSheet.insertChart()
chart.newChart()
.setChartType(Charts.ChartType.COLUMN)
.setOption('Chart Title', 'Service reviews')
.setPosition(5,5,0,0)
.build();
}
activeSheet is a variable held in another function that creates a new sheet for each month. The embedded chart needs to be created in that sheet to correctly reflect the data for each month. I note I haven't added a SpreadsheetApp.getActiveSpreadSheet, this is based on the assumption that since this is being called in the other function it is not needed here.
Where am I going wrong?
This is the code for the function calling this one.
function checkSheetName() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = formatDate(); // load the current 'Month-Year'
var activeSheet;
try {
activeSheet = ss.getSheetByName(sheetName);
ss.setActiveSheet(activeSheet); // try to set 'sheetName' as active sheet
} catch (e) { // if returns error,
activeSheet = createNewMonthSheet(); // creates a new sheet
}
return activeSheet;
}
function createNewMonthSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = formatDate(); // load the current 'Month-Year'
ss.insertSheet(sheetName, 2); // creates a new sheet on the left side, after 2 existing sheets
var newSheet = ss.getSheetByName(sheetName);
var columns = ['Comment','Compliment','Complaint']; // Array of review type.
var rows = ['Befriending','Finance','Fund Raising','Home Help','I & A','Mgmt
Services','Toes Nails','Trading']; // Array of services provided.
for(r=0; r<rows.length; r++){
newSheet.getRange(r+2, 1).setValue(rows[r]);} // iterates through
the length of row array, gets the range and sets the value.
for(c=0; c<columns.length; c++)
{
newSheet.getRange(1, c+2).setValue(columns[c]); // iterates through length of column array, gets the range and sets the value.
}
return ss.getSheetByName(sheetName); //returns active spreadsheet with date formated M & YYYY.
}
function formatDate() {
var monthNames =
["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var monthNumber = Utilities.formatDate(new Date(), 'GMT+12:00', "M");
var yearNumber = Utilities.formatDate(new Date(), 'GMT+12:00', "yyyy");
return monthNames[monthNumber-1]+'-'+yearNumber;
}
According to the documentation for insertChart(), you have to call it after you build it, you're calling insertChart() before the chart is built.
Try writing the function like this:
function createBarGraph(activeSheet) {
var chart = chart.newChart()
.setChartType(Charts.ChartType.COLUMN)
.setOption('Chart Title', 'Service reviews')
.setPosition(5,5,0,0)
.build();
activeSheet.insertChart()
}

Google Sheets Script hideSheet() , Sheet not hidden

Trying to duplicate a hidden template, causing it to be revealed, but then have it be hidden again after the duplication.
The hideSheet() function is not working. Any ideas?
function googleQuiz(){
//Duplicate Sheet
var ss =SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.setActiveSheet(ss.getSheetByName('QuizFormTPlate'));
ss.duplicateActiveSheet();
sheet.hideSheet();
//Rename sheet
var dSheet = ss.setActiveSheet(ss.getSheetByName('Copy of QuizFormTPlate'));
var date = new Date();
var tz = ss.getSpreadsheetTimeZone();
var marksDate = Utilities.formatDate(date, tz, 'dd-MMM');
var name = "G-Quiz ".concat(marksDate);
dSheet.setName(name);
//Insert Cell
var cell = dSheet.getRange("C2");
cell.setValue('Formative');
}
Actually it's "showSheet()"
This works for me:
var spreadsheet = SpreadsheetApp.getActive();
var sheetTemplate = spreadsheet.getSheetByName('Template');
sheetTemplate.showSheet();
//do something...
sheetTemplate.hideSheet();
Since hideSheet() takes no effect if the sheet is already hidden:
https://developers.google.com/apps-script/reference/spreadsheet/sheet#hidesheet
Showing the hidden sheet first should do the trick:
https://developers.google.com/apps-script/reference/spreadsheet/sheet#showsheet
Here is alternative solution that will that copy the sheet and keep it hidden
function googleQuiz(){
//Duplicate Sheet
var ss =SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('QuizFormTPlate');
var dSheet = sheet.copyTo(SpreadsheetApp.openById(ss.getId()))
dSheet.showSheet()
//Rename sheet
var date = new Date();
var tz = ss.getSpreadsheetTimeZone();
var marksDate = Utilities.formatDate(date, tz, 'dd-MMM');
var name = "G-Quiz ".concat(marksDate);
dSheet.setName(name);
//Insert Cell
var cell = dSheet.getRange("C2");
cell.setValue('Formative');
}
Basically, instead of your using duplicateActiveSheet() function of a spreadsheet object. You can use copyTo() function of a sheet object and provide it with the current spreadsheet.
sheet.copyTo(SpreadsheetApp.openById(ss.getId())).
And directly pass the new sheet object to var dSheet to make it visible and rename it.
It appears the issue is caused by using setActiveSpreadSheet on a hidden sheet, if you call ss.getSheetByName('QuizFormTPlate').showSheet(); prior to the ss.setActiveSpreadsheet(ss.getSheetByName('QuizFormTPlate')); the call to hideSheet() will work fine afterwards. Posting this here so anyone else running into this problem can just add the .showSheet() instead of reworking their whole code.

Missing ; error in first attempt at script

I am writing an OnOpen script for a spreadsheet.
I have a number in cell B1 and a date in C1
When the spreadsheet is opened, I want to check that the date on the sheet is today's and if not, it will change the sheet's date and also reset the number in B1 to 0
I am getting the error Missing ; before statement. (line 8, file "Code")
(Which is the If Statement)
function OnOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Create Ticket");
var TicketCount = sheet.getRange("B1").getvalue();
var TicketDate = sheet.getRange("C1").getvalue();
var Today = date().setNumberFormat("dd/mm/yyyy");
If not TicketDate = Today {
sheet.getRange("C1").setValue(new Date()).setNumberFormat("dd/mm/yyyy");
sheet.getRange("B1").setvalue(0);
}
}
This is all new to me so my apologies if this is basic. The only coding I ever did was simple VBA, so I don't even know what == means.
You can try this function
function onOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Create Ticket");
var TicketCount = sheet.getRange('B1').getValue();
var TicketDate = Utilities.formatDate(new Date(sheet.getRange("C1").getValue()),Session.getScriptTimeZone(),"dd/MM/yyyy");
var Today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(),"dd/MM/yyyy");
if(TicketDate != Today) {
sheet.getRange("C1").setValue(Utilities.formatDate(new Date(), Session.getScriptTimeZone(),"dd/MM/yyyy"));
sheet.getRange("B1").setValue(0);
}
}
Be carefull because in your code there is some typo error.
setvalue => setValue
getvalue => getValue
This will generate error.
To format date you can use Utilities.formatDate()
Stéphane