Is it possible to execute a Google Script on the last row of a spreadsheet exclusively

I have an email script that is functioning correctly, but I only want it to run through the last row with data in it. If there is no data in a row, then I do not need the script to run for that specific row. How can I modify the example script below to reflect this requirement?

For instance, if there are only 3 rows of data in my spreadsheet, I want the script to process those 3 rows and not continue beyond that. However, as the number of entries may vary each day, I cannot set a fixed number.

Essentially, I am trying to replace:

var numRows =20;// Number of rows to process

with some iteration using .getlastrow...I believe?

Here is the sample script for your reference:

function sendEmails() {
  var sheet =SpreadsheetApp.getActiveSheet();

  var startRow =2;// First row of data to process
  var numRows =20;// Number of rows to process

  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow,1, numRows,2)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();

  for(i in data){
    var row = data[i];
    var emailAddress = row[0];// First column
    var message = row[1];// Second column
    var subject ="Sending emails from a Spreadsheet";
    MailApp.sendEmail(emailAddress, subject, message);
   }
}

Thank you for assisting me!

Answer №1

To retrieve the index of the last filled row in the spreadsheet, you can utilize the getLastRow() method. Another option is to use getDataRange().getValues which will return only the rows containing data.

function sendEmails(){

  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow =2;// Define the initial row for processing data
  var data = sheet.getDataRange().getValues();

  for(var i=startRow; i<data.length; i++){
    var row = data[i];
    var emailAddress = row[0];// Extracting data from the first column
    var message = row[1];// Obtaining data from the second column
    var subject ="Sending emails from a Spreadsheet";
    MailApp.sendEmail(emailAddress, subject, message);
  }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a three.js texture with a JSON object

Currently, I am working on a customization project where I am using three.js to export an HTML5 canvas as a 3D preview. My goal is to have the texture placed only on the front side, but it seems to appear on all sides instead. This is the code I am using: ...

Using ng-pattern to validate that a text field does not conclude with a particular term

In this code snippet, I am attempting to prevent a textfield from ending with any of the specified letters in the $scope.pointPattern variable. $scope.pointPattern = /^(?!.*ess|ence|sports|riding?$)/; $scope.error = "not valid"; Upon executio ...

What methods can be used to assess the security risks posed by a third-party library implemented in a React JS application?

How can I ensure the security of third-party libraries added to my create-react-app with additional scripts? ...

How do server side cookies and javascript cookies interact with each other?

Can you explain the connection between the cookies generated by the Cookie Class in Servlet and document.cookie in JavaScript? ...

What is the process for including a checkbox with a label in Card Media?

I attempted to create this feature using code. However, I encountered an issue where the CardMedia and the checkbox would not align properly, resulting in a lack of responsiveness. <Card> <CardMedia ...

Tips for showcasing an image prior to uploading within a personalized design input file

I am facing an issue with displaying multiple images inside custom style input file labels before uploading them to the database. Currently, the script I am using only displays one image at a time and in random positions. My goal is to have each image ap ...

Accessing the Next.js API after a hash symbol in the request URL

Is there a way to extract query strings from a GET request URL that contains the parameters after a '#' symbol (which is out of my control)? For example: http://...onnect/endpoint/#var_name=var_value... Even though request.url does not display a ...

The construction of the Gatsby site encountered a major obstacle

I've been facing challenges while trying to build my Gatsby site. Whenever I run 'gatsby develop' in the console, my app starts without any issues. However, when I attempt to build it, I encounter errors like the ones shown below. Does anyon ...

What could be the culprit behind the error in the "blend-mode" function when using .mp4 files in Firefox?

Attempting to utilize mix-blend-mode with an mp4 playing in the background has been a fun experiment. The concept is to have a div containing some text, with the video playing in the background to create an effect on the letters. This method works flawless ...

Steps to invoke another service (function) prior to calling the res.view() function in sails JS:

I am looking to execute a separate function, like a Service function, before Sails renders the page into HTML. Please refer to the controller code below... var MYController = { index: function(req, res, next) { req.flash("error", "Testing hello ...

Exploring the utilization of type (specifically typescript type) within the @ApiProperty type in Swagger

Currently, I am grappling with a dilemma. In my API documentation, I need to include a 'type' in an @ApiProperty for Swagger. Unfortunately, Swagger seems to be rejecting it and no matter how many websites I scour for solutions, I come up empty-h ...

Ways to adjust a specific div within an ng repeat using the value from JSON in AngularJS

When I select a different option from the dropdown menu, such as cities or states, the values are populated from a JSON file. My specific requirement is to hide a button only when the value 'No data' is populated upon changing the dropdown select ...

How come I am unable to reach the window in my Next.js application's '_app.js' file?

In my Next.js application, I am trying to implement a feature where the app loads and then checks for network access using a custom modal dialog that alerts the user if they lose internet connection. I have set up an _app.js file in my application to estab ...

The function in the method (in quasar) is not activated by the @change event

When I select an option, I am trying to retrieve the selected value in a function called within my methods. However, the function does not seem to be triggering. This is my code: From the template : <q-select filled v-model="invoice_product.tarri ...

A guide to obtaining a single access token/refresh token for unlimited use with oauth2 on the Spotify API

I'm working on a project that will exclusively rely on one Spotify account, but I'm having trouble grasping the concept of the refresh token in oauth2. Ideally, I want to generate an access token and refresh token through the Spotify API console ...

Converting HTML content into a single string simplifies data manipulation and extraction

exampleHTML=" This is sample HTML code that needs to be converted into a string using JavaScript </p>" I am looking to transform it into a single string format like str="This is sample HTML code, that needs to be converted into a string ...

Using async/await keywords in React Native while iterating through an array and calling an API does not result in successful resolution

When attempting to request data from my API in this manner: export default ({ navigation }) => { // Call getMovieImages with the id of the likedMovies from the state.likedMovies const { getMovieImages, state:{ likedMovies }} = useContext(MovieContext); ...

How to trigger a jQuery function once a v-for loop has completed in VueJS?

Utilizing vue-resource, I successfully retrieve data from my API and incorporate it into my HTML. However, I am encountering an issue where I want to execute a jQuery function after the v-for loop has completed in order for jQuery to recognize elements in ...

Validate selected checkbox using JavaScript

Is there a way for me to achieve real-time updates when checking and unchecking multiple checkboxes in a list? Here's the code snippet I currently have: window.onload = function () { var input = document.getElementById('listTaxi'); fu ...

The function webpack.validateSchema does not exist

Out of the blue, Webpack has thrown this error: Error: webpack.validateSchema is not defined Everything was running smoothly on Friday, but today it's not working. No new changes have been made to the master branch since Friday. Tried pruning NPM ...