Search code examples
basic

BASIC nested loops: filtering rows


I'm using LibreOffice Calc to store 16 RGB colors (red in B column, green in C and blue in D), then I want to paint the background of 16 cells with each respective color. Each color is in one row.

At the moment I've been able to achieve this partially: not only 16 cells are painted, but 48 (16x3)! It seems I need to "group" the nested loops. This is my code/macro:

function bgcolor()

Dim Doc, Sheet, CellPaint As Object
Dim CellR, CellG, CellB As String

Doc = ThisComponent
Sheet = Doc.Sheets.getByIndex(0)

For i = 1 to 16 step 1
    For j = 1 to 3 step 1
        CellR = Sheet.getCellByPosition(j+0,i).getValue()
        CellG = Sheet.getCellByPosition(j+1,i).getValue()
        CellB = Sheet.getCellByPosition(j+2,i).getValue()
        CellPaint = Sheet.getCellByPosition(j+6,i)
        CellPaint.CellBackColor = RGB(CellR,CellG,CellB)
    next j
next i

bgcolor=CellPaint.CellBackColor

end function

This is the result: Screenshot

The first column of colors (H) is what I need, exactly. Other two columns appear there, so: how do I fix my nested loops? Probably I need to filter them using a simple if statement, but I'm not sure.

EDIT - For reference: the solution should be similar to this one, however I've read it's not possible on OpenOffice (I assume neither on LibreOffice).

Thanks!


Solution

  • Just drop the inner loop -- You don't need to iterate horizontally:

    function bgcolor()
    
      Dim Doc, Sheet, CellPaint As Object
      Dim CellR, CellG, CellB As String
    
      Doc = ThisComponent
      Sheet = Doc.Sheets.getByIndex(0)
    
      For i = 1 to 16 step 1
        CellR = Sheet.getCellByPosition(1,i).getValue()
        CellG = Sheet.getCellByPosition(2,i).getValue()
        CellB = Sheet.getCellByPosition(3,i).getValue()
        CellPaint = Sheet.getCellByPosition(7,i)
        CellPaint.CellBackColor = RGB(CellR,CellG,CellB)
      next i
    
      bgcolor=CellPaint.CellBackColor
    
    end function