You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求问:是否存在与DSUM公式功能类似的Google Apps Script脚本?

在Google Apps Script中实现类似DSUM的多条件求和

自定义DSUM替代函数

你可以直接编写自定义函数模拟DSUM的多条件求和逻辑,以下是一个实用的示例:

function customDSUM(dataRange, criteriaRange) {
  const dataValues = SpreadsheetApp.getActiveSpreadsheet().getRange(dataRange).getValues();
  const criteriaValues = SpreadsheetApp.getActiveSpreadsheet().getRange(criteriaRange).getValues();
  
  // 提取条件列名和对应的条件规则
  const criteriaHeaders = criteriaValues[0];
  const criteriaRules = criteriaValues.slice(1).filter(row => row.some(cell => cell !== ""));
  
  // 获取数据列名索引映射
  const dataHeaderIndex = dataValues[0].reduce((map, header, index) => {
    map[header] = index;
    return map;
  }, {});
  
  let total = 0;
  
  // 遍历数据行(跳过表头)
  for (let i = 1; i < dataValues.length; i++) {
    const row = dataValues[i];
    let matchesAllCriteria = true;
    
    // 检查是否匹配所有条件规则
    for (const rule of criteriaRules) {
      let matchesRule = false;
      
      for (let j = 0; j < criteriaHeaders.length; j++) {
        const header = criteriaHeaders[j];
        const criteria = rule[j];
        
        if (!criteria || !dataHeaderIndex.hasOwnProperty(header)) continue;
        
        const cellValue = row[dataHeaderIndex[header]];
        
        // 处理不同类型的条件匹配(文本、数字、日期)
        if (typeof criteria === 'string') {
          // 支持通配符:* 匹配任意字符,? 匹配单个字符
          const regexPattern = criteria.replace(/\*/g, '.*').replace(/\?/g, '.');
          matchesRule = new RegExp(`^${regexPattern}$`, 'i').test(cellValue);
        } else if (typeof criteria === 'number' || criteria instanceof Date) {
          matchesRule = cellValue === criteria;
        }
        
        if (matchesRule) break;
      }
      
      if (!matchesRule) {
        matchesAllCriteria = false;
        break;
      }
    }
    
    // 如果匹配所有条件,累加最后一列的值(DSUM默认求和列为数据范围最后一列)
    if (matchesAllCriteria) {
      total += typeof row[row.length - 1] === 'number' ? row[row.length - 1] : 0;
    }
  }
  
  return total;
}

使用方式和原生DSUM类似:在单元格中输入=customDSUM("A1:D100", "F1:H3"),第一个参数是包含表头的数据范围,第二个是包含表头和条件规则的条件范围。

参考资源

  • YouTube视频:
    • "Google Apps Script: Build a Custom DSUM Function"(讲解自定义函数实现逻辑,涵盖条件匹配和数据遍历)
    • "Advanced Google Sheets with Apps Script: Replace Formulas with Scripts"(对比原生公式和脚本实现,包含多条件求和场景)
  • Google官方文档:
    • Apps Script的Range.getValues()方法说明(掌握数据读取的核心操作)
    • 自定义函数开发指南(了解如何在表格中调用脚本函数)

内容的提问来源于stack exchange,提问作者Ardi Entdecker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:54:21