Share via


Validação de dados: listas suspensas, prompts e pop-ups de aviso

A validação de dados ajuda o usuário a garantir a consistência em uma planilha. Use esses recursos para limitar o que pode ser inserido em uma célula e fornecer avisos ou erros aos usuários quando essas condições não forem atendidas. Para saber mais sobre a validação de dados no Excel, consulte Aplicar validação de dados às células.

Criar uma lista suspensa usando a validação de dados

O exemplo a seguir cria uma lista de seleção suspensa para uma célula. Ele usa os valores existentes do intervalo selecionado como as opções para a lista.

Uma planilha mostrando um intervalo de três células que contêm opções de cores

function main(workbook: ExcelScript.Workbook) {
  // Get the values for data validation.
  const selectedRange = workbook.getSelectedRange();
  const rangeValues = selectedRange.getValues();

  // Convert the values into a comma-delimited string.
  let dataValidationListString = "";
  rangeValues.forEach((rangeValueRow) => {
    rangeValueRow.forEach((value) => {
      dataValidationListString += value + ",";
    });
  });

  // Clear the old range.
  selectedRange.clear(ExcelScript.ClearApplyTo.contents);

  // Apply the data validation to the first cell in the selected range.
  const targetCell = selectedRange.getCell(0,0);
  const dataValidation = targetCell.getDataValidation();

  // Set the content of the dropdown list.
  dataValidation.setRule({
      list: {
        inCellDropDown: true,
        source: dataValidationListString
      }
    });
}

Adicionar um prompt a um intervalo

Este exemplo cria uma nota de prompt que aparece quando um usuário insere as células fornecidas. Isso é usado para lembrar os usuários sobre os requisitos de entrada, sem uma aplicação estrita.

Um prompt com o título

/**
 * This script creates a text prompt that's shown in C2:C8 when a user enters the cell.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the data validation object for C2:C8 in the current worksheet.
    const selectedSheet = workbook.getActiveWorksheet();
    const dataValidation = selectedSheet.getRange("C2:C8").getDataValidation();

    // Clear any previous validation to avoid conflicts.
    dataValidation.clear();

    // Create a prompt to remind users to only enter first names in this column.
    const prompt: ExcelScript.DataValidationPrompt = {
      showPrompt: true,
      title: "First names only",
      message: "Only enter the first name of the employee, not the full name."
    }
    dataValidation.setPrompt(prompt);
}

Alerte o usuário quando dados inválidos são inseridos

O script de exemplo a seguir impede que o usuário insira qualquer outra coisa que não seja números positivos em um intervalo. Se eles tentarem colocar qualquer outra coisa, uma mensagem de erro aparecerá e indicará o problema.

Uma mensagem de erro com o título 'Dados inválidos' e a mensagem 'Números positivos apenas', ao lado de uma célula com um número negativo.

/**
 * This script creates a data validation rule for the range B2:B5.
 * All values in that range must be a positive number.
 * Attempts to enter other values are blocked and an error message appears.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the range B2:B5 in the active worksheet.
    const currentSheet = workbook.getActiveWorksheet();
    const positiveNumberOnlyCells = currentSheet.getRange("B2:B5");

    // Create a data validation rule to only allow positive numbers.
    const positiveNumberValidation: ExcelScript.BasicDataValidation = {
        formula1: "0",
        operator: ExcelScript.DataValidationOperator.greaterThan
    };
    const positiveNumberOnlyRule: ExcelScript.DataValidationRule = {
      wholeNumber: positiveNumberValidation
    };

    // Set the rule on the range.
    const rangeDataValidation = positiveNumberOnlyCells.getDataValidation();
    rangeDataValidation.setRule(positiveNumberOnlyRule);

    // Create an alert to appear when data other than positive numbers are entered.
    const positiveNumberOnlyAlert: ExcelScript.DataValidationErrorAlert = {
        message: "Positive numbers only.",
        showAlert: true,
        style: ExcelScript.DataValidationAlertStyle.stop,
        title: "Invalid data"
    };
    rangeDataValidation.setErrorAlert(positiveNumberOnlyAlert);
}