Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsstring-concatenation

Missing ) after argument list when trying to use importrange in app script


I'm trying to use google app script in google sheets to set a formula to importrange. I have the following code:

SpreadsheetApp.getActiveSheet().getCurrentCell().setFormulaR1C1('=IMPORTRANGE("https://docs.google.com/spreadsheets/d/blahblah","Completed Work!B5:N")');

My problem is when I try to make the code take an argument for the URL so when I say:

SpreadsheetApp.getActiveSheet().getCurrentCell().setFormulaR1C1('=IMPORTRANGE('URL',"Completed Work!B5:N")');

When I try to run my function using:

myfunction("https://docs.google.com/spreadsheets/d/blahblah","Completed Work!B5:N")

I get a Missing ) after argument list error, how would I go about fixing the second formula so URL can be passed as an argument of the function?

Thanks!


Solution

  • Short answer

    Use the JavaScript string concatenation operator +

    Extended answer

    You have to learn about string concatenation on JavaScript.

    From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String (follow the link to see the inline links)

    Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf() method, or extracting substrings with the substring() method.

    Instead of

    '=IMPORTRANGE('URL',"Completed Work!B5:N")'
    

    use

    '=IMPORTRANGE("' + URL + '","Completed Work!B5:N")'
    

    NOTE: Pleas note the use of " to doble quote enclose the value of URL as it's required by IMPORTRANGE.