In the following VBA code, I debug.print each cell value. Using the data in the picture, my answer appears like this.
Sub loopAndDebugPrintEachCell()
Dim cl As Object
With Sheets("Sheet1")
For Each cl In .Range("A1:D2")
Debug.Print cl.Value
Next cl
End With
End Sub
I am trying to reiterate this code in JavaScript and I figured out a solution, but I am not sure that this is the most efficient way. I am getting the exact same answer, but is there a more advantageous way to loop through a range?
loopAndConsoleLogEachCell = async () => {
try {
await Excel.run(async context => {
const range = context.workbook.worksheets.getItem("Sheet1").getRange("A1:D2");
range.load(["columnCount", "rowCount"]);
await context.sync();
let i = 0;
let rowC = 0;
do {
let loopRng = range.getAbsoluteResizedRange(1, 1).getOffsetRange(rowC, i).load(["values"]);
await context.sync();
console.log(`${loopRng.values} `);
let rangeColCount = Math.floor(((range.columnCount) / 2) + 1);
if (rowC < (range.rowCount) && i == (rangeColCount)) {
rowC++;
i = 0;
} else {
i++;
}
}
while (rowC < range.rowCount && i < range.columnCount);
});
} catch (error) {
console.error(error);
}
};


context.syncin a loop. For details about how to avoid this, see learn.microsoft.com/en-us/office/dev/add-ins/concepts/….