对文件夹中的所有 Excel 文件运行脚本

此项目对位于 OneDrive for Business 文件夹中的所有文件执行一组自动化任务。 它还可用于 SharePoint 文件夹。 它会对 Excel 文件执行计算、添加格式并插入 @mentions 同事的注释。

示例 Excel 文件

下载 此示例 所需的所有工作簿的highlight-alert-excel-files.zip。 将这些文件提取到标题为 “Sales”的文件夹。 将以下脚本添加到脚本集合,以亲自尝试示例!

示例代码:添加格式并插入注释

这是在每个单独的工作簿上运行的脚本。 在 Excel 中,使用 “自动化>新脚本” 粘贴代码并保存脚本。 将其保存为 “审阅”脚本 ,并亲自尝试该示例!

function main(workbook: ExcelScript.Workbook) {
  // Get the table named "Table1" in the workbook.
  const table1 = workbook.getTable("Table1");

  // If the table is empty, end the script.
  const rowCount = table1.getRowCount();
  if (rowCount === 0) {
    return;
  }

  // Force the workbook to be completely recalculated.
  workbook.getApplication().calculate(ExcelScript.CalculationType.full);

  // Get the "Amount Due" column from the table.
  const amountDueColumn = table1.getColumnByName('Amount Due');
  const amountDueValues = amountDueColumn.getRangeBetweenHeaderAndTotal().getValues();

  // Find the highest amount that's due.
  let highestValue = amountDueValues[0][0];
  let row = 0;
  for (let i = 1; i < amountDueValues.length; i++) {
    if (amountDueValues[i][0] > highestValue) {
      highestValue = amountDueValues[i][0];
      row = i;
    }
  }

  let highestAmountDue = table1.getColumn("Amount due").getRangeBetweenHeaderAndTotal().getRow(row);

  // Set the fill color to yellow for the cell with the highest value in the "Amount Due" column.
  highestAmountDue.getFormat().getFill().setColor("FFFF00");

  // Insert an @mention comment in the cell.
  workbook.addComment(highestAmountDue, {
    mentions: [{
      email: "AdeleV@M365x904181.OnMicrosoft.com",
      id: 0,
      name: "Adele Vance"
    }],
    richContent: "<at id=\"0\">Adele Vance</at> Please review this amount"
  }, ExcelScript.ContentType.mention);
}

Power Automate 流:在文件夹中的每个工作簿上运行脚本

此流在“Sales”文件夹中的每个工作簿上运行脚本。

  1. 创建新的 即时云流

  2. 选择 “手动触发流 ”,然后选择“ 创建”。

  3. 在流生成器中 + ,选择按钮和 “添加操作”。 使用OneDrive for Business连接器的“在文件夹中列出文件”操作。 对操作使用以下值。

    • 文件夹:文件选取器) 选择/Sales (

    Power Automate 中已完成的OneDrive for Business连接器。

  4. 确保仅选择了工作簿。 添加新 的“条件” 控件操作。 对条件使用以下值。

    • 选择一个值名称 (文件夹中 ) 列出文件动态内容
    • 结尾为:下拉列表中的 ()
    • 选择值:.xlsx

    将后续操作应用于每个文件的 Power Automate 条件块。

  5. True 分支下,添加新操作。 选择 Excel Online (Business) 连接器的 “运行脚本 ”操作。 对操作使用以下值。

    • 位置:OneDrive for Business
    • 文档库:OneDrive
    • 文件:id (文件夹) 中列出文件的动态内容
    • 脚本:查看脚本

    Power Automate 中已完成的 Excel Online (Business) 连接器。

  6. 保存流。 流设计器应如下图所示。

    已完成流的关系图,其中显示了条件前的两个步骤和条件的真实路径下一个步骤。

  7. 尝试一下! 使用流编辑器页上的“ 测试 ”按钮,或通过“我的流”选项卡运行 。请务必在出现提示时允许访问。

培训视频:对文件夹中的所有 Excel 文件运行脚本

观看 Sudhi Ramamurthy 在 YouTube 上演练此示例