Google电子表格脚本帮助 - 列循环

时间:2014-09-21 06:30:41

标签: google-apps-script google-sheets

我有一个脚本,其中包含电子邮件地址,角色和群组电子邮件地址,并将其添加到Google Apps群组。我目前只在一排工作。如何在没有针对所有这些行的单独脚本的情况下使其适用于许多(即25个)行?脚本列在这里:

function addGroupMember() {
  var userEmail = getUser();
  var groupEmail = getGroup();
  var member = {
   email: userEmail,
   role: getRole()
  };
  member = AdminDirectory.Members.insert(member, groupEmail);
  Logger.log('User %s added as a member of group %s.', userEmail, groupEmail);
  }

function getUser() {
  user = SpreadsheetApp.getActiveSheet().getRange('A2').getValue();
  return user }

function getRole() {
  role = SpreadsheetApp.getActiveSheet().getRange('B2').getValue();
  return role }

function getGroup() {
  group = SpreadsheetApp.getActiveSheet().getRange('A27').getValue();
  return group }

感谢您的帮助!

-Joe

1 个答案:

答案 0 :(得分:0)

不要对getWhatever()函数中的单元格值进行硬编码,而是使用可循环的参数。例如:

function getUser(row) {
  // "User" is in column A, aka column 1
  user = SpreadsheetApp.getActiveSheet().getRange(row,1).getValue();
  return user }

看起来getGroup保持原样,因为每个用户都在同一个群组中。

参数化addGroupMember功能:

function addGroupMember(row) {
  var userEmail = getUser(row);
  var groupEmail = getGroup(row);
  var member = {
   email: userEmail,
   role: getRole()
  };
  member = AdminDirectory.Members.insert(member, groupEmail);
  Logger.log('User %s added as a member of group %s.', userEmail, groupEmail);
  }

然后你可以这样做:

function addAll() {
  // assume users in rows 2 - 26, since you may have headers, and row 27 has group
  for (var row=2; row<=26; row++) {
    addGroupMember(row);
  }
}

此处仍需要大量改进,主要是出于性能原因。