title: Looping through cells in a range in Google Sheets with Google Script
body: <p>I want to write a script that allows me to highlight (background color) only some cells within a selected range, e.g., only cells in COLUMN 2 and ROW 2, even if I select the entire table.</p>
  
  <p>Ex:
  <a href="https://i.stack.imgur.com/wCJhe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wCJhe.png" alt="How the script is supposed to work"></a></p>
  
  <p>For example:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>For each cell in selected range {
   If selected cell[i][j] is within allowed range {
    cell background color = green
   };
  };</code></pre>
  </div>
  </div>
  </p>
  
  <p>The code I'm trying to finish:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function BackgroundColor() {
    var spreadsheet = SpreadsheetApp.getActive();
    var sheet = spreadsheet.getActiveSheet();
    var range = sheet.getActiveRange();
    var cells = range.getValues();
    var numRows = range.getNumRows();
    var numCols = range.getNumColumns();
    
    for (var i = 0; i &lt; numRows; i++) {
      for (var j = 0; j &lt; numCols; j++) {
        if (range.getValues()[i][j] == '') {
          range.setBackground('#00B050').setFontColor('#ffffff')
        }
      }
    }
    range.setValues(cells);
  };</code></pre>
  </div>
  </div>
  </p>
  
  <p>I was able to make it in VBA:</p>
  
  <pre class="lang-vb prettyprint-override"><code>Sub cmdGreen()
  
      Dim Cel As Range
      Dim GreenArrayCount As Integer
      Dim InteriorColor As Long, FontColor As Long
      Dim GreenArray() As Variant
      Dim BodyRange As String
  
      InteriorColor = VBA.RGB(0, 176, 80) 'interior in green
      FontColor = VBA.RGB(255, 255, 255) 'font in white
      GreenArray = Array("COLUMN 2", "ROW 2")
      BodyRange = ActiveSheet.ListObjects(1).DataBodyRange.Address
  
      For Each Cel In Application.Selection.Cells
          If Not Intersect(Cel, Range(BodyRange)) Is Nothing Then
              For GreenArrayCount = LBound(GreenArray) To UBound(GreenArray)
                  If (ActiveSheet.ListObjects(1).HeaderRowRange(Cel.Column).Value _
                      = GreenArray(GreenArrayCount) Or _
                      ActiveSheet.ListObjects(1).DataBodyRange(Cel.Row - 1, 1).Value _
                      = GreenArray(GreenArrayCount)) Then
                      Cel.Interior.Color = InteriorColor
                      Cel.Font.Color = FontColor
                  End If
              Next GreenArrayCount
          End If
      Next Cel
  
  End Sub
  </code></pre>
  
  <p>Can anyone help me, please?</p>