getRange函数调用报错:TypeError无法调用null类的getRange方法
Hey Adam, sorry you ran into this frustrating error—let's break down what's happening and fix it step by step.
错误根源
The error on line 7 means that SpreadsheetApp.getActiveSpreadsheet().getSheetByName(skoroszyt) is returning null. That happens when the script can't find a sheet with the name stored in your skoroszyt variable. You can't call getRange() on a null value, hence the TypeError.
常见原因 & 修复步骤
Sheet name mismatch: Google Apps Script is case-sensitive when looking up sheet names. Double-check if the sheet name you're passing (like
'stand'in your test call) exactly matches the sheet's name in your spreadsheet—no extra spaces, wrong capitalization, or typos. For example, if the sheet is named "Stand" (capital S),getSheetByName('stand')will fail.Add a safety check: To avoid this error and get clearer feedback, add a check for the sheet before trying to access its range. This will help you debug faster if the sheet is missing.
修改后的代码示例
Here's your code with the safety check added, plus a fix for another hidden issue:
function getPriceStand(poziom, pion, addr, sheet) { var adres = addr.toString(); var skoroszyt = sheet; var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // 先检查目标工作表是否存在 var targetSheet = activeSpreadsheet.getSheetByName(skoroszyt); if (!targetSheet) { throw new Error(`工作表 "${skoroszyt}" 不存在,请检查名称拼写!`); } var c = targetSheet.getRange(adres); var rowOffset = 1; var columnOffset = 1; var ileKolumn = 0; var ileWierszy = 0; // 恢复第一个while循环的逻辑(原来的条件和闭合括号被注释掉了) while(c.offset(0, ileKolumn).getValue() != ''){ ileKolumn++; Logger.log('cena standu kolumna'+ileKolumn); } while(c.offset(ileWierszy, 0).getValue() != ''){ ileWierszy++; } for (var i = 0; i < ileKolumn; i++ ){ if (poziom >= c.offset(0, columnOffset).getValue()){ columnOffset++; } } for (var i = 0; i < ileKolumn; i++ ){ if (pion >= c.offset(rowOffset, 0).getValue()){ rowOffset++; } } return c.offset(rowOffset-1, columnOffset-1).getValue(); }
额外提示
I noticed your first while loop's condition and closing bracket were commented out—this would have broken your column-counting logic, making ileKolumn only increment once. I've restored that part so the script can correctly count non-empty columns as intended.
内容的提问来源于stack exchange,提问作者Adam Serocki

