Share via


Validación de datos: listas desplegables, mensajes y elementos emergentes de advertencia

La validación de datos ayuda al usuario a garantizar la coherencia en una hoja de cálculo. Use estas características para limitar lo que se puede escribir en una celda y proporcionar advertencias o errores a los usuarios cuando no se cumplan esas condiciones. Para obtener más información sobre la validación de datos en Excel, vea Aplicar validación de datos a celdas.

Creación de una lista desplegable mediante la validación de datos

En el ejemplo siguiente se crea una lista desplegable de selección para una celda. Usa los valores existentes del intervalo seleccionado como las opciones de la lista.

Hoja de cálculo que muestra un rango de tres celdas que contienen las opciones de color

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
      }
    });
}

Adición de un símbolo del sistema a un intervalo

En este ejemplo se crea una nota de aviso que aparece cuando un usuario entra en las celdas especificadas. Esto se usa para recordar a los usuarios los requisitos de entrada, sin una aplicación estricta.

Un mensaje con el 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);
}

Alerta al usuario cuando se escriben datos no válidos

El siguiente script de ejemplo impide que el usuario escriba cualquier cosa que no sea números positivos en un intervalo. Si intentan colocar cualquier otra cosa, aparece un mensaje de error que indica el problema.

Mensaje de error con el título

/**
 * 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);
}