Search code examples
google-apps-script

how to apply script to entire columns in google spredsheet


this script changes E1 to 36 and then clears D1. i.e it add two cells and then clears the other cell. D1 E1 10 26

 var ss = SpreadsheetApp.getActiveSheet(); 
 var num1 = ss.getRange("D1").getValue(); 
 var num2 = ss.getRange("E1").getValue();
 ss.getRange("E1").setValue(num1+num2); 
 ss.getRange("D1").clear();

As i have copied code from Google spreadsheet script to add two cells together. i want to aplly above example to all cells in columns i.e entire column D and column E.


Solution

  • This is an answer:

    function addColumns(){
      var ss = SpreadsheetApp.getActiveSheet();
      var len = ss.getLastRow();
      for(var i = 1 ; i < len +1  ; i++){
        var num1 = ss.getRange("D"+i).getValue(); 
        var num2 = ss.getRange("E"+i).getValue();
        ss.getRange("E"+i).setValue(num1+num2); 
        ss.getRange("D"+i).clear(); 
      }
    }
    

    It is not at all efficient ... so you will find it strangely slow. But it works.
    I agree with @eddyparkinson that it is good to learn google apps script (which is pretty much the same as javascript) because you are likely to get a lot out of it. I had to start learning it from scratch about 1 year ago, mainly by looking at this particular forum for google apps script and then, when I got stuck, referencing the huge quantity of javascript general help you can find on the internet just by doing a search for the term in hand.

    EDIT To make it apparent, I have shared this script within a spreadsheet (click here). In that spreadsheet, there is a custom menu called "Script Center Menu>Add column D to E

    This will then add all the values in column D Sheet1 to those in column E Sheet 1, displaying them in column E and deleting the original value in column D. (If you wish to experiment, you can prepare the columns' values manually, simply by typing your required values into columns D and E - it may be easier to first clear current values in columns D and E. An alternative way to set yourself up the values for a demonstration is to use the second menu item Script Center Menu>Copy Columns which will simply copy the existing values in Sheet2 over to Sheet1).