Google Sheets脚本开发需求:检测指定单元格背景色并自动发送邮件
Completed Google Sheets Script for Green Cell Email Notifications
Got it, let's fill in that missing logic to make your script work exactly as you need. Here's the full implementation with clear explanations:
function automatednotifications() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("Q4:Q20"); var bgColors = range.getBackgrounds(); for (var i in bgColors) { for (var j in bgColors[i]) { if (bgColors[i][j] === '#00ff00') { // Convert array index to actual sheet row number (Q4 is the first row in our range) var targetRow = 4 + parseInt(i); // Grab the email address from column E in the same row var recipientEmail = sheet.getRange(targetRow, 5).getValue(); // Optional: Validate email to avoid sending to empty/invalid addresses if (recipientEmail && typeof recipientEmail === 'string' && recipientEmail.includes('@')) { // Send the email - customize subject and body to fit your use case MailApp.sendEmail( recipientEmail, "Automated Spreadsheet Notification", `Hello,\n\nThis is a reminder that cell Q${targetRow} in your spreadsheet has been marked green.\n\nBest regards,\nYour Spreadsheet Bot` ); // Log successful sends for tracking/debugging Logger.log(`Sent email to: ${recipientEmail} (Row ${targetRow})`); } else { Logger.log(`Skipping invalid/empty email in row ${targetRow}`); } } } } }
Key Breakdown of the Added Logic:
- Row Number Calculation:
targetRow = 4 + parseInt(i)translates the array index (starting at 0 for Q4) to the actual row number in your sheet. - Email Retrieval:
sheet.getRange(targetRow, 5)targets column E (the 5th column) in the matching row to pull the recipient's email. - Email Validation: The extra check ensures we don't trigger errors by trying to send emails to empty cells or non-email formatted text.
- Customizable Email: Tweak the subject and body inside
MailApp.sendEmail()to include specific details relevant to your workflow.
Quick Tips:
- First run authorization: You'll need to grant the script permission to send emails when you run it for the first time (follow Google's prompts to complete this).
- Avoid duplicate emails: If you don't want to resend notifications every time the script runs, add a flag (like a checkbox in another column) to mark rows that have already been notified, then update the script to skip those rows.
内容的提问来源于stack exchange,提问作者Jumper040
相关产品推荐
相关产品推荐

