以编程方式添加时间戳

时间:2016-07-28 01:15:57

标签: javascript google-apps-script google-sheets

我正在尝试为Google Spreadsheets创建代码。在VBA代码中它非常简单。我的目标是,当一个特定的单元格被填满时,另一个单元格显示完成的日期和时间。

在VBA中:

Function DateTime()
  DateTime = NOW
End Function

2 个答案:

答案 0 :(得分:1)

根据您最近的评论,说明您要从Google工作表前端拨打custom function,您在脚本编辑器(后端)中需要的只是:

<Style TargetType="{x:Type ToggleButton}" x:Key="ListToggleButton">
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />
    <Setter Property="Foreground" Value="#FF232A2E"/>
    <Setter Property="Background" Value="White"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ToggleButton}">
                <Border x:Name="ButtonBorder" Background="{TemplateBinding Background}" BorderBrush="#FFECECEC" BorderThickness="0,0,0,1">
                    <Grid>
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
                    </Grid>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="False">
                        <Setter Property="Background" Value="#FF232A2E"/>
                        <Setter Property="BorderBrush" Value="#FFECECEC" TargetName="ButtonBorder"/>
                        <Setter Property="BorderThickness" Value="0,0,0,1" TargetName="ButtonBorder"/>
                    </Trigger>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Background" Value="#FFF5F5F5"/>
                        <Setter Property="BorderBrush" Value="#FF25a0da" TargetName="ButtonBorder"/>
                        <Setter Property="BorderThickness" Value="0,0,0,2" TargetName="ButtonBorder"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

然后,您可以从工作表中的公式调用该函数,这与您已编写的内容非常相似:

function timeStamp() {
  return new Date();
}

答案 1 :(得分:0)

这段代码将帮助您摆脱想要实现的目标。

下面的代码会在您输入值的任何字段的下一列中添加日期。

//onEdit is the default "on edit event handler" provided by google app script
function onEdit(e){
  var spreadSheet = e.source;
  var sheet = spreadSheet.getActiveSheet();
  var range = e.range;
  //only add the date in the next column if value in cell is not empty
  if(range.getValue() != ""){
    var col = range.getColumn();
    var row = range.getRow();
    //get the very next column
    var newRange = sheet.getRange(row, col + 1);
    newRange.setValue(new Date());
  }
}

希望这会有所帮助。

注意: 请注意,此代码仅适用于scripts bound to google apps