写google Javascript类似于vlookup

use*_*629 6 javascript for-loop google-sheets google-apps-script

ColumnA ColumnB
jhinz    115
tom      116 
Run Code Online (Sandbox Code Playgroud)

这段代码背后的想法是有人输入一个数字(比方说116),计算机在B列中查找并返回A列中的名称(tom)

我需要帮助代码的唯一部分是计算机在第116列中查找值.

我试图用嵌套的if语句做一个for循环,但它没有用.有人能帮助我吗?

Ser*_*sas 16

以最简单的形式,看看你可以尝试的工作原理:

function findinB() {
  var sh = SpreadsheetApp.getActiveSheet();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var last=ss.getLastRow();
  var data=sh.getRange(1,1,last,2).getValues();// create an array of data from columns A and B
  var valB=Browser.inputBox('Enter value to search in B')
  for(nn=0;nn<data.length;++nn){
    if (data[nn][1]==valB){break} ;// if a match in column B is found, break the loop
      }
Browser.msgBox(data[nn][0]);// show column A
}
Run Code Online (Sandbox Code Playgroud)


Dro*_*ror 5

我发现@Serge的功能可以稍微模块化一些,可能值得分享。

/*
Imitates the Vlookup function. Receives:
1. sheet - A reference to the sheet you would like to run Vlookup on
2. column - The number of the column the lookup should begin from
3. index - The number of columns the lookup should cover.
4. value - The desired value to look for in the column.
Once the cell of the [value] has been found, the returned parameter would be the value of the cell which is [index] cells to the right of the found cell.
*/
function vlookup(sheet, column, index, value) {

  var lastRow=sheet.getLastRow();
  var data=sheet.getRange(1,column,lastRow,column+index).getValues();

  for(i=0;i<data.length;++i){
    if (data[i][0]==value){
      return data[i][index];
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

任何建议或改进表示赞赏。这也可能是一个开始回购缺少的急需的Google Sheet API函数的好机会。我开始了一个新的仓库,有一天它可能会变得更有用,如果您打算贡献自己的定制功能,请不要犹豫。

干杯!