Halen Lakes
Halen Lakes

Reputation: 35

Calling variables from another function

Trying to call a variable from a sub function, but "sheet" is not defined. Any suggestions on how to call it?

function getDate(){
var mnthYearDate = Utilities.formatDate(new Date,"EST","MMM yyyy");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mnthYearDate);
}

function getValue(){
getDate();
var target = sheet.getRange("A1").getValue();
}

Upvotes: 0

Views: 4349

Answers (3)

UEC OSH
UEC OSH

Reputation: 1

//---GLOBAL VARIABLES---
var mnthYearDate = Utilities.formatDate(new Date,"EST","MMM yyyy");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mnthYearDate);
var target;

//---RETRIEVE DATA---
function getValue(){
 target = sheet.getRange("A1").getValue();
}

//---GET DATA FROM OTHER FUNCTION---
function showInLog() {
gatValue();
Logger.log("Show target: "+target)
} 

Upvotes: 0

ReyAnthonyRenacia
ReyAnthonyRenacia

Reputation: 17651

The variable 'sheet' here is only known in your function getDate because you defined it there. To make it available to other functions, define it outside like what I did here.

var sheet;

function getDate(){
var mnthYearDate = Utilities.formatDate(new Date,"EST","MMM yyyy");
 sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(12345);
}

function getValue(){
    getDate();
    var target = sheet.getRange("A1").getValue();
    Logger.log(target);  
}

Upvotes: 1

Alex Dragnea
Alex Dragnea

Reputation: 174

Return it from your getValue() function and pass it as parameter to getValue(sheet) function.

Upvotes: 1

Related Questions