首页 > 解决方案 > 如何将特定单元格与列范围进行比较并返回与列范围关联的字符串?

问题描述

感谢您阅读我的第一个问题。我刚开始使用谷歌表格,请多多包涵。 这是我正在使用的工作表

因此,如果对于我玩的游戏,我们会根据功率等级分配公会攻击。我正在寻找创建一个函数或脚本并将其放在 O 列中。我希望此函数将 F 列与 M 列中的特定单元格进行比较,然后返回与 F 列关联的用户,该用户 >= 比特定的M列中的单元格。像这样在此处输入图像描述, 我将前三个突出显示为示例。

我显然可以手动执行此操作,但我需要时间,并且希望使此过程自动化,以提高效率。我尝试过 Vlookups、MATCH、IF,但都没有成功。任何帮助将不胜感激。再说一次,我只是一个使用谷歌表格的初学者,所以请放轻松。:)

标签: google-sheetsgoogle-sheets-formulagoogle-sheets-querygoogle-sheets-macros

解决方案


解决方案

正如您提到的,您也会对脚本解决方案感到满意,我创建了这个脚本,我相信它可以解决您的问题。它有评论逐步解释它是如何工作的:

function myFunction() {
  // Get our sheet
  var ss = SpreadsheetApp.getActive().getSheetByName('Automate Test');
  
  // Get the values of the ranges of F and M. Flat will convert the 2D array we get from getValues() into a 1D one which is easier to work with
  var valuesF = ss.getRange('F2:F16').getValues().flat();
  var valuesD = ss.getRange('D2:D16').getValues().flat();
  var valuesM = ss.getRange('M2:M16').getValues().flat();
  var valuesN = ss.getRange('N17:N31').getValues().flat();
  
  
  // We will iterate through all the players in column M to find their opponents
  for(i=0;i<valuesM.length;i++){
    // We create an empty array to be filled with the list of possible opponents to then choose a random one of the list
    var playersHigherEqual = [];
    
    // Iterate through the opponent list
    for(j=0;j<valuesF.length;j++){
      // If the opponent meets the condition
      if(valuesF[j]>= valuesM[i]){
        // Add it to the array of possible opponents
        playersHigherEqual.push(ss.getRange(j+2, 2).getValue());
      }
    }
    
    //Finally we will set the opponent by choosing a random one out of the list. Note that i+2 is because the arrays start from 0
    ss.getRange(i+2, 15).setValue(playersHigherEqual[Math.floor(Math.random()*playersHigherEqual.length)]);
  }
  
  
  // We will iterate through all the players in column M to find their opponents
  for(i=0;i<valuesN.length;i++){
    // We create an empty array to be filled with the list of possible opponents to then choose a random one of the list
    var playersHigherEqual = [];
    
    // Iterate through the opponent list
    for(j=0;j<valuesD.length;j++){
      // If the opponent meets the condition
      if(valuesD[j]>= valuesN[i]){
        // Add it to the array of possible opponents
        playersHigherEqual.push(ss.getRange(j+2, 2).getValue());
      }
    }
    
    //Finally we will set the opponent by choosing a random one out of the list. Note that i+2 is because the arrays start from 0
    ss.getRange(i+17, 15).setValue(playersHigherEqual[Math.floor(Math.random()*playersHigherEqual.length)]);
  }  
  
}

如果您还需要此问题的表格公式解决方案,请告诉我。有关 Apps 脚本的更多信息,请查看文档

我希望这对你有所帮助。让我知道您是否需要其他任何内容,或者您​​是否不理解某些内容。:)


推荐阅读