如果单元格中的值是日期,则运行自定义函数 [英] Run custom function if value in cell is date

查看:191
本文介绍了如果单元格中的值是日期,则运行自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Google脚本很陌生。我想检查单元格中的值是否为日期,如果是,则更改日期的默认格式,然后返回新的格式化日期值。



下面是我想要的一个例子:

  var activeCellValues = SpreadsheetApp.getActiveRange()。getValues(); 
if(activeCellValues =Is_Type_Date)
{
var activeCellValues = Utilities.formatDate(pubDateCell,PST,MM / dd / yyyy)
}

这是可能的吗?

解决方案 div>

使用下面的 isDate()函数来完成你所要求的功能。日期格式可以更改以适应其他需求。请参阅[ Utilities.formatDate()] [3]获取更多信息。

$ c> //从http://stackoverflow.com/questions/1353684
//如果变量d是日期对象,则返回'true'。
函数isValidDate(d){
if(Object.prototype.toString.call(d)!==[object Date])
return false;
return!isNaN(d.getTime());
}

//测试值是否为日期,如果是,则格式为
//否则,将输入变量反映为原样。
函数isDate(sDate){
if(isValidDate(sDate)){
sDate = Utilities.formatDate(new Date(sDate),PST,MM / dd / yyyy) ;
}
返回sDate;

$ / code>

在脚本中,您使用了 Range .getValues()函数,它将返回给定范围内数据的二维数组。 (您的整个工作表,您的情况。)因此,您需要循环读取值并在您感兴趣的任何单元上调用此函数,然后将信息写回电子表格。在Google的文档和Stackoverflow中有很多这方面的例子。


I am new to Google scripting. I would like to check if the value in a cell is a date, and if so, to change the default format of the date, and then return the new formatted date value.

Here is an example of what I would like:

var activeCellValues = SpreadsheetApp.getActiveRange().getValues();
if ( activeCellValues = "Is_Type_Date")
       {   
          var activeCellValues = Utilities.formatDate(pubDateCell,"PST", "MM/dd/yyyy")
       }

Is this possible?

解决方案

Use the isDate() function, below, to do what you're asking. The date format can be changed to suit other needs. Refer to [Utilities.formatDate()][3] for more info.

// From http://stackoverflow.com/questions/1353684
// Returns 'true' if variable d is a date object.
function isValidDate(d) {
  if ( Object.prototype.toString.call(d) !== "[object Date]" )
    return false;
  return !isNaN(d.getTime());
}

// Test if value is a date and if so format
// otherwise, reflect input variable back as-is. 
function isDate(sDate) {
  if (isValidDate(sDate)) {
    sDate = Utilities.formatDate(new Date(sDate), "PST", "MM/dd/yyyy");
  }
  return sDate;
}

In your script, you've used the Range.getValues() function, which will return a two-dimensional array of the data in the given range. (Your whole sheet, in your case.) You will therefore need to loop over the read values and call this function on any cell that you're interested in, and then write the information back out to the spreadsheet. There are plenty of examples of this both in Google's documentation and on Stackoverflow.

这篇关于如果单元格中的值是日期,则运行自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