如何通过App Script在Google Sheets中添加按钮实现工作表跳转
Hey there, I've got you covered! Here's a straightforward, step-by-step way to add clickable navigation buttons between your Google Sheets tabs using Apps Script—perfect for moving between sheet1, sheet2, or any other tabs in your spreadsheet:
Step-by-Step Solution
1. Open the Apps Script Editor
- Fire up your Google Spreadsheet
- Head to the top menu: Extensions > Apps Script
- This opens a new script editor window with a default
Code.gsfile ready to edit
2. Paste the Navigation Functions
Replace the default code in Code.gs with this snippet:
// Universal function to jump to any sheet by name function jumpToSheet(sheetName) { const spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); const targetSheet = spreadsheet.getSheetByName(sheetName); // Check if the target sheet exists to avoid errors if (targetSheet) { targetSheet.activate(); } else { SpreadsheetApp.getUi().alert(`Oops! Couldn't find a sheet named "${sheetName}".`); } } // Shortcut functions for your specific sheets (easy to bind to buttons) function goToSheet1() { jumpToSheet("sheet1"); } function goToSheet2() { jumpToSheet("sheet2"); }
What this does:
jumpToSheet(sheetName)is a reusable core function that handles the actual tab switch and includes error checking (so you won't get silent failures if a sheet name is wrong)goToSheet1()andgoToSheet2()are simple wrapper functions that call the core function with your specific tab names—these are what you'll bind to your buttons
3. Create and Bind Buttons
- Go back to your spreadsheet
- Click Insert > Drawing to open the drawing tool
- Draw a button (e.g., a rectangle with text like "Go to Sheet2"), then click Save and Close
- Once the drawing is on your sheet, right-click it and select Assign script
- Type the name of the shortcut function you want (e.g.,
goToSheet2) and click OK - Repeat this to create a button for
goToSheet1(or any other sheets you need to navigate to)
4. Test It Out
Click your new buttons—they should instantly switch to the target sheet. If you mistype a sheet name in the code, you'll get a friendly alert letting you know something's off.
Pro Tip:
If you add more sheets later, just add a new wrapper function like:
function goToSheet3() { jumpToSheet("sheet3"); }
Then create a new button and bind it to this function.
内容的提问来源于stack exchange,提问作者Harshit Goyal




