I'm trying to find a Office script (preferably) or VBA that concats the columns: NUMBER,RECORDS,SITE,LC,DESC so it becomes a unique id. Then I'd like to the find the duplicate values of that unique id and return the duplicates value and copies the whole row into another existing blank worksheet.
Dataset
NUMBER | Records | ID1 | Site | LC | Desc | ID2 |
---|---|---|---|---|---|---|
100103 | 23019 | 1 | MAIL1 | LOCK | HOUSE | A |
200103 | 23019 | 2 | MAIL2 | DOCK | HOUSE | B |
100103 | 23019 | 3 | MAIL1 | LOCK | HOUSE | C |
100103 | 23019 | 4 | MAIL4 | DOCK | HOUSE | D |
200103 | 23019 | 5 | MAIL2 | DOCK | HOUSE | E |
100103 | 23019 | 6 | MAIL6 | DOCK | HOUSE | F |
Result
NUMBER | Records | ID1 | Site | LC | Desc | ID2 |
---|---|---|---|---|---|---|
100103 | 23019 | 1 | MAIL1 | LOCK | HOUSE | A |
100103 | 23019 | 3 | MAIL1 | DOCK | HOUSE | C |
200103 | 23019 | 2 | MAIL2 | LOCK | HOUSE | B |
200103 | 23019 | 5 | MAIL2 | DOCK | HOUSE | E |
The main logic is same as privous answer.
findDuplicateRows()
.Extracting columns for duplicate check
section is changed to concate the key from selected cols.function main(workbook: ExcelScript.Workbook) {
const Sheet1 = workbook.getWorksheet("Sheet1");
const Sheet2 = workbook.getWorksheet("Sheet2");
const dataRng = Sheet1.getRange("A1").getSurroundingRegion()
const dataVals = dataRng.getValues();
// Extracting columns for duplicate check
const keyCols = "1|2|4|5|6"; // modify as needed
const colIndex = keyCols.split("|").map(c => Number(c) - 1);
const mergedRows: string[] = [];
for (let i = 0; i < dataVals.length; i++) {
const row = dataVals[i];
const mergedRow = colIndex.map(idx => row[idx]).join("|");
mergedRows.push(mergedRow);
}
const dupVals = findDuplicateRows(mergedRows, dataVals);
if (dupVals) {
const rowCnt = dupVals.length;
const colCnt = dupVals[0].length;
Sheet2.getRange().clear(ExcelScript.ClearApplyTo.all);
Sheet2.getRange("A1").getAbsoluteResizedRange(rowCnt, colCnt).setValues(dupVals);
} else {
console.log("No duplicated data")
}
}
function findDuplicateRows(mergedRows: string[], dataVals: (string | boolean | number)[][]): (string | boolean | number)[][] {
const duplicateRows: (string | boolean | number)[][] = [];
const foundRows: Set<string> = new Set();
for (let i = 0; i < mergedRows.length; i++) {
const row = mergedRows[i];
if (!foundRows.has(row)) {
for (let j = i + 1; j < mergedRows.length; j++) {
if (row === mergedRows[j]) {
duplicateRows.push(dataVals[i]); // Add the entire row
foundRows.add(row);
break;
}
}
} else {
duplicateRows.push(dataVals[i]);
}
}
return duplicateRows;
}