exceloffice-scripts

Office scripts, use Variable to determine a Row inside a SetFormulaLocal If


I'm trying to determine a Row inside of an If clause, i already know the column, it will always be E, but the row will change depending on what the active cell is,

this is what i have:

   let activeRow = workbook.getSelectedRange().getRowIndex()+1;



    let srcAddress = "E" + activeRow.toString();


    // Set selected cell on selectedSheet
    workbook.getSelectedRange().setFormulaLocal("=IF(G16-E3<0,0,G16-E3)"); 

obviouslly this works if i have the E3 in there, but i tired it 2 different ways and im not sure how to do it,

I tried it like:

workbook.getSelectedRange().setFormulaLocal("=IF(G16-srcAddress<0,0,G16-srcAddress)");

and like this:

workbook.getSelectedRange().setFormulaLocal("=IF(G16-E{activeRow}<0,0,G16-E{activeRow})");

but it does not work,

im lost, any help would be amazing,

thank you


Solution

  • You don't need to retrieve the activeRow explicitly. The cell reference automatically adjusts to the row, similar to how a standard formula behaves.

    Pls try

    function main(workbook: ExcelScript.Workbook) {
        let selectedSheet = workbook.getActiveWorksheet();
    
        // Set formulas on range F1:F16
        selectedSheet.getRange("F1:F16").setFormula("=IF($G$16-E1<0,0,$G$16-E1)");
    }
    

    enter image description here


    If you need to use logic similar to what your script implements, pls try to make two changes:

    workbook.getSelectedRange().setFormulaLocal(`=IF(G16-E${activeRow}<0,0,G16-E${activeRow})`);