目标是在工作表上的表“PO”中查找 A 列中值为“已取消”、“已订购”或“已作废”的任何行,复制该行,然后将其粘贴到表的末尾(“PO存档”)在sheet2上。在我弄清楚如何执行此操作后,我将从“PO”中删除该行,但现在已将其注释掉。
问题是,当我按原样运行此代码时,代码会在表格末尾粘贴一个空白行(我通过测试在代码中将
lastrow+1
替换为 lastrow-1
时发生的情况确定了这一点)。有趣的是,它只粘贴一个空白行,即使这里有不止一行满足条件。
我还尝试手动将 setValue 语句中的行号更改为满足条件的单行,这会导致脚本在每个单元格 A:O 中粘贴仅包含 A 列值的行。
我也知道我在 for 循环中设置 i 计数器的方式可能效率低下,但我不确定修复它的最佳方法。
function main(workbook: ExcelScript.Workbook) {
let tb = workbook.getTable("PO");
let tableRows = tb.getRowCount();
let sheet = workbook.getActiveWorksheet();
let tb2 = workbook.getTable("PO");
let tableRows2 = tb.getRowCount();
let sheet2 = workbook.getWorksheet("PO Archive");
// Set the range to the column of data to modify
let lastRowCount = sheet.getTable("PO").getRowCount()
if (tb) {
let range = tb.getRangeBetweenHeaderAndTotal();
let vals = range.getValues();
for (let i = 3; i < vals.length + 3; i++) {
let value: string = vals[i - 3][0].toString();
if (value == "Cancelled" || value == "Ordered" || value == "Voided") {
let lastRow = sheet2.getUsedRange().getLastCell().getRowIndex() + 1;
sheet2.getRange(`A${lastRow+1}:O${lastRow+1}`).setValue(sheet.getRange(`A${i+3}:O${i+3}`).getValue());
//tb.deleteRowsAt(0, i-3);
}
}
}
}
修改脚本逻辑如下:
function main(workbook: ExcelScript.Workbook) {
let tbPO = workbook.getTable("PO");
let sheet = workbook.getWorksheet("PO_Table"); // modify as needed
let sheet2 = workbook.getWorksheet("PO Archive");
// Set the range to the column of data to modify
if (tbPO) {
const tabFilter = tbPO.getAutoFilter();
tabFilter.clearCriteria();
const dataRange = tbPO.getRangeBetweenHeaderAndTotal()
tabFilter.apply(dataRange,
0, {
filterOn: ExcelScript.FilterOn.values,
values: ["Cancelled", "Ordered", "Voided"]
});
const visRng = dataRange.getSpecialCells(ExcelScript.SpecialCellType.visible);
if (visRng) {
const desDataRange = sheet2.getUsedRange(true);
const destCell = sheet2.getCell(desDataRange.getRowCount(), 0);
destCell.copyFrom(visRng);
// remove filtered rows from PO
const visAreas = visRng.getAreas().reverse();
let visRngRefs: string[] = visAreas.map(x => x.getAddress());
// remove rows
visRngRefs.forEach(x => {
sheet.getRange(x).getEntireRow().delete(ExcelScript.DeleteShiftDirection.up);
})
}
tbPO.getAutoFilter().clearCriteria();
}
}