简体   繁体   中英

Google Sheets App Script Add Value Cell Based on Date

I have the following sample sheet which uses the following formulas that somewhat work. I say somewhat because often opening the sheet there are errors with the filter formulas after sorting filtering the tabs or sometimes when new rows are added. The values being set are not going to change once set initially so I'm looking for some help getting me started with an app script that will set the values on open if the value in the respective cells are blank.

I'd like to use app script one because of the said errors and also interested in learning it a bit. I've done a bit of js work in other platforms and confident I can dial this in with help with one or of the following

Transaction Tab

    FILTER(text(B2:B,"MMMM"),Not(ISBLANK(B2:B)))
    FILTER(text(B2:B,"YYYY"),Not(ISBLANK(B2:B)))
    filter(if(E2:E < 0,"debit","credit"),not(ISBLANK(E2:E)))
    filter(VLOOKUP(D2:D,Lists!A:B,2,false),not(ISBLANK(B2:B)))

BalanceHistory

   FILTER(text(B2:B,"MMMM"),Not(ISBLANK(B2:B)))
   FILTER(text(B2:B,"YYYY"),Not(ISBLANK(B2:B)))
   ARRAYFORMULA({"Date/Time"; B2:B+C2:C})

https://docs.google.com/spreadsheets/d/17SId7mIzO3hVOC36Nq40O0bjPS5YfGOX4wsMU1NlbCU/edit?usp=sharing

You can refer to this sample code:

function onOpen() {
  updateTransactionsSheet();
  updateBalanceHistorySheet();
}

function updateTransactionsSheet() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var transactionSheet = ss.getSheetByName("Transactions");
  var transactionData = transactionSheet.getDataRange().getValues();

  // Check each row data in the transaction sheet. Ignore header row
  var transactionResult = [];
  for (var i = 1; i < transactionData.length; i++) {
    var row = transactionData[i];
    Logger.log("Current row: ",row)
    var date = row[1]; // Get date value in column B (zero-based)
    var amount = row[4] // Get amount value in column E (zero-based)

    var dateObj = new Date(date);
    var month = dateObj.toLocaleString('default', { month: 'long' });
    var year = dateObj.getFullYear().toString();
    var amountStr = amount < 0 ? "Debit" : "Credit";
    
    transactionResult.push([month, year, "", amountStr])
  }
  Logger.log(transactionResult)
  // Write result in transaction sheet to column P (index 16 one-based) starting from row 2
  transactionSheet.getRange(2,16,transactionResult.length,transactionResult[0].length).setValues(transactionResult);
}

function updateBalanceHistorySheet() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var balanceSheet = ss.getSheetByName("BalanceHistory");
  var balanceData = balanceSheet.getDataRange().getValues();
  // Check each row data in the balance sheet. Ignore header row
  var balanceResult = [];
  for (var i = 1; i < balanceData.length; i++) {
    var row = balanceData[i];
    var date = row[1]; // Get date value in column B (zero-based)
    var time = row[2]; // Get date value in column C (zero-based)
    
    var dateObj = new Date(date);
    dateObj.setHours(time.getHours(),time.getMinutes(),0);
    var dateTimeStr = Utilities.formatDate(dateObj, Session.getScriptTimeZone(), "MM/dd/yyyy' 'HH:mm:ss");
    var month = dateObj.toLocaleString('default', { month: 'long' });
    var year = dateObj.getFullYear().toString();

    
    balanceResult.push([month, year, dateTimeStr])
  }
  Logger.log(balanceResult)
  //Write result in balance sheet to column M (index 13 one-based) starting from row 2
  balanceSheet.getRange(2,13,balanceResult.length,balanceResult[0].length).setValues(balanceResult);
}

What it does?

  • Create an onOpen() simple trigger and call updateTransactionsSheet() and updateBalanceHistorySheet() to update the values of their respective sheets
  • In updateTransactionsSheet() . Get the current active srpeadsheet object using getActiveSpreadsheet() . Get transaction sheet object using getSheetByName(name) . Get all data range object in your transaction sheet using getDataRange() then get the values of your range using getValues() . It will return a two-dimensional array of values.
  • Loop each row (skip header row with index 0) and get the date value and the amount value in column B and column E respectively.
  • Create a JavaScript date object using your date value , use toLocalString() to get the month string of your date object. And use getFullYear() to get the year of your date object
  • Once you obtained the necessary values in your current row, add the data in the result array using array.push() . Notice that the value pushed is an array [month, year, "", amountStr] this is the current row value to be set for 4 columns (columns P to S).
  • Write the value to your sheet. Use getRange(row, column, numRows, numColumns) to get the range where you want to write your data. Since we want to right it from P2:Q, row start will be 2, column start will be 16, num of rows and num of columns will be based on the size of your result array (which is a two-dimensional array). Use setValues(values)
  • Similar process was done for updateBalanceHistorySheet()

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM