Excel script encountering "Cannot Convert" error while trying to generate a link to a file within a spreadsheet

This function is designed to search through a spreadsheet and extract the link from the third column based on the value in the first column

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var searchMenuEntries = [ {name: "Search in all documents", functionName: "search"}];
  ss.addMenu("Search Document List", searchMenuEntries);
}


function lastValue(column) {
  var lastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
  var values = SpreadsheetApp.getActiveSheet().getRange(column + "1:" + column + lastRow).getValues();

  for (; values[lastRow - 1] == "" && lastRow > 0; lastRow--) {}
  return values[lastRow - 1];
}

function search() {

  // Get the current spreadsheet and active sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  
  var startRow = 2;  // Starting row of data 
  var numRows = lastValue("A");   // Total rows to process
  var dataRange = sheet.getRange(startRow, 1, numRows)
  
  var data = dataRange.getValues();
  for (i in data) {

    var files = DocsList.find(data[i].toString());

    for (var j = 0; j < files.length; j++) {


      if (files[j].getType() == "other"){
        urlBase = "https://docs.google.com/fileview?id=";
        sheet.getRange(i, 3, 1, 1).setValue(urlBase + files[j].getId());
       }
    }


  }

}

However, when executed, an error occurs:

Cannot convert d59f868312238f16bd8534f61c01dd0695512d38 in (class)

The string mentioned above is the final value in column A that I use to retrieve the link with DocsList.find

Any ideas on what might be causing this issue?

Thank you

Answer №1

Another option would be to utilize the DriveApp feature.

var items = DriveApp.getFilesByName(data[i].toString());

while (items.hasNext()) {

   var item = item.getNext();

   if (item.getMimeType().indexOf("other") !== -1) {
     Logger.log(item.getUrl());
   }
}

Answer №2

Running the code provided resulted in an error occurring at this specific line:

var dataRange = sheet.getRange(startRow, 1, numRows);

The issue lies in incorrectly utilizing the syntax for the getRange() function. I encountered a similar error message while testing your code.

getRange supports two types of notation parameters: A1 notation and R1C1 notation.

A1 notation requires that the parameter be enclosed within quotation marks as it is a string:

var cell = sheet.getRange("A1");

R1C1 notation encompasses four settings, yet you have only included three. The correct format for R1C1 notation is:

Start Row, Start Column, Number of Rows to Get, Number of Columns to Get

This distinction may not be detailed in the getRange() documentation, but further clarification can be found in the documentation for getSheetValues() available here:

Google Documentation - getSheetValues

Answer №3

After identifying design flaws in the program, I undertook a complete refactoring to eliminate errors. Despite this, the script halted prematurely due to exceeding the allowed runtime. Implementing a sleep function as per Google's request helped manage the multiple requests but did not enable processing all 370 rows in the spreadsheet, stalling at row 318.

I am seeking advice on enhancing the performance of my algorithm. Are there any techniques that can optimize its efficiency?

function search() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  var startRow = 2;
  var numRows = sheet.getMaxRows();

  var dataRange = sheet.getRange(startRow, 1, numRows - 1);
  var data = dataRange.getValues();
  k = startRow;

  for (i in data) {
    var files = DocsList.find(data[i].toString() + ".txt");
    Utilities.sleep(1000);

    for (var j = 0; j < files.length; j++) {
      if (files[j].getType() == "other") {
        urlBase = "https://docs.google.com/fileview?id=";
        sheet.getRange(k, 8, 1, 1).setValue(urlBase + files[j].getId());
        k = k + 1;
        break;
      }
    }
  }

}

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

Creating random objects that span multiple directions in three.js involves utilizing the Math.random() function to generate

My goal is to generate a sphere in Three.js by constructing multiple cylinders and then rotating them in various directions. I attempted to iterate through 2 pie settings to adjust the rotation axis, but unfortunately, it did not yield the desired outcom ...

Encountering a blank screen issue post building with vue-cli-service and electron:build

