Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-macros

How to Change .getMergedRanges() From String to a Range?


The following code will run very slow in my Google Sheets because my getRange is too large. Is there a way to only loop through the columns that are merged? I only want the for loop to get the number of columns in "yourRange" that are merged.

function getUpfrontCosts() {
    var sheet = SpreadsheetApp.getActive().getSheetByName('LPB_COST');
    var cl , count=0;
    var yourRange = sheet.getRange("H13:UV13");
    for (var i = 1; i < yourRange.getNumColumns()+1; i++)
    {
        cl=yourRange.getCell(1, i);
        if (cl.isPartOfMerge()){
            if (cl.offset(15, 0).getBackground() == "#ff8300" && cl.getMergedRanges()[0].getCell(1, 1).getValue()=='Upfront Costs') {
               count = count + cl.offset(15, 0).getValue();
            }
            else {
            }   
        } else {
        }
    }
   return count;
};

The second code is how I am trying to turn a string to a range. I am getting "Cell reference out of range" error

How can I change cl to not be a string and be a range?

function getUpfrontCosts() 
{
    var sheet = SpreadsheetApp.getActive().getSheetByName('LPB_COST');
    var destSheet = SpreadsheetApp.getActive().getSheetByName('Top Level PN');
    var cl , count=0;
    var yourRange = sheet.getRange("I13:UZ13");
    var mergedRanges = yourRange.getMergedRanges();
    for (var i = 0; i < mergedRanges; i++){
    }
    var newRange = sheet.getRange(mergedRanges[i].getA1Notation());
    Logger.log(newRange.getA1Notation());
    for (var i = 0; i < newRange.getNumColumns()+1; i++){
      cl=newRange.getCell(1, i);
      Logger.log(newRange.getA1Notation());
          if (cl.offset(15, 0).getBackground() == "#ff8300" && cl.getValue()=='Upfront Costs') {
               count = count + cl.offset(15, 0).getValue();
            }
            else {
            }
    }
   return count;
};

This is the line with the error

   cl=newRange.getCell(1, i);

Solution

  • if you want to use merge cell range, you can do this:

    function UntitledMacro1() 
    {
        var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
        var cl , count=0 ;
        var yourRange = sheet.getRange("I13:UZ13");
        var bb = yourRange.getMergedRanges();
        for (a=bb[0].getColumn();a<bb[0].getLastColumn()+1;a++)
        {
          //Your actual columns from I13, for first merge range, here your cl, 
          //but if your range is ("13:13"), you don't need 
          //-sheet.getRange("I13").getColumn()+1
          cl=yourRange.getCell(1, a-sheet.getRange("I13").getColumn()+1);
    
          //For your offset 15
          Logger.log(cl.offset(15, 0).getValue());
    
          //on so on
    
        }
    };