Google Sheets script getValue doesn't get value in UI (latest calculation) - javascript

I am writing a simple script that basically reads a value and send it to another sheet upon clicking a button. For testing purpose I wrote:
SpreadsheetApp.flush()
var sheet = localSheet.getSheetByName('Input');
var dateTimeRange = sheet.getRange(2,2);
var dateTimeValue = dateTimeRange.getDisplayValue();
localSheet.toast(readingValue, dataTypeValue)
In my spreadsheet setting, I set:
File->Spreadsheet settings->Calculation->On change and every minute
Cell in range 2,2 has
=now()
So, every minute, the value in cell 2,2 recalculates itself.
But when I run the script, the output value that I see is always the value of the last time I modified the sheet. As long as I don't interact with the sheet, the script is unable to read the new value. I tried adding flush(), doesn't work. Anyone have any idea?
Thank you.

I think that the reason of your issue is that the sheet is not updated. In your case, unfortunately, flush() cannot be used. In order to avoid this issue, how about the following workarounds? Please think of this as just one of several answers.
In your situation, when the sheet is edited, the value retrieving by getDisplayValue() is updated. In this answer, this is used.
Workaround 1:
In this workaround, the cell "B2" is overwritten by =NOW().
Modified script:
var localSheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = localSheet.getSheetByName('Input');
var dateTimeRange = sheet.getRange(2, 2);
var dateTimeValue = dateTimeRange.setFormula("=NOW()").getDisplayValue(); // Modified
localSheet.toast(dateTimeValue);
Workaround 2:
In this workaround, an empty cell is cleared. At sample script, the cell "B3" supposes the empty and this cell is not related to the main data. This cell is cleared. By this, let Spreadsheet know the sheet is edited.
Modified script:
var localSheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = localSheet.getSheetByName('Input');
var dateTimeRange = sheet.getRange(2, 2);
sheet.getRange("B3").clear(); // Added
var dateTimeValue = dateTimeRange.getDisplayValue();
localSheet.toast(dateTimeValue);
Value of "B2" on the sheet "Input" is updated even if the edited cell is different from the main sheet. So you can also use localSheet.getSheetByName("Sheet1").getRange("A1").clear() instead of sheet.getRange("B3").clear().
Note:
It seems that your script might not be the latest one.
Is localSheet var localSheet = SpreadsheetApp.getActiveSpreadsheet()?
readingValue and dataTypeValue are not declared. In this answer, dateTimeValue is used.
In above workarounds, the value is updated. But the retrieved value shows the value of 4 or 5 seconds faster every time. About this, I couldn't find to do the same value with "B2". I apologize for this situation.
If this was not useful for your situation, I apologize.

Related

Get random range google spreadsheet

I have managed with VBA and Excel to achieve my purposes, but I'd like to move to google spreadsheet for particular reasons.
I'm trying to replicate a code that works just fine in VBA.
It's simple, I have a sheet with a bank of questions in column A, and I'd like a macro that can select 1 random question and copy it to a second sheet.
I'm having trouble understanding how I can access a random cell, copy it and paste it to the second sheet. Some plain explanation would be appreciated since I have very little or non-existent knowledge of programming or javascript.
function test() {
var ss = SpreadsheetApp.openById("sheetID");
//Say I have 10 questions in the BANKSHEET, for instance
var rQuestion = Math.floor(Math.random()*10+1);
//What goes in A1? So that I can access the range randomly according to rQuestion value.
var inputRange = ss.getSheetByName("BANKSHEET").getRange("A1");
var inputValues = inputRange.getValues();
var outputRange = ss.getSheetByName("QUIZZ").getRange("A1").setValues(inputValues);
How about this modification? I think that there are several solutions for your situation. So please think of this as one of them.
Modification points :
Retrieve the number of cells at "A1:A" from sheet of "BANKSHEET".
Retrieve randomly one of the number.
Copy the cell value of the retrieved number to "A1" of "QUIZZ".
Modified script :
function test() {
var ss = SpreadsheetApp.openById("sheetID");
// Retrieve randomly a value from sheet of BANKSHEET
var sheet = ss.getSheetByName("BANKSHEET");
var src = sheet.getRange("A" + (1 + Math.floor(Math.random() * sheet.getLastRow())));
// Put the value to "A1" at sheet of QUIZZ
var dst = ss.getSheetByName("QUIZZ").getRange("A1");
src.copyTo(dst);
}
Note :
It supposes that there are values in only column A of "BANKSHEET".
This modified script randomly retrieves one value from column A of "BANKSHEET" every time.
If you don't want to use the value which has already been used, please modify the script for your situation.
Reference :
copyTo()
If I misunderstand your question, I'm sorry.

How to place notes from different source sheet in Google Spreadsheets

I've been struggling trying to find a method to place information from a cell (a range of cells) as comments in a different cell (range of cell) in a different sheet.
Something like this, if I have Apple in Cell A1 in Sheet1 I want Apple to be inserted as a comment in Cell F1 in Sheet 2.
I tried coming up with something like this.
//I'm still working on this I have not been able to make this work//
//Ideally this will put the phone numbers as comment's in the needed cases//
var ss = SpreadsheetApp.getActiveSpreadsheet();
var targetsheet = ss.getSheetByName("report");
var sourcesheet = ss.getSheetByName("Sheet1");
var nrange = sourcesheet.getRange(2, 3, sourcesheet.getLastRow(), 1)
var sourcenotes = [nrange.getValue()]
var notes = targetsheet.getRange(2, 6, sourcesheet.getLastRow(),1)
notes.setNotes(sourcenotes);
As you can read this is not working I've tried different methods but none is working so I come to you guys for help.
The function "setNotes" takes a 2 dimension array, the value should be like this setNotes([sourcenotes]). Check the documentation.
Also if you are going to set the note for just one cell, i would recomend to use the function setNote. Here is an example on that function.

getActiveCell always returns A1

I'm using the new Google Sheets API and any every time I try to get the active cell, it just returns cell A1 in the first sheet, no matter what. Here's my code:
var s = SpreadsheetApp.getActiveSpreadsheet();
var ss = s.getActiveSheet();
var result = ss.getActiveCell().getValue();
Seems like a Google bug...
This is currently working perfectly for me. If I highlight a cell in the active sheet and run your code, the value in the cell is logged for me.
You must use getActiveSheet() to specify the sheet. You cannot specify the sheet with getSheetByName()

Google Spreadsheet Determine lowest number in a row of cells

I'm new to this site for the main purpose that I plan to pursue a career in programming. I've landed my first job at an engineering company who is asking me to set up a system in which they can easily determine the time between a job being filed, and it's completion. We're using spreadsheet docs right now to accomplish certain pieces of this.
I'm looking to create a custom function in Google Docs that will allow me to traverse the array of values in row C and then compare it with a number that the function was called with, compare the number to the number in the array and give me which one is the smaller number. EDIT: The function will be called on another sheet called "parsed data" located in the same project file. It's purpose is to automatically file the order number of a current project (just for the sake of being organized) All the other functions I plan to implement will be based off of this order number being correct.
So far, I've gathered this much (I'm learning this on the fly because I still lack experience, so bear with me.)
{
/**created by Alexander Bickford for use at Double E Company
*sorts through a range of values to determine the lowest next value
*returns lowest determined value of next cell
*/
//List Of To Be Implemented Functions
// sheet.appendRow
function setValue(num)
{
var ss = SpreadsheetApp.getActiveSpreadsheet('parsed data');
var ss = ss.getSheets()[0];
var myRange = ss.getRange("C:C").getValues();
newValues = [];
for(i=1;i<=myRange;i++) //Loop to traverse the C range and find the lowest value.
{
if(num<=range[3][i])
{
}
else
num = range[3][i];
}
return num;
}
}
when I call the function in the spreadsheet, I'm getting an error passed that says:
error: ReferenceError: "SPREADSHEET_ID_GOES_HERE" is not defined. (line 8, file "Code")
Google predefines some functions at the top that look like this:
/**
* Retrieves all the rows in the active spreadsheet that contain data and logs the
* values for each row.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
function readRows() { <---Line 8 in the file
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
Logger.log(row);
}
};
* Adds a custom menu to the active spreadsheet, containing a single menu item
* for invoking the readRows() function specified above.
* The onOpen() function, when defined, is automatically invoked whenever the
* spreadsheet is opened.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Read Data",
functionName : "readRows"
}];
sheet.addMenu("Script Center Menu", entries);
};
End Code I don't need */
I assume it has something to do with the earlier lines (I pointed out line 8). Any thoughts?
Below code is working fine for me.
var ss = SpreadsheetApp.getActiveSheet();
var myRange = ss.getRange("C:C").getValues();
newValues = [];
for(i=1;i<=myRange.length;i++)
{
Logger.log(myRange[i]);
}
Looking at your code, it seems like you have a few problems.
You seem to be mixing up "sheets" with "spreadsheet", and your redundant declaration of "ss" as a variable is bound to cause you some problems.
You seem to be passing in arguments to the incorrect methods. I had this same problem when working with the Google App script earlier. It took a lot of poking around Google's Documentation (which you should really take a look at: https://developers.google.com/apps-script/). You seem to be making the same mistake I did, coding by analogy. looking at Google's sample code and trying to replicate is bound to bump you into some trouble.
Some useful advice:
The most confusing thing to wrap your head around is the structure: spreadsheet>>sheet>>range, you have to explicitely deal with the one's on top before moving to the one's on the bottom.
Remove the 'parsed data' argument from getActiveSpreadsheet(), it should be blank. What you want to use is "getSheetByName("parsed data")" and pass that into a sheet variable.
In your for loop, you also need to use the ".length" method, or use the ".getLastRow()" method with a sheet object to find the last row in your sheet.
Your code might look something like this:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("parsed data");
var endRowNumber = sheet1.getLastRow();
//insert rest of code

Get Column Range Based on Active Cell

I am trying to copy some data to the clipboard, from a Google Spreadsheet, by running a script - I want to minimize user error, this is the reason for the script. Depending on the active cell, I want the script to select 57 rows below the active cell and copy the values to the clipboard, in order to be pasted somewhere else. I cannot figure out how to do this. Here is the code that I have at the moment.
function copyDailySubsidy() {
var ss = SpreadsheetApp.getActive();
var rangeRow = ss.getActiveCell().getRow();
var rangeCol = ss.getActiveCell().getColumn();
var range = ss.getRange(rangeRow, rangeCol, 23).getValues();
//var values = ss.getRange().getValues();
Logger.log(rangeCol);
}
I can't seem to figure out how to copy the values of the range, or even select the appropriate range. Any help that you can afford would be greatly appreciated!
This is not achievable in Google Apps Script. Your script is running on a remote server, and has no access to a user's clipboard.

Categories

Resources