I need to loop though 1 column to find the yellow color cell and add a row after that cell row

71 views Asked by At
function main(workbook: ExcelScript.Workbook) {
    // Get the active worksheet
    let sheet = workbook.getActiveWorksheet();
    // Get the used range of the sheet
    let usedRange = sheet.getUsedRange();
    // Get the row count of the used range
    let rowCount = usedRange.getRowCount();
    console.log(rowCount)
    // Loop through each row of the used range
    let i = "F1"
    for (let i = 0; i < rowCount; i++) {
        // Get the row using the index
        let Range = usedRange.getColumn(6)
        let selectedCell = workbook.getActiveCell();
        let selectedSheet = workbook.getActiveWorksheet();
        let g = selectedCell.getFormat().getFill().getColor();
        let R = selectedCell.getOffsetRange(1, 0).getAddress()
        let Y = R.slice(8, 10)
        let N = Y + ":" + Y
        console.log(N)
        if (g = "#FFFF00") {
            let g = selectedCell.getFormat().getFill().getColor();
            let R = selectedCell.getOffsetRange(1, 0).getAddress()
            let Y = R.slice(8, 10)
            let N = Y + ":" + Y;
            selectedSheet.getRange(N).insert(ExcelScript.InsertShiftDirection.down);
        }
    }
}
1

There are 1 answers

1
taller On

Note: Handling the insertion or deletion of rows in reverse order is a better approach. This helps avoid potential duplication of extra actions.

function main(workbook: ExcelScript.Workbook) {
  const targetColor = "#FFFF00";
  const targetColum = "F1" // any cell in target column
  // Get the active worksheet
  let sheet = workbook.getActiveWorksheet();
  // Get the used range of the sheet
  let usedRange = sheet.getUsedRange();
  let dataRange = usedRange.getIntersection(sheet.getRange(targetColum).getEntireColumn())
  // Get the row count of the used range
  let rowCount = dataRange.getRowCount();
  // Loop through each row of the data range in reverse order
  for (let i = rowCount - 1; i > -1; i--) {
    // Get a cell
    let selectedCell: ExcelScript.Range = dataRange.getRow(i)
    // Get color of the cell
    let cellColor = selectedCell.getFormat().getFill().getColor();
    if (cellColor === targetColor) {
      // Insert row
      selectedCell.getOffsetRange(1, 0).getEntireRow().insert(ExcelScript.InsertShiftDirection.down);
    }
  }
}