Search code examples
exceltypescriptoffice-scripts

Problem with Loop Through Number Range Using Array Values


I'm using Office Script in Excel. I have a spreadsheet of data, and each row starts with a driver's full name. I pulled the first names into an array. Now I'm trying to loop through each row and based on the driver name, copy the row to the sheet that is named after the driver.

Here is the code:

for (let value of uniquedrivers) {
    for (let i = 1; i <= lastrow; i++) {
        if (value = wsALL.getRangeByIndexes(i, 0, 1, 1).getValue().toString().substring(0, wsALL.getRangeByIndexes(i, 0, 1, 1).getValue().toString().indexOf(" "))) {
            workbook.getWorksheet(value).getRange("A:K").getUsedRange(true).getLastRow().getOffsetRange(1,0).copyFrom(wsALL.getRangeByIndexes(i, 0, 1, 1).getEntireRow())
            }
    }
};

When I run my current code, it pastes the data to the appropriate driver sheet, but it does it once for each item in my array. So my array has 16 driver names in it, and I end up with 16 copies of each driver's data on each driver sheet.

Here is what I get when I log my array:

(16) ["Aaron", "Bruce", "Calvin", "Cheng", "Donnie", "Dustin", "Eric", "Eugene", "Jerry", "Jethro", …] 0: "Aaron" 1: "Bruce" 2: "Calvin" 3: "Cheng" 4: "Donnie" 5: "Dustin" 6: "Eric" 7: "Eugene" 8: "Jerry" 9: "Jethro" 10: "Kirk" 11: "Louis" 12: "Lt" 13: "Lynn" 14: "Rick" 15: "Tracy"


Solution

  • In OfficeScript (TypeScript), =, ==, and === are three different operators with distinct purposes and behaviors.

    • = (Assignment Operator): is used to assign a value to a variable.

    • == is used to compare two values for equality. It performs type coercion (type conversion) before comparison.

    • === is also used to compare two values for equality. It returns true only if the values and types are the same.


    • Assignment Operator is used as comparation operator. The if condition is always evaluated as True. It's the reason why you got 16 copies of each driver's data on each driver sheet.

    eg.

    let c:number=3;
    console.log(c)              // 3
    console.log(c==4)           // false    
    console.log(c===4)          // false    
    console.log(Boolean(c=4))   // true , the value of c is changed to 4           
    console.log(c===4)          // true    
    

    Change your code to

    if (value == wsALL.getRangeByIndexes(i, 0, 1, 1).getValue().toString().substring(0, wsALL.getRangeByIndexes(i, 0, 1, 1).getValue().toString().indexOf(" ")))