Google Sheets JavaScript代码调用getMonth报is not a function错误
问题根因
- 只有Date类型的对象才拥有
getMonth()方法,你的日志语句仅执行一次,读取的对应单元格内容是合法的日期格式,所以可以正常运行。 - while循环每次执行都会修改
aportes-cont变量,向上遍历行的过程中,必然会命中某一行C列(第三列)的内容不是日期类型:可能是空值、纯数字、普通文本、格式异常的日期字符串,此时getValue()返回的结果不是Date对象,调用getMonth()就会抛出该错误。
修复方案
首先优化取值逻辑,先判断类型再调用方法,同时把重复的取值逻辑抽出来避免重复调用Sheet API,提高运行效率:
- 基础修复方案,新增类型校验
// 先获取对应工作表实例,避免每次循环重复查找工作表 const rendimentosSheet = ss.getSheetByName("Rendimentos"); while (true) { const currentCellValue = rendimentosSheet.getRange(aportes-cont, 3).getValue(); // 先判断是不是Date类型再调用getMonth if (Object.prototype.toString.call(currentCellValue) !== '[object Date]') { break; } if (currentCellValue.getMonth() !== numMes) { break; } // 原有循环内的业务逻辑写在这里 // ... // 循环变量更新 aportes-cont -= 1; }
- 兼容字符串格式的合法日期
如果部分单元格的日期被识别为字符串格式,可以新增转换逻辑:
空白内容、非日期内容转换后会生成无效Date,仍需做合法性判断
const currentCellValue = rendimentosSheet.getRange(aportes-cont, 3).getValue(); const currentDate = typeof currentCellValue === 'string' ? new Date(currentCellValue) : currentCellValue; if (!(currentDate instanceof Date) || isNaN(currentDate.getTime())) { break; } // 后续正常调用currentDate.getMonth()即可
- 大数量级遍历优化方案
如果需要遍历的行数较多,可以一次性读取整列内容,减少API调用次数,避免触发调用频率限制:
// 一次性读取C列所有有内容的行的值 const colCValues = rendimentosSheet.getRange(1, 3, rendimentosSheet.getLastRow(), 1).getValues(); // 直接在内存中遍历数组即可 while (aportes-cont >=1 && aportes-cont <= colCValues.length) { const currentCellValue = colCValues[aportes-cont - 1][0]; // 后续类型判断、月份判断逻辑和上述方案一致 }
内容的提问来源于stack exchange,提问作者Eduardo Caetano
相关产品推荐
相关产品推荐

