Tabellenbeispiele

In diesen Beispielen werden allgemeine Interaktionen mit Excel-Tabellen veranschaulicht.

Erstellen einer sortierten Tabelle

In diesem Beispiel wird eine Tabelle aus dem verwendeten Bereich des aktuellen Arbeitsblatts erstellt und dann basierend auf der ersten Spalte sortiert.

function main(workbook: ExcelScript.Workbook) {
  // Get the current worksheet.
  const selectedSheet = workbook.getActiveWorksheet();

  // Create a table with the used cells.
  const usedRange = selectedSheet.getUsedRange();
  const newTable = selectedSheet.addTable(usedRange, true);

  // Sort the table using the first column.
  newTable.getSort().apply([{ key: 0, ascending: true }]);
}

Filtern einer Tabelle

In diesem Beispiel wird eine vorhandene Tabelle anhand der Werte in einer der Spalten gefiltert.

function main(workbook: ExcelScript.Workbook) {
  // Get the table in the workbook named "StationTable".
  const table = workbook.getTable("StationTable");

  // Get the "Station" table column for the filter.
  const stationColumn = table.getColumnByName("Station");

  // Apply a filter to the table that will only show rows 
  // with a value of "Station-1" in the "Station" column.
  stationColumn.getFilter().applyValuesFilter(["Station-1"]);
}

Tipp

Kopieren Sie die gefilterten Informationen mithilfe von Range.copyFromin der Arbeitsmappe. Fügen Sie am Ende des Skripts die folgende Zeile hinzu, um ein neues Arbeitsblatt mit den gefilterten Daten zu erstellen.

  workbook.addWorksheet().getRange("A1").copyFrom(table.getRange());

Einen Wert herausfiltern

Im vorherigen Beispiel wird eine Tabelle basierend auf einer Liste der enthaltenen Werte gefiltert. Um einen bestimmten Wert aus der Tabelle auszuschließen, müssen Sie die Liste aller anderen Werte in der Spalte angeben. In diesem Beispiel wird eine -Funktion columnToSet verwendet, um eine Spalte in einen Satz eindeutiger Werte zu konvertieren. Dieser Satz hat dann den ausgeschlossenen Wert ("Station-1") entfernt.

function main(workbook: ExcelScript.Workbook) {
  // Get the table in the workbook named "StationTable".
  const table = workbook.getTable("StationTable");

  // Get the "Station" table column for the filter.
  const stationColumn = table.getColumnByName("Station");

  // Get a list of unique values in the station column.
  const stationSet = columnToSet(stationColumn);

  // Apply a filter to the table that will only show rows
  // that don't have a value of "Station-1" in the "Station" column. 
  stationColumn.getFilter().applyValuesFilter(stationSet.filter((value) => {
      return value !== "Station-1";
  }));
}

/**
 * Convert a column into a set so it only contains unique values.
 */
function columnToSet(column: ExcelScript.TableColumn): string[] {
    const range = column.getRangeBetweenHeaderAndTotal().getValues() as string[][];
    const columnSet: string[] = [];
    range.forEach((value) => {
        if (!columnSet.includes(value[0])) {
            columnSet.push(value[0]);
        }
    });

    return columnSet;
}

Tabellenspaltenfilter entfernen

In diesem Beispiel werden die Filter basierend auf der position der aktiven Zelle aus einer Tabellenspalte entfernt. Das Skript erkennt, ob die Zelle Teil einer Tabelle ist, bestimmt die Tabellenspalte und löscht alle Filter, die darauf angewendet werden.

Laden Sie table-with-filter.xlsx für eine einsatzbereite Arbeitsmappe herunter. Fügen Sie das folgende Skript hinzu, um das Beispiel selbst auszuprobieren!

function main(workbook: ExcelScript.Workbook) {
  // Get the active cell.
  const cell = workbook.getActiveCell();

  // Get the tables associated with that cell.
  // Since tables can't overlap, this will be one table at most.
  const currentTable = cell.getTables()[0];

  // If there's no table on the selection, end the script.
  if (!currentTable) {
    console.log("The selection is not in a table.");
    return;
  }

  // Get the table header above the current cell by referencing its column.
  const entireColumn = cell.getEntireColumn();
  const intersect = entireColumn.getIntersection(currentTable.getRange());
  const headerCellValue = intersect.getCell(0, 0).getValue() as string;

  // Get the TableColumn object matching that header.
  const tableColumn = currentTable.getColumnByName(headerCellValue);

  // Clear the filters on that table column.
  tableColumn.getFilter().clear();
}

Vor dem Löschen des Spaltenfilters (beachten Sie die aktive Zelle)

Eine aktive Zelle vor dem Löschen des Spaltenfilters.

Nach dem Löschen des Spaltenfilters

Eine aktive Zelle nach dem Löschen des Spaltenfilters.

Tipp

Wenn Sie mehr darüber erfahren möchten, wie Sie den Filter vor dem Löschen speichern (und später erneut anwenden), lesen Sie Verschieben von Zeilen über Tabellen durch Speichern von Filtern, ein erweitertes Beispiel.

Dynamischer Verweis auf Tabellenwerte

Dieses Skript verwendet die Syntax "@COLUMN_NAME", um Formeln in einer Tabellenspalte festzulegen. Die Spaltennamen in der Tabelle können ohne Änderung dieses Skripts geändert werden.

function main(workbook: ExcelScript.Workbook) {
  // Get the current worksheet.
  const table = workbook.getTable("Profits");

  // Get the column names for columns 2 and 3.
  // Note that these are 1-based indices.
  const nameOfColumn2 = table.getColumn(2).getName();
  const nameOfColumn3 = table.getColumn(3).getName();

  // Set the formula of the fourth column to be the product of the values found
  // in that row's second and third columns.
  const combinedColumn = table.getColumn(4).getRangeBetweenHeaderAndTotal();
  combinedColumn.setFormula(`=[@[${nameOfColumn2}]]*[@[${nameOfColumn3}]]`);
}

Vor dem Skript

Monat Kurs Verkaufte Einheiten Gesamt
Jan 45 5
Februar 45 3
Mrz 45 6

Nach dem Skript

Monat Kurs Verkaufte Einheiten Gesamt
Jan 45 5 225
Februar 45 3 135
Mrz 45 6 270