Partilhar via


Cenário de exemplo de Scripts do Office: botão Desatar relógio

A ideia de cenário e o script usados neste exemplo foram contribuídos pelo membro da comunidade do Office Scripts , Brian Gonzalez.

Nesse cenário, você criará uma folha de tempo para um funcionário que permite que eles registrem seus horários de início e término com um botão. Com base no que foi gravado anteriormente, selecionar o botão iniciará seu dia (relógio) ou terminará seu dia (relógio).

Uma tabela com três colunas ('Clock In', 'Clock Out' e 'Duration') e um botão rotulado como 'Relógio de soco' na pasta de trabalho.

Instruções de instalação

  1. Baixe a pasta de trabalho de exemplo para o OneDrive.

    Uma tabela com três colunas: 'Clock In', 'Clock Out' e 'Duration'.

  2. Abra a pasta de trabalho no Excel.

  3. Na guia Automatizar, selecioneNovo Script e cole o script a seguir no editor.

    /**
     * This script records either the start or end time of a shift, 
     * depending on what is filled out in the table. 
     * It is intended to be used with a Script Button.
     */
    function main(workbook: ExcelScript.Workbook) {
      // Get the first table in the timesheet.
      const timeSheet = workbook.getWorksheet("MyTimeSheet");
      const timeTable = timeSheet.getTables()[0];
    
      // Get the appropriate table columns.
      const clockInColumn = timeTable.getColumnByName("Clock In");
      const clockOutColumn = timeTable.getColumnByName("Clock Out");
      const durationColumn = timeTable.getColumnByName("Duration");
    
      // Get the last rows for the Clock In and Clock Out columns.
      let clockInLastRow = clockInColumn.getRangeBetweenHeaderAndTotal().getLastRow();
      let clockOutLastRow = clockOutColumn.getRangeBetweenHeaderAndTotal().getLastRow();
    
      // Get the current date to use as the start or end time.
      let date: Date = new Date();
    
      // Add the current time to a column based on the state of the table.
      if (clockInLastRow.getValue() as string === "") {
        // If the Clock In column has an empty value in the table, add a start time.
        clockInLastRow.setValue(date.toLocaleString());
      } else if (clockOutLastRow.getValue() as string === "") {
        // If the Clock Out column has an empty value in the table, 
        // add an end time and calculate the shift duration.
        clockOutLastRow.setValue(date.toLocaleString());
        const clockInTime = new Date(clockInLastRow.getValue() as string);
        const clockOutTime  = new Date(clockOutLastRow.getValue() as string);
        const clockDuration = Math.abs((clockOutTime.getTime() - clockInTime.getTime()));
    
        let durationString = getDurationMessage(clockDuration);
        durationColumn.getRangeBetweenHeaderAndTotal().getLastRow().setValue(durationString);
      } else {
        // If both columns are full, add a new row, then add a start time.
        timeTable.addRow()
        clockInLastRow.getOffsetRange(1, 0).setValue(date.toLocaleString());
      }
    }
    
    /**
     * A function to write a time duration as a string.
     */
    function getDurationMessage(delta: number) {
      // Adapted from here:
      // https://stackoverflow.com/questions/13903897/javascript-return-number-of-days-hours-minutes-seconds-between-two-dates
    
      delta = delta / 1000;
      let durationString = "";
    
      let days = Math.floor(delta / 86400);
      delta -= days * 86400;
    
      let hours = Math.floor(delta / 3600) % 24;
      delta -= hours * 3600;
    
      let minutes = Math.floor(delta / 60) % 60;
    
      if (days >= 1) {
        durationString += days;
        durationString += (days > 1 ? " days" : " day");
    
        if (hours >= 1 && minutes >= 1) {
          durationString += ", ";
        }
        else if (hours >= 1 || minutes > 1) {
          durationString += " and ";
        }
      }
    
      if (hours >= 1) {
        durationString += hours;
        durationString += (hours > 1 ? " hours" : " hour");
        if (minutes >= 1) {
          durationString += " and ";
        }
      }
    
      if (minutes >= 1) {
        durationString += minutes;
        durationString += (minutes > 1 ? " minutes" : " minute");
      }
    
      return durationString;
    }
    
  4. Renomeie o script como "Relógio de perfuração".

  5. Salve o script.

  6. Na pasta de trabalho, selecione célula E2.

  7. Adicione um botão script. Acesse o menu Mais opções (...) na página Detalhes do script e selecione Adicionar na pasta de trabalho.

  8. Salve a pasta de trabalho.

Executar o script

Selecione o botão Socar o relógio para executar o script. Ele registra o tempo atual em "Clock In" ou "Clock Out", dependendo do que foi inserido anteriormente.

A tabela e o botão

Observação

A duração só será registrada se for maior que um minuto. Edite manualmente o tempo "Clock In" para testar durações maiores.