Using Google Apps Script to input data into the next available row

Utilizing Google Apps Script, I am retrieving data from another spreadsheet and storing it daily in a sheet named "DATABASE".

Although my current solution is basic, it keeps overwriting existing data. I wish to enhance the script to copy data from the imported range spreadsheet to a specific column and continue copying it to the next empty row without erasing any previously copied data. Can someone please assist me with this?

var scriptProperties = PropertiesService.getScriptProperties();
var ssid = '1usRuvazJlxAGvF0G2-e00MEQ_AjMCOnWopBFX4qfUcc';
var sheetName = 'DATABASE';

function CopyDatabase() {
  var sheet = SpreadsheetApp.openById(ssid).getSheetByName(sheetName);
  var startRow = 3;
  var numRows = sheet.getLastRow() - 1;
  var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
  var data = dataRange.getValues();
  var Copy = "Copy";
  var newRow = sheet.getLastRow() + 1;
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    if (row[5] != Copy) {
      var Code = row[0];
      var orderDate = row[1];
      var custName = row[2];

      sheet.getRange(startRow + i, 5).setValue(Code);
      sheet.getRange(startRow + i, 6).setValue(orderDate);
      sheet.getRange(startRow + i, 7).setValue(custName);

    }
  }
}

Here is the link to the database (Google sheet):

https://docs.google.com/spreadsheets/d/1usRuvazJlxAGvF0G2-e00MEQ_AjMCOnWopBFX4qfUcc/edit#gid=0

Screenshoot

Answer №1

It seems like you're looking to transfer rows from columns A-D (excluding rows where column D is labeled Copy) to columns E-H, starting from the first available empty row in the target columns.

To achieve this, follow these steps:

  • Determine the first empty row in columns E-H using the getNextDataCell(direction) method.
  • Filter out the rows that do not have the value Copy in column D from the source data using the filter function.
  • Utilize the setValues(values) method to copy the filtered rows to the destination columns, starting from the first empty row.

Here is a snippet of the code:

function CopyDatabase() {
  var sheet = SpreadsheetApp.openById(ssid).getSheetByName(sheetName);
  var startRow = 3; 
  var numRows = sheet.getLastRow() - startRow + 1; 
  var startCol = 1;
  var numCols = 4;
  var startColTarget = 5;
  var dataRange = sheet.getRange(startRow, startCol, numRows, numCols); 
  var data = dataRange.getValues(); 
  var Copy = "Copy"; 
  var firstEmptyRow = sheet.getRange("E3:H3").getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow() + 1;
  var dataToCopy = data.filter(row => row[3] !== Copy);
  sheet.getRange(firstEmptyRow, startColTarget, dataToCopy.length, dataToCopy[0].length).setValues(dataToCopy);
}

Answer №2

If you're looking for a simple way to move your data to another tab in the spreadsheet, consider using the following code snippet instead of your current for loop:

  const destinationSheetName = 'New Data Tab';
  const destinationSheet = sheet.getParent().getSheetByName(destinationSheetName)
    || sheet.getParent().insertSheet(destinationSheetName);
  data
    .filter(row => row[3] === "Copy")
    .forEach(row => destinationSheet.appendRow([row[0], row[1], row[2]]));

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

Issue: Reactjs - Material-UI HTML Tooltip does not display dynamic HTML content.In the Reactjs

I have been using a customized HTML MUI Tooltip. Currently, it is functioning with static content but I am looking to make it dynamic. Unfortunately, it is not working with dynamic HTML content. Here is my attempted approach: const ADJUSTMENT_HELP_TEXT = ...

Check the Full Calendar to see if any events are scheduled for today

I have a group of users who need to save their availability. Currently, I am utilizing Full Calendar and looking for a way to prevent them from adding the same event multiple times on a single day. My tech stack includes VueJs and all events are stored in ...

Transform date format using VueJS in JavaScript

I need to convert a date format from 19 Oct 2017 to 20171019. Is there a way to do this quickly? I am using FlatPickr in VueJs. Here is the code snippet for reference: import flatPickr from 'vue-flatpickr-component'; import 'flatpickr/dist/ ...

How can Redux help persist input value through re-rendering?

Handling Input Value Persistence in Redux despite Re-rendering? I am currently able to store and save input values, but only the data from one step ago. For example, when I click on the second input field, it displays the value from the first input fiel ...

Is it possible to use two onChange functions in a single text field with ReactJS?

Is it possible to have two onChange functions in a single Textfield? In my code, "onChange={ showDiv}" is a handler that shows "Direct 2" when clicked and hides upon selecting option1. The second onChange={(e) => exhandleChange(e)} is used for another ...

Error: Type Error - 'style' is not defined in the Progress Bar Project

Having recently started learning Javascript, I have been engaging with various tutorials and projects in order to gain familiarity with the language. One particular tutorial that caught my attention is a Progress-Bar tutorial by "dcode" available at this l ...

On mobile devices, the height of the absolutely positioned element is larger than its

I currently have an element with a background image that includes an absolutely positioned element at the bottom. As the screen width decreases, the height of the absolutely positioned element increases and surpasses the parent element. Since absolutely p ...

Issues arise when using Jquery events in conjunction with AngularJS causing them to function

I have encountered an issue with my AngularJS menu code. I am sending an array to prepare the menu when the document loads. In this sequence, I have also added a click event to the generated menu. However, the click event does not fire if it is placed befo ...

Discover the best practices for implementing MongoDB's latest Schema Validation functionality within your Express.js application

Need help implementing MongoDB's Schema Validation in an Express server? While working on a simple todo app, I opted for the native MongoClient over mongoose but still require a schema for my data. According to MongoDB's documentation available ...

Switching React Icons when Clicked

I'm struggling to understand this. I want the React icons below to be filled and remain filled when clicked, changing back to outlined when another is clicked. Here's the code: import { useState } from "react"; import { Link } from "react-router- ...

Guide on how to initialize a variable in Express.js within a conditional statement in Node.js

Trying to create a variable based on a conditional statement, but even with simple code I am unable to retrieve the new variable. Here is my code: exports.productPatch = (req, res, next) => { const id = req.params.productId; const image = req.body.p ...

What is the process for importing a jquery plugin like turnjs into a React component?

After searching through countless posts on stackoverflow, it seems like there is no solution to my problem yet. So... I would like to integrate the following: into my react COMPONENT. -I attempted using the script tag in the html file, but react does no ...

switch the anchor tag value and send it along with the URL

I am trying to update the value of "trans" in the Ajax URL based on a toggle between on and off values. However, despite successfully toggling the text, the URL parameter does not change accordingly. Can anyone offer any assistance? I currently have to rel ...

Models of Earth and the Sun are failing to render

After numerous attempts at debugging, I am stuck on an issue with my Earth and Sun models not rendering correctly. They are displaying as a dull filled color despite having a texture applied to the sphere. If you could take a look at lines 104 - 141 where ...

Creating variables in styled-components allows you to easily reuse values throughout

Can a variable be defined inside a styled-components component? The code snippet below, although not functioning properly, demonstrates my intention: const Example = styled.div` ${const length = calc(vw - props.someValue)} width: ${length}; &. ...

"I am looking for a way to retrieve dynamic data from a (click) event in Angular. Can

Within my component, I have a video loaded in an i tag on a click event. The challenge is accessing the video ID from the video.component.ts file in order to dynamically load a new video. The solution has been elusive so far. <li *ngFor="let video of c ...

Is there a way I can appropriately display an image in a specific size box?

Check out the code snippet I wrote below: import React from 'react' function OurCourse() { return ( <div className='w-full '> <div className='w-full h-[390px]' style={{ backgroundImage:&apos ...

Can you provide guidance on how to successfully transfer an array of JSON objects from the script section of an HTML file to the JavaScript

My webpage contains an array of JSON objects that I need to send to the server. The array, stored in a variable called results, appears normal when checked in the console before trying to POST it. Here is a sample of the data: 0: {id: 02934, uName: "Ben", ...

When a webpage is moved, the globalProperties variable of "vue3 typescript" is initialized to null

main.ts const app = createApp(App) .use(router) .use(createPinia()) .use(vuetify) .use(vue3GoogleLogin, googleLogin) const globalProps = app.config.globalProperties; globalProps.isDebugMode = true; vue-shim declare ...

Exploring the integration of d3 in an Express application - encountering an error: document is not recognized

I am facing a challenge in my expressjs application where I need to dynamically render vertices in a graph using d3. However, the code execution order seems to be causing issues for me. When attempting to use the d3.select function, I encounter the followi ...