Search code examples
google-sheetsgoogle-apps-script

Getting an Undefined Value error in Google Script Function


The 'Ensure columnReference is a valid number' section of the Google Script code below evaluates to true, even though I'm calling the function with a value that is clearly a number. I'm new to javascript, so any insight would be most appreciated.

getColumnValuesWithRename(5);

function getColumnValuesWithRename(columnReference) {
  // Get the sheet by name
  let sheet = SpreadsheetApp.getActive().getSheetByName('References');
  
  // Check if the sheet exists
  if (!sheet) {
    Logger.log("Sheet 'References' not found.");
    return; // Exit the function
  }
  
  // Ensure columnReference is a valid number
  if (typeof columnReference !== 'number' || columnReference < 1) {
    Logger.log("Invalid columnReference value: " + columnReference);
    return; // Exit if columnReference is invalid
  }
  
  // Get the range and log the values
  const columnValues = sheet.getRange(1, columnReference, 1000, 1).getValues();
  Logger.log(columnValues); // Log the retrieved values
}


Solution

  • Replace

    getColumnValuesWithRename(5);
    

    by

    function main(){
      getColumnValuesWithRename(5);
    }
    

    Then, before clicking Run, ensure that the dropdown next to this button displays main. Otherwise, first select main, then click Run.