I have attempted various solutions to eliminate the blank screen issue in my electron application: (1) I tried commenting out createProtocol and loadURL('app:...') in background.js and instead using path.join(): if (process.env.WEBPACK_DEV_SERVE ...

Customize your Wordpress site with a JQuery load more button specifically designed for custom post types

I'm currently working on adding a "load more" button to my WordPress website in order to load my custom post types. I've managed to successfully make it load the posts, but I'm facing an issue where each time I load more posts, it replaces t ...

Execute JavaScript using "matches" without the need for the page to refresh

I have been developing a school project which involves creating a Chrome extension to streamline the Checkout process on a website. In my manifest.json file, I specified that a content.js file should run when it matches a specific URL. "content_script ...

Script on Google Sheets fails to update with every event trigger

I came across a JSON import script while exploring. /** * Retrieves all the rows in the active spreadsheet that contain data and logs the * values for each row. * For more information on using the Spreadsheet API, see * https://developers.google.com/a ...

Using Javascript to implement a min-width media query

I'm currently facing an issue with my website () where the media query (min-width) is not effectively removing a JavaScript code within a specific div. The HTML structure in question is as follows: <div id="advertisementslot1"> <script lang ...

The Katura video is loading properly, yet it is rotating instead of playing

I am working on a web application that involves playing videos from Kaltura platform and then loading the link on an iOS webview. <html> <body> <div id="myEmbedTarget" style="width:400px;height:330px;"></div> ...

What is the reason behind TypeScript choosing to define properties on the prototype rather than the object itself?

In TypeScript, I have a data object with a property defined like this: get name() { return this._hiddenName; } set name(value) { ...stuff... this._hiddenName = value; } However, when I look at the output code, I notice that the property is on ...

Encountered a Error: [$injector:modulerr] while integrating Angular JS with the mysterious Planet 9

I encountered an error after implementing AngularJS in Planet 9. Planet 9 is a tool built on top of SAP UI5, offering drag and drop functionality as well as the ability to include HTML, CSS, and JavaScript. I needed to use ng-repeat for an application, so ...

What is the best approach for managing _app.js props when transitioning from a page router to an app router?

Recently, in the latest version of next.js 13.4, the app router has been upgraded to stable. This update prompted me to transition my existing page router to utilize the app router. In _app.jsx file, it is expected to receive Component and pageProps as pr ...

Definition of a class in Typescript when used as a property of an object

Currently working on a brief .d.ts for this library, but encountered an issue with the following: class Issuer { constructor(metadata) { // ... const self = this; Object.defineProperty(this, 'Client', { va ...

Tips for altering the class of an HTML button dynamically when it's clicked during runtime

I currently have a set of buttons in my HTML page: <button id="button1" onclick="myFunction()" class="buttonClassA"></button> <button id="button2" onclick="myFunction()" class="buttonClassA"></button> <button id="button3" onclic ...

Modifying JSON data within an Express Node.js server

As someone who is relatively new to the world of node.js and web development, I am eager to learn more. If you have any valuable resources or materials for me to explore, please share them. Currently, my focus is on prototyping the exchange of a JSON obje ...

Swap the displayed text in a textbox within an HTML5 document

Is there a way to replace specific text in an HTML5 document? Let's say the user inputs: My name is Toni. I want to change the output text "Toni" to Ani, so the final output is: "My name is Ani". This is the current code I have: <title>tex ...

Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct ...

Guide on incorporating a refresh button to automatically update information from a database in MaterialUI's Datagrid

Recently diving into JavaScript, I encountered a common issue: The data for my table is sourced from a MySQL database through Axios Whenever CRUD operations are performed in the web app, the database is updated accordingly Although backend changes ...

Creating a Basic jQuery AJAX call

I've been struggling to make a simple jQuery AJAX script work, but unfortunately, I haven't had any success so far. Below is the code I've written in jQuery: $(document).ready(function(){ $('#doAjax').click(function(){ alert ...

Unable to execute PHP files using Node.js

I have been working on a Node.js web application hosted on a Heroku server. The issue I am facing is related to an AJAX request in my JavaScript code that sends a GET request to a PHP file on the server. Interestingly, this request works perfectly when I r ...

When selecting the top edge in React flow, it will automatically select the bottom

Documentation: Example from documentation: Steps to replicate issue: Drag and drop any node to a different location Select the top edge handle of the moved node Try dragging the edge out and notice that the bottom edge gets selected instead of the top e ...

What is preventing the console from displaying [Object] instead of my information?

Looking to add a meme command to my Discord bot using data stored in a JSON file called memes.json. In my index.js file, I have a variable set up to retrieve the data as follows: const meme = require("./memes.json"). However, when trying to embed the meme ...