我一直在試圖找出原因,但不知道for loop足夠多并不會讓我知道為什么會發生這種情況。
我正在執行以下操作:
- 使用獲取一列資料(類別)
getvalues() - 回圈遍歷它并隔離每個值以進行進一步比較
- 將其他類別推入一個陣列(在將每個類別與下一次迭代中的行資料進行比較時將被忽略;
- 將資料集每一行的第一列與步驟 2 中隔離的類別進行比較;
它為我提供了在資料中找到每個類別的正確行,但是當我將該值放入陣列時,它會比它應該推的多一個,導致陣列大于作業表值。
const categories = catSubSheet.getRange(2, 1, catSubSheet.getLastRow(), 3).getValues();
const subCategories1 = categories.filter(e => e[1] != '').map(function (e) { return e[1] });
const sheetData = sheet.getRange(5, 1, sheet.getLastRow(), 15).getValues();
var sub1Array = [];
var subCategory1 = '';
for (let n = 0; n < subCategories1.length; n ) {
let subs1ToIgnore = [];
subCategory1 = subCategories1[n];
//PUSHES SUBCATEGORIES 1 TO IGNORE IN THE FOLLOWING ITERATION
for (let a = 0; a < subCategories1.length; a ) {
if (subCategories1[a] != subCategory1) {
subs1ToIgnore.push(subCategories1[a])
}
}
let found;
for (let n = 0; n < sheetData.length; n ) {
const rowData = sheetData[n][0]
rowData.toString().trim();
if (rowData !== '' && rowData === subCategory1) {
found = true
startRowsSub1 = n 5
}
if (found) {
sub1Array.push([subCategory1])
}
if (subs1ToIgnore.indexOf(rowData) > - 1) {
found = false
}
}
}
資料從第 5 行開始。
以下是日志:

感謝任何幫助。
uj5u.com熱心網友回復:
確保在執行時應用偏移量,getRange 尤其是在處理不是從第一行開始的資料時。
由于您的腳本非常笨拙,因此我對其進行了大修。請參閱下面的答案。
腳本:
//THIS FUNCTION FORMATS CELL BACKGROUND COLORS AND SPREADS THE FORMULAS FROM ROW 4 (WHICH IS HIDDEN) THROUGH THE SHEET
function formatBOQcells() {
const SS = SpreadsheetApp.getActiveSpreadsheet();
const sheet = SS.getSheetByName('Test')
const catSubSheet = SS.getSheetByName('Categories and Subcategories')
const categories = catSubSheet.getRange(2, 1, catSubSheet.getLastRow() - 1, 3).getValues();
const subCategories1 = categories.filter(e => e[1]).map(function (e) { return e[1] });
// get ColA, transform to 1D array and remove blank cells
const sheetData = sheet.getRange(5, 1, sheet.getLastRow() - 4, 1).getValues().flat().filter(String);
// this will store the current subcategory
var currSubCategory = [''];
// for each sheetData row
const output = sheetData.map(item => {
// check if description a subcategory
if(subCategories1.includes(item)) {
// if subcategory, save it as current subcategory
currSubCategory = [item];
// return its value
return currSubCategory;
}
// if item is this row, write nothing
if(item == 'Sub Total for Pipework') {
return [''];
}
// if item is not a subcategory, assign the current subcategory
return currSubCategory;
});
sheet.getRange(5, 3, output.length, output[0].length).setValues(output);
}
筆記:
- 第三個引數是資料長度。而且由于您不是從 1 開始,因此您需要偏移引數以獲得確切的數字
- 要獲得正確的偏移量,您需要減去跳到最后一行的行數(假設所有行都是有效/未過濾的)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/431123.html
