I have a script that copies a table from a Google Sheet into an e-mail which is being sent automatically every day (there is a trigger). The table always starts in the cell K1 and it always has 6 columns, however, the number of rows is always different. I want to account for it and make it sorta dynamic. Here is the google script:
function CheckShare() {
// Fetch the monthly sales
var Range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share").getRange("I2");
var result = Range.getValue();
var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share").getRange("K1:P10").getValues();
var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;'
var htmltable = '<table ' + TABLEFORMAT +' ">';
for (row = 0; row<data.length; row++){
htmltable += '<tr>';
for (col = 0 ;col<data[row].length; col++){
if (data[row][col] === "" || 0) {htmltable += '<td>' + 'None' + '</td>';}
else
if (row === 0) {
htmltable += '<th>' + data[row][col] + '</th>';
}
else {htmltable += '<td>' + data[row][col] + '</td>';}
}
htmltable += '</tr>';
}
htmltable += '</table>';
Logger.log(data);
Logger.log(htmltable);
// Check totals sales
if (result >0){
// Fetch the email address
var emailAddress = "[email protected]";
// Send Alert Email.
var message = 'There are ' + result +' deviating metrics: https://docs.google.com/spreadsheets/d/1AQEBTt919TIu92Gb9TeZRD3KpSm3L_WCHgTOmw/edit#gid=1525731698'
+ ' See the dashboard here: <link> ';
var subject = 'Transaction Monitoring Alert: AA Share';
MailApp.sendEmail(emailAddress, subject, message, {htmlBody:htmltable});
}
}
The current e-mail output looks likes this:
I want it to exclude rows with values "None" (empty cells)
Use .getDataRange()
rather than .getRange("K1:P10")
, this should only return rows with actual data.
var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share").getDataRange().getValues();
Edit:
Since you can't use .getDataRange()
to achieve your goal. Try using .getLastRow()
instead then passing that to your getRange()
. The below code should get the range of K1:Px (x = however many rows of data you have).
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share");
var lastRow = dataSheet.getLastRow();
var data = dataSheet.getRange(1, 11, lastRow, 6).getValues();