Google-apps-script – How to change position of column form responding sheet after add form item

google-apps-scriptgoogle-forms

I can add an item to a Google form and to change its position in the form by Google apps script. The corresponding column in the responding sheet is always the last column. I can manually move that column to the position I want (same position as the item in the form), but how do I move it using Google apps script?

Best Answer

It is not possible for a script to rearrange columns linked to a form. The sheets and columns linked to a form are special, and this special nature is not something Apps Script can see. (Explanation below).

Alternative approach

Create another sheet, Real Form Data, in which the first row is filled with formulas such as

={'Form Responses 1'!A:A}, ={'Form Responses 1'!C:C}, ={'Form Responses 1'!B:B}

in whatever order you wish. These formulas can be manipulated by a script in any way you want, with setFormula(s) methods. You can hide the original sheet with form data, and work only with this new one, which has the desired order of columns.

Explanation

There is no script method for "moving" the way we move rows and columns in the interface. Their surrogates, described in Moving a column in Google Spreadsheet, are

  1. Insert a column, copy values there, delete the original.
  2. Take values of the entire sheet, rearrange them script-side, then write back.

Method 1 doesn't work for form data because the new column wouldn't be linked to the form (and the original column can't be deleted).

Method 2 doesn't work because changing the values in columns doesn't affect their invisible link to the form: it will still send data in the same way as it did.