我正在尝试遍历工作表并计算职位的“先进先出”成本基础。我的工作表现在只有约120行,但无疑会随着时间而增长。该功能已经执行得非常慢,因此我正在寻找有关如何加快其速度的解决方案。我也是菜鸟编码者,这是我第一次使用javascript,因此,任何其他建议将不胜感激!
谢谢!
function FifoCostBasis(symbol, quantity) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Transactions Import");
var lastRow = 150;
var lastCol = 12;
var costBasisSold = Number(0);
var quantitySold = Number(0);
for (var row = lastRow; row >= 2; row--){
var action = sheet.getRange(row,2).getValue();
var sym = sheet.getRange(row,3).getValue();
var qSold = Number(sheet.getRange(row,5).getValue());
var cbSold = Number(sheet.getRange(row,10).getValue());
var price = Number(sheet.getRange(row, 6).getValue());
if(["Buy", "Reinvest Shares", "Short Term Cap Gain Reinvest",
"Qual Div Reinvest", "Long Term Cap Gain
Reinvest"].indexOf(action)>=0
&& sym == symbol){
quantitySold += qSold;
costBasisSold += cbSold;
if(quantitySold > quantity){
var difference = quantitySold - quantity;
var cbSoldAdj = difference*price;
quantitySold = quantitySold - difference;
costBasisSold = costBasisSold - cbSoldAdj;
};
};
};
return costBasisSold;
};
答案 0 :(得分:1)
您应该最小化对getValue()的调用。您应该下拉一组值,而不是一次获取一个值。
var data = sheet.getRange(2, 1, lastRow, lastCol).getValues();
这将返回一个Javascript数组对象。要记住的一件事是,Javascript数组从索引值0开始。
var row2 = data[0]; //Since we the range started at row 2, row 2 will be at position 0.
var row2col1 = row[0][0];
如果使用数组中的值,则该过程将更快。
答案 1 :(得分:0)
类似的方法可能对您有用:
function FifoCostBasis(symbol, quantity) {
if(symbol && quantity){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sh=ss.getSheetByName("Transactions Import");
var lastRow=150;//there is a sh.getLastRow() function that might work for you
var lastCol=12;//there is a sh.getLastColumn() function that might work for you
var rg=sh.getRange(2,1,149,12);//row 2, column 1, num rows = 150-2+1, 12 columns
var vA=rg.getValues();//all data for the entire sheet is acquired here
var costBasisSold=0;
var quantitySold=0;
for(var i=vA.length-1;i>=0;i++){//i=0 is row 2
var action=vA[i][1];
var sym=vA[i][2];
var qSold=Number(vA[i][4]);
var dbSold=Number(vA[i][9]);
var price=Number(vA[i][5]);
if((["Buy","Reinvest Shares","Short Term Cap Gain Reinvest","Qual Div Reinvest","Long Term Cap Gain Reinvest"].indexOf(action)>=0) && sym==symbol){
quantitySold += qSold;
costBasisSold += cbSold;
}
if(quantitySold > quantity) {
var difference = quantitySold - quantity;
var cbSoldAdj = difference*price;
quantitySold = quantitySold - difference;
costBasisSold = costBasisSold - cbSoldAdj;
}
}
return costBasisSold;
}else{
throw('Error: Invalid Inputs in function FifoCostBasis');
}
}