Search code examples
google-apps-scriptbatch-request

Using batch request when insert columns in google spreadsheet


I'm trying to insert a large number of columns into a table, I need to insert through 2 columns, now my code looks like this

sheet.insertColumnAfter(16),sheet.insertColumnAfter(18),sheet.insertColumnAfter(20),sheet.insertColumnAfter(22)

I tried to use an array, nothing worked, I will be very grateful


Solution

  • I believe your goal as follows.

    • You want to insert the columns like insertColumnAfter(16), insertColumnAfter(18), insertColumnAfter(20) and insertColumnAfter(22) using Google Apps Script.
    • When your goal is achieved, the inserted columns are the columns "Q", "T", "W" and "Z".
    • You want to achieve this using an array.

    Modification points:

    • In this case, how about inserting the columns from insertColumnAfter(22) to insertColumnAfter(16)?
      • I thought that this might be the reason of your issue.
    • In order to use the array, prepare an array including the column numbers, and using the array, the columns are inserted.

    When above points are reflected to the script, it becomes as follows.

    Modified script:

    const sheet = SpreadsheetApp.getActiveSheet();
    const columns = [16, 18, 20, 22];
    columns.reverse().forEach(c => sheet.insertColumnAfter(c));
    
    • In this script, the active sheet is used. So please modify it for your actual situation.
    • When this script is run, the columns are inserted from the column 22 to the column 16. By this, the inserted columns are the columns "Q", "T", "W" and "Z".

    References: