Modify a Google Docs script for use in Google Sheets

I created a function called "myFunk()" that works flawlessly in Google Docs. It essentially looks for fields marked with ## in a sheet and replaces them with user input. However, when I attempt to run it in Sheets after making some changes to the functions, I receive an error message stating "Cannot find function replaceText in object." What could be causing this issue?

function myFunk() {
  // Code to display dialog boxes for information gathering.
  var documentProperties = PropertiesService.getDocumentProperties();
  var ui = SpreadsheetApp.getUi();
  //var response = ui.prompt('Enter Name', 'Enter owners person's name', ui.ButtonSet.OK);
  var nameResponse = ui.prompt("Enter the name of the document OWNER");
  var salesperson = nameResponse.getResponseText();
  var documentProperties = PropertiesService.getDocumentProperties();
  var date = new Date();
  var htmlDlg = HtmlService.createHtmlOutputFromFile("HTML_myHtml")
    .setSandboxMode(HtmlService.SandboxMode.IFRAME)
    .setWidth(200)
    .setHeight(150);

  var modal = SpreadsheetApp.getUi();
  modal.showModalDialog(htmlDlg, "Document Classification");

  //Get Current Document ID
  var documentId = SpreadsheetApp.getActiveSpreadsheet().getId();
  console.log(documentId);

  //Get the document body as a variable
  var body = SpreadsheetApp.openById(documentId).getDataRange().getValues();
  console.log(body);

  //Insert the entries into the document
  body.replaceText("##OWNER##", nameResponse.getResponseText());

  //AddValuesFromModal();
}
<form id="docType">
<select id="selectDocumentType" name="documentClass">
  <option value="PUBLIC">Public</option>
  <option value="INTERNAL">Internal</option>
  <option value="CONFIDENTIAL">Confidential</option>
  <option value="SECRET">Secret</option>
</select>

<hr/>
 <input type="button" onClick="formSubmit();" value="Submit" />
</form>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>a
    function formSubmit(){
    Submit();
    }
   
    
    function Submit() {
    var selectedValue = $('#selectDocumentType').val();
    console.log(selectedValue);
      google.script.run
        .withSuccessHandler(closeIt)
        .AddValuesFromModal(selectedValue);
      };
      
    function closeIt(){
      google.script.host.close();
    };
    </script>

Answer №1

When working with a Spreadsheet, there is no traditional body section like in a document. Instead, you will find Ranges, which are grids of data that represent the cells within the spreadsheet that you want to manipulate. Rather than focusing on the values within the Range as you may be doing currently, it is more efficient to work directly with the Range object itself.

To achieve this, you can select the desired Range using getDataRange(), but avoid calling getValues(). Instead, utilize a TextFinder object to search for and replace specific data within the Range.

The code snippet below demonstrates how you can accomplish this:

var range = SpreadsheetApp.openById(documentId).getDataRange();
var finder = range.createTextFinder('##OWNER##');
finder.replaceAllWith(nameResponse.getResponseText());

This code snippet can be condensed into a simpler one-liner for increased efficiency:

SpreadsheetApp.openById(documentId).getDataRange().createTextFinder('##OWNER##').replaceAllWith(nameResponse.getResponseText());

For more information, please refer to:

https://developers.google.com/apps-script/reference/spreadsheet/range#createTextFinder(String)

https://developers.google.com/apps-script/reference/spreadsheet/text-finder#replaceWith(String)

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

The audio event continues to trigger even after it has been removed using removeEventListener

In my React component, specifically handling an audio track with an HTML <audio> element, I have implemented the following lifecycle methods: componentDidMount() { const {track} = this.props; this.refs.audio.src = track.getTrackUrl(); _.each(t ...

Display the properties of the nested object

I am trying to extract and print the postal_code value from the JSON file provided below: { "results" : [ { "address_components" : [ { "long_name" : "286", "short_name" : "286", "t ...

How can you create a basic slideshow without relying on jQuery to cycle through images?

Imagine you have a div containing 3 images. Is there a way to build a basic slideshow that smoothly transitions between the images, showing each one for 5 seconds before moving on to the next one and eventually looping back to the first image without rely ...

Building a Wordpress website with AJAX functionality using only raw Javascript and no reliance on Jquery

So, I have a custom script named related-posts.php, and I want to insert it into posts only when the user scrolls. In addition, I have an enqueued script file in WordPress that loads in the footer, where I have written AJAX code like this: var xmlhttp = ...

What is the best way to structure a JSON object to support conditional statements?

My goal is to develop a JSON object capable of handling conditionals/branching. My workflow involves multiple steps where the user's choices determine the subsequent set of options. This branching logic continues throughout different stages. I envisi ...

What is the best way to dynamically insert a new row into a table, with each row containing a table heading and column?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="tbl" class="tbl1"> <tr> <th> mobileno </th> <td class='mo' id="mo_0"> </td> ...

Using window.print as a direct jQuery callback is considered an illegal invocation

Curious about the behavior when using Chrome $(selector).click(window.print) results in an 'illegal invocation' error $(selector).click(function() { window.print(); }), on the other hand, works without any issues To see a demo, visit http://js ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

Changing a string into a date format with the help of JavaScript AngularJS

My string is as follows: 13-12-2017 05:05 AM I am looking to convert it to the following format: Date 2017-12-13T05:05:00.000Z Attempted Solution: var mydate = '13-12-2017 05:05 AM'; var selectedDate = new Date(mydate); Upon logging the selec ...

How much will it set me back for '`$(this)`?

Many individuals in this community frequently recommend caching the jQuery object generated from a DOM element, as illustrated by the following code snippet: $('#container input').each(function() { $(this).addClass('fooClass'); ...

How to use jQuery to hide list items after a certain threshold

$('li[data-number=4]').after().hide(); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li data-number="0"">1</li> <li data-number="1">2</li> ...

Exploring Selenium: Clicking on Auto-Complete Suggestions using Python

Attempting to interact with an auto-complete search bar on the site in order to search for results. Wanting to click on the drop-down element that appears after entering a city name to perform a full city name search and obtain results. Below is the cod ...

I'm having trouble getting Tailwind CSS colors to work with my Next.js components. Any tips on how to apply background colors

https://i.stack.imgur.com/8RGS3.png https://i.stack.imgur.com/FRTOn.png Hey there! I'm currently experimenting with using Tailwind background colors in my Next.js project. However, I'm facing an issue where the background color is not being appl ...

Navigating through segments of an array in javascript

Within my condensed array, I have omitted most of the input data to demonstrate a particular task. For illustrative purposes, here is an extensive example showcasing the elements: storyArray=["#C1", "String showing first message", "String displaying secon ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Exploring Error Handling in AngularJS and How to Use $exceptionHandler

When it comes to the documentation of Angular 1 for $exceptionHandler, it states: Any uncaught exception in angular expressions is passed to this service. https://code.angularjs.org/1.3.20/docs/api/ng/service/$exceptionHandler However, I have noticed ...

Incorporate a new class for every date within the range of start and end

I have incorporated a JQuery event calendar plugin into my project, sourced from this specific website. Within my events, there are distinct start and end dates. Currently, I have managed to display green squares on the calendar for both the start and end ...

Using jQuery to trigger several setTimeout() functions in succession

I'm struggling to grasp the concept of jQuery promises. To delve into this topic, I have put together the following code snippet inspired by a discussion on StackOverflow. let functions = [ function () { setTimeout(function () { console.log("func ...

Do you think my approach is foolproof against XSS attacks?

My website has a chat feature and I am wondering if it is protected against XSS attacks. Here is how my method works: To display incoming messages from an AJAX request, I utilize the following jQuery code: $("#message").prepend(req.msg); Although I am a ...

Unleashing the power of scroll-based dynamic pagination in ReactJS

I have 33 entries in a json format. I've implemented a code that tracks the scroll on my page and loads new 10 entries at a time. Everything works smoothly when the scroll value is set to equal or less than zero. When the scroll reaches the bottom of ...