Skip to content

Instantly share code, notes, and snippets.

@carthegian
Last active December 8, 2020 04:24
Show Gist options
  • Save carthegian/8ab0dedbc0d477b9009c5117a57c710b to your computer and use it in GitHub Desktop.
Save carthegian/8ab0dedbc0d477b9009c5117a57c710b to your computer and use it in GitHub Desktop.
Google Apps Script example to jump to specific sheet and cell based on some conditions upon opening a Google Sheets document.
function onOpen(e) {
// Get current month
var now = new Date();
var currentMonthSheet = now.getFullYear() + "年" + (now.getMonth() + 1) + "月";
// Jump to current month's sheet
var sheetToSet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(currentMonthSheet);
SpreadsheetApp.setActiveSheet(sheetToSet);
// Jump to current date's cell by iterating dates in column range
var dateRange = sheetToSet.getRange('A:A');
var currentMonthDate = (now.getMonth() + 1) + "/" + now.getDate();
forEachRangeCell(dateRange, (cell) => {
if (cell.getValue() instanceof Date) {
Logger.log("vey");
} else {
Logger.log("oy");
}
if (!cell.isBlank() && cell.getValue() instanceof Date) {
var cellMonthDate = (cell.getValue().getMonth() + 1) + "/" + cell.getValue().getDate();
if (cellMonthDate == currentMonthDate) {
// Set active cursor to today's date
SpreadsheetApp.getActiveSheet().getRange(cell.getA1Notation()).activate();
}
}
})
}
// Helper `forEachRangeCell` function
// Returns each cell from range
function forEachRangeCell(range, f) {
const numRows = range.getNumRows();
const numCols = range.getNumColumns();
for (let i = 1; i <= numCols; i++) {
for (let j = 1; j <= numRows; j++) {
const cell = range.getCell(j, i)
f(cell)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment