google-apps-script - How do i deal with getRange() Class error in Google Script?
问题描述
I am working in Google Script and trying to get values from following column. Any idea of why i am getting error "TypeError: Cannot read property 'getRange' of undefined", and how to deal with it? Here is following code:
const ss = SpreadsheetApp.openById(ssId);
const workspaceSheet = ss.getSheetByName("Workspaces")
function getWorkspaces (workspaceSheet) {
WORKSPACE_ID = workspaceSheet.getRange(1,1,100).getValues()
return WORKSPACE_ID
}
解决方案
When getWorkspaces
is run as the custom function, an error occurs at const ss = SpreadsheetApp.openById(ssId);
. From this situation, I thought that you might have directly run the function of getWorkspaces
with the script editor. If my understanding is correct, when getWorkspaces
is run with the script editor, workspaceSheet
of getWorkspaces(workspaceSheet)
is undefined
. By this, such error occurs. If you want to remove your issue, how about the following modification?
Modified script 1:
In this modification, workspaceSheet
of getWorkspaces(workspaceSheet)
is removed. By this, workspaceSheet
of const workspaceSheet = ss.getSheetByName("Workspaces");
is used.
const ssId = "###"; // Please set the Spreadsheet ID.
const ss = SpreadsheetApp.openById(ssId);
const workspaceSheet = ss.getSheetByName("Workspaces");
function getWorkspaces() {
WORKSPACE_ID = workspaceSheet.getRange(1, 1, 100).getValues();
return WORKSPACE_ID;
}
Modified script 2:
In this modification, ss
and workspaceSheet
are declared in the function.
function getWorkspaces() {
const ssId = "###"; // Please set the Spreadsheet ID.
const ss = SpreadsheetApp.openById(ssId);
const workspaceSheet = ss.getSheetByName("Workspaces");
WORKSPACE_ID = workspaceSheet.getRange(1, 1, 100).getValues();
return WORKSPACE_ID;
}
Modified script 3:
When you want to call getWorkspaces
from other function, how about the following modified script?
function getWorkspaces(workspaceSheet) {
WORKSPACE_ID = workspaceSheet.getRange(1, 1, 100).getValues();
return WORKSPACE_ID;
}
// In this case, please run this function. By this, `getWorkspaces` is run.
function sample() {
const ssId = "###"; // Please set the Spreadsheet ID.
const ss = SpreadsheetApp.openById(ssId);
const workspaceSheet = ss.getSheetByName("Workspaces");
const WORKSPACE_ID = getWorkspaces(workspaceSheet);
console.log(WORKSPACE_ID);
}
推荐阅读
- android - 需要解析动态HashMap
>> - json - 将对象数组表示为 protobuf 消息
- java - 无法使用 jgit api 克隆 Github repo 获取无效远程异常
- nginx - 反向代理不会在子域上加载 /_Nuxt/ 目录
- javascript - ERR_BLOCKED_BY_RESPONSE.NotSameOrigin CORS 策略 JavaScript
- flutter - Flutter:直接分享火力 (PDF)
- azure - Azure 应用服务:未找到应用程序依赖项清单 (Microsoft.AspNetCore.AzureAppServices.HostingStartup.deps.json) 中指定的程序集
- javascript - 使用 Javascript 设置 SVG 填充
- loops - 有没有办法让嵌入式 Spotify 链接自动播放并重复离开?
- scheduled-tasks - 计划的报告和活动不起作用 - SuiteCRM