0% found this document useful (0 votes)
104 views1,341 pages

Javascript API Office Scripts Office Scripts

The Office Scripts API reference provides documentation for automating tasks in Excel using scripts. It outlines the object model, including common classes such as Workbook, Worksheet, and Range, and their relationships. Additionally, it includes details on various interfaces and enums related to Excel scripting functionalities.

Uploaded by

Gabo Moreno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views1,341 pages

Javascript API Office Scripts Office Scripts

The Office Scripts API reference provides documentation for automating tasks in Excel using scripts. It outlines the object model, including common classes such as Workbook, Worksheet, and Range, and their relationships. Additionally, it includes details on various interfaces and enums related to Excel scripting functionalities.

Uploaded by

Gabo Moreno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1341

Tell us about your PDF experience.

Office Scripts API reference


Article • 02/14/2023

The Office Scripts API lets you automate common tasks in Excel. Use this reference
documentation to learn more about the classes, methods, and other types available for
your scripts. All the objects accessible through Office Scripts can be found in the table of
contents on the left of the page.

7 Note

If you're looking for the JavaScript APIs for developing Office Add-ins, visit the
Office Add-ins JavaScript API reference.

Common classes
The following list breaks down the basics of the Office Scripts object model. This shows
the common classes and how they relate to one another.

A Workbook contains one or more Worksheets.


A Worksheet gives access to cells through Range objects.
A Range represents a group of contiguous cells.
Ranges are used to create and place Tables, Charts, Shapes, and other data
visualization or organization objects.
A Worksheet contains arrays filled with those objects that are present in the
individual sheet.
A Workbook contains arrays of some of those data objects for the entire
Workbook.

For more information about the Office Scripts object model, visit Fundamentals for
Office Scripts in Excel

See also
About Office Scripts
Record, edit, and create Office Scripts in Excel
Fundamentals for Office Scripts in Excel
ExcelScript package
Reference

Interfaces
ノ Expand table

ExcelScript.Allow Represents an AllowEditRange object found in a worksheet. This object works


EditRange with worksheet protection properties. When worksheet protection is enabled,
an AllowEditRange object can be used to allow editing of a specific range,
while maintaining protection on the rest of the worksheet.

ExcelScript.Allow The interface used to construct optional fields of the AllowEditRange object.
EditRangeOptions

ExcelScript. Represents the Excel application that manages the workbook.


Application

ExcelScript.Auto Represents the AutoFilter object. AutoFilter turns the values in Excel column
Filter into specific filters based on the cell contents.

ExcelScript.Basic Represents the basic type data validation criteria.


DataValidation

ExcelScript. Represents an Office.js binding that is defined in the workbook.


Binding

ExcelScript.Cell Represents a cell value conditional format.


ValueConditional
Format

ExcelScript.Chart Represents a chart object in a workbook.

ExcelScript.Chart Encapsulates the format properties for the overall chart area.
AreaFormat

ExcelScript.Chart Represents the chart axes.


Axes

ExcelScript.Chart Represents a single axis in a chart.


Axis

ExcelScript.Chart Encapsulates the format properties for the chart axis.


AxisFormat

ExcelScript.Chart Represents the title of a chart axis.


AxisTitle
ExcelScript.Chart Represents the chart axis title formatting.
AxisTitleFormat

ExcelScript.Chart Encapsulates the bin options for histogram charts and pareto charts.
BinOptions

ExcelScript.Chart Represents the border formatting of a chart element.


Border

ExcelScript.Chart Represents the properties of a box and whisker chart.


Boxwhisker
Options

ExcelScript.Chart Represents the data label of a chart point.


DataLabel

ExcelScript.Chart Encapsulates the format properties for the chart data labels.
DataLabelFormat

ExcelScript.Chart Represents a collection of all the data labels on a chart point.


DataLabels

ExcelScript.Chart Represents the data table object of a chart.


DataTable

ExcelScript.Chart Represents the format of a chart data table.


DataTableFormat

ExcelScript.Chart This object represents the attributes for a chart's error bars.
ErrorBars

ExcelScript.Chart Encapsulates the format properties for chart error bars.


ErrorBarsFormat

ExcelScript.Chart Represents the fill formatting for a chart element.


Fill

ExcelScript.Chart This object represents the font attributes (such as font name, font size, and
Font color) for a chart object.

ExcelScript.Chart Represents the substring in chart related objects that contain text, like a
FormatString ChartTitle object or ChartAxisTitle object.

ExcelScript.Chart Represents major or minor gridlines on a chart axis.


Gridlines

ExcelScript.Chart Encapsulates the format properties for chart gridlines.


GridlinesFormat

ExcelScript.Chart Represents the legend in a chart.


Legend
ExcelScript.Chart Represents the legend entry in legendEntryCollection .
LegendEntry

ExcelScript.Chart Encapsulates the format properties of a chart legend.


LegendFormat

ExcelScript.Chart Encapsulates the formatting options for line elements.


LineFormat

ExcelScript.Chart Encapsulates the properties for a region map chart.


MapOptions

ExcelScript.Chart Encapsulates the options for the pivot chart.


PivotOptions

ExcelScript.Chart This object represents the attributes for a chart plot area.
PlotArea

ExcelScript.Chart Represents the format properties for a chart plot area.


PlotAreaFormat

ExcelScript.Chart Represents a point of a series in a chart.


Point

ExcelScript.Chart Represents the formatting object for chart points.


PointFormat

ExcelScript.Chart Represents a series in a chart.


Series

ExcelScript.Chart Encapsulates the format properties for the chart series


SeriesFormat

ExcelScript.Chart Represents a chart title object of a chart.


Title

ExcelScript.Chart Provides access to the formatting options for a chart title.


TitleFormat

ExcelScript.Chart This object represents the attributes for a chart trendline object.
Trendline

ExcelScript.Chart Represents the format properties for the chart trendline.


TrendlineFormat

ExcelScript.Chart This object represents the attributes for a chart trendline label object.
TrendlineLabel

ExcelScript.Chart Encapsulates the format properties for the chart trendline label.
TrendlineLabel
Format
ExcelScript.Color Represents the color scale criteria for conditional formatting.
ScaleConditional
Format

ExcelScript. Represents a comment in the workbook.


Comment

ExcelScript. Represents the entity that is mentioned in comments.


Comment
Mention

ExcelScript. Represents a comment reply in the workbook.


CommentReply

ExcelScript. Represents the content contained within a comment or comment reply. Rich
CommentRich content incudes the text string and any other objects contained within the
Content comment body, such as mentions.

ExcelScript. Represents a cell value conditional format rule.


ConditionalCell
ValueRule

ExcelScript. Represents the criteria of the color scale.


ConditionalColor
ScaleCriteria

ExcelScript. Represents a color scale criterion which contains a type, value, and a color.
ConditionalColor
ScaleCriterion

ExcelScript. Represents a conditional format for the negative side of the data bar.
ConditionalData
BarNegative
Format

ExcelScript. Represents a conditional format for the positive side of the data bar.
ConditionalData
BarPositiveFormat

ExcelScript. Represents a rule-type for a data bar.


ConditionalData
BarRule

ExcelScript. An object encapsulating a conditional format's range, format, rule, and other
Conditional properties.
Format

ExcelScript. Represents a rule, for all traditional rule/format pairings.


Conditional
FormatRule
ExcelScript. Represents an icon criterion which contains a type, value, an operator, and an
ConditionalIcon optional custom icon, if not using an icon set.
Criterion

ExcelScript. Represents the preset criteria conditional format rule.


ConditionalPreset
CriteriaRule

ExcelScript. Represents the border of an object.


ConditionalRange
Border

ExcelScript. Represents the background of a conditional range object.


ConditionalRange
Fill

ExcelScript. This object represents the font attributes (font style, color, etc.) for an object.
ConditionalRange
Font

ExcelScript. A format object encapsulating the conditional formats range's font, fill,
ConditionalRange borders, and other properties.
Format

ExcelScript. Represents a cell value conditional format rule.


ConditionalText
ComparisonRule

ExcelScript. Represents the rule of the top/bottom conditional format.


ConditionalTop
BottomRule

ExcelScript. Provides information based on current system culture settings. This includes
CultureInfo the culture names, number formatting, and other culturally dependent
settings.

ExcelScript. Represents a custom conditional format type.


Custom
Conditional
Format

ExcelScript. Represents the custom data validation criteria.


CustomData
Validation

ExcelScript. Represents a custom property.


CustomProperty

ExcelScript. Represents a custom XML part object in a workbook.


CustomXmlPart
ExcelScript.Data Represents an Excel conditional data bar type.
BarConditional
Format

ExcelScript.Data Represents the Excel DataPivotHierarchy.


PivotHierarchy

ExcelScript.Data Represents the data validation applied to the current range.


Validation

ExcelScript.Data Represents the error alert properties for the data validation.
ValidationError
Alert

ExcelScript.Data Represents the user prompt properties for the data validation.
ValidationPrompt

ExcelScript.Data A data validation rule contains different types of data validation. You can only
ValidationRule use one of them at a time according the ExcelScript.DataValidationType .

ExcelScript.Date Represents the date data validation criteria.


TimeData
Validation

ExcelScript. Defines the culturally appropriate format of displaying numbers. This is based
DatetimeFormat on current system culture settings.
Info

ExcelScript. Represents workbook properties.


Document
Properties

ExcelScript.Filter Manages the filtering of a table's column.

ExcelScript.Filter Represents the filtering criteria applied to a column.


Criteria

ExcelScript.Filter Represents how to filter a date when filtering on values.


Datetime

ExcelScript.Filter Represents the Excel FilterPivotHierarchy.


PivotHierarchy

ExcelScript. Represents the format protection of a range object.


FormatProtection

ExcelScript. Represents a geometric shape inside a worksheet. A geometric shape can be


GeometricShape a rectangle, block arrow, equation symbol, flowchart item, star, banner,
callout, or any other basic shape in Excel.

ExcelScript.HeaderFooter
ExcelScript.HeaderFooterGroup

ExcelScript.Icon Represents a cell icon.

ExcelScript.Icon Represents an icon set criteria for conditional formatting.


SetConditional
Format

ExcelScript.Image Represents an image in the worksheet. To get the corresponding Shape


object, use Image.getShape .

ExcelScript. Represents the iterative calculation settings.


Iterative
Calculation

ExcelScript.Line Represents a line inside a worksheet. To get the corresponding Shape object,
use Line.shape .

ExcelScript.Linked Contains information about a linked workbook. If a workbook has links


Workbook pointing to data in another workbook, the second workbook is linked to the
first workbook. In this scenario, the second workbook is called the "linked
workbook".

ExcelScript.List Represents the List data validation criteria.


DataValidation

ExcelScript. Represents a defined name for a range of cells or value. Names can be
NamedItem primitive named objects (as seen in the type below), range object, or a
reference to a range. This object can be used to obtain range object
associated with names.

ExcelScript. Represents an object containing values and types of a named item.


NamedItemArray
Values

ExcelScript. Represents a named sheet view of a worksheet. A sheet view stores the sort
NamedSheetView and filter rules for a particular worksheet. Every sheet view (even a temporary
sheet view) has a unique, worksheet-scoped name that is used to access the
view.

ExcelScript. Defines the culturally appropriate format of displaying numbers. This is based
NumberFormat on current system culture settings.
Info

ExcelScript.PageBreak

ExcelScript.Page Represents layout and print settings that are not dependent on any printer-
Layout specific implementation. These settings include margins, orientation, page
numbering, title rows, and print area.

ExcelScript.Page Represents the options in page layout margins.


LayoutMargin
Options

ExcelScript.Page Represents page zoom properties.


LayoutZoom
Options

ExcelScript.Pivot Configurable template for a date filter to apply to a PivotField. The condition
DateFilter defines what criteria need to be set in order for the filter to operate.

ExcelScript.Pivot Represents the Excel PivotField.


Field

ExcelScript.Pivot An interface representing all PivotFilters currently applied to a given


Filters PivotField.

ExcelScript.Pivot Represents the Excel PivotHierarchy.


Hierarchy

ExcelScript.Pivot Represents the Excel PivotItem.


Item

ExcelScript.Pivot Configurable template for a label filter to apply to a PivotField. The


LabelFilter condition defines what criteria need to be set in order for the filter to
operate.

ExcelScript.Pivot Represents the visual layout of the PivotTable.


Layout

ExcelScript.Pivot Configurable template for a manual filter to apply to a PivotField. The


ManualFilter condition defines what criteria need to be set in order for the filter to
operate.

ExcelScript.Pivot Represents an Excel PivotTable.


Table

ExcelScript.Pivot Represents a PivotTable style, which defines style elements by PivotTable


TableStyle region.

ExcelScript.Pivot Configurable template for a value filter to apply to a PivotField. The


ValueFilter condition defines what criteria need to be set in order for the filter to
operate.

ExcelScript. An object encapsulating a style's format and other properties.


PredefinedCell
Style

ExcelScript.Preset Represents the preset criteria conditional format such as above average,
Criteria below average, unique values, contains blank, nonblank, error, and noerror.
Conditional
Format

ExcelScript.Query Represents a Power Query query.


ExcelScript.Range Range represents a set of one or more contiguous cells such as a cell, a row,
a column, or a block of cells.

ExcelScript.Range RangeAreas represents a collection of one or more rectangular ranges in the


Areas same worksheet.

ExcelScript.Range Represents the border of an object.


Border

ExcelScript.Range Represents the background of a range object.


Fill

ExcelScript.Range This object represents the font attributes (font name, font size, color, etc.) for
Font an object.

ExcelScript.Range A format object encapsulating the range's font, fill, borders, alignment, and
Format other properties.

ExcelScript.Range Represents the necessary strings to get/set a hyperlink (XHL) object.


Hyperlink

ExcelScript.Range Manages sorting operations on Range objects.


Sort

ExcelScript.Range RangeView represents a set of visible cells of the parent range.


View

ExcelScript. Represents the results from Range.removeDuplicates .


Remove
DuplicatesResult

ExcelScript. Represents the replace criteria to be used.


ReplaceCriteria

ExcelScript.Row Represents the Excel RowColumnPivotHierarchy.


ColumnPivot
Hierarchy

ExcelScript.Search Represents the search criteria to be used.


Criteria

ExcelScript.Shape Represents a generic shape object in the worksheet. A shape could be a


geometric shape, a line, a group of shapes, etc.

ExcelScript.Shape Represents the fill formatting of a shape object.


Fill

ExcelScript.Shape Represents the font attributes, such as font name, font size, and color, for a
Font shape's TextRange object.

ExcelScript.Shape Represents a shape group inside a worksheet. To get the corresponding


Group Shape object, use ShapeGroup.shape .
ExcelScript.Shape Represents the line formatting for the shape object. For images and
LineFormat geometric shapes, line formatting represents the border of the shape.

ExcelScript.ShowAsRule

ExcelScript.Slicer Represents a Slicer object in the workbook.

ExcelScript.Slicer Represents a slicer item in a slicer.


Item

ExcelScript.Slicer Represents a slicer style, which defines style elements by region of the slicer.
Style

ExcelScript.Sort Represents a condition in a sorting operation.


Field

ExcelScript. Subtotals for the Pivot Field.


Subtotals

ExcelScript.Table Represents an Excel table.

ExcelScript.Table Represents a column in a table.


Column

ExcelScript.Table Manages sorting operations on Table objects.


Sort

ExcelScript.Table Represents a table style, which defines the style elements by region of the
Style table.

ExcelScript.Text Represents a specific text conditional format.


Conditional
Format

ExcelScript.Text Represents the text frame of a shape object.


Frame

ExcelScript.Text Contains the text that is attached to a shape, in addition to properties and
Range methods for manipulating the text.

ExcelScript. Represents a TimelineStyle , which defines style elements by region in the


TimelineStyle timeline.

ExcelScript.Top Represents a top/bottom conditional format.


Bottom
Conditional
Format

ExcelScript. Workbook is the top level object which contains related workbook objects
Workbook such as worksheets, tables, and ranges.
ExcelScript. Represents the protection of a workbook object.
Workbook
Protection

ExcelScript. Represents a collection of one or more rectangular ranges in multiple


WorkbookRange worksheets.
Areas

ExcelScript. An Excel worksheet is a grid of cells. It can contain data, tables, charts, etc.
Worksheet

ExcelScript. Represents a worksheet-level custom property.


Worksheet
CustomProperty

ExcelScript.WorksheetFreezePanes

ExcelScript. Represents the protection of a worksheet object.


Worksheet
Protection

ExcelScript. Represents the options in sheet protection.


Worksheet
Protection
Options

ExcelScript. Represents the worksheet search criteria to be used.


WorksheetSearch
Criteria

Enums
ノ Expand table

ExcelScript. Aggregation function for the DataPivotHierarchy .


Aggregation
Function

ExcelScript.ArrowheadLength

ExcelScript.ArrowheadStyle

ExcelScript.ArrowheadWidth

ExcelScript.AutoFill The behavior types when AutoFill is used on a range in the workbook.
Type

ExcelScript.BindingType
ExcelScript.BorderIndex

ExcelScript.BorderLineStyle

ExcelScript.BorderWeight

ExcelScript.BuiltInStyle

ExcelScript.CalculationMode

ExcelScript. Represents the state of calculation across the entire Excel application.
CalculationState

ExcelScript.CalculationType

ExcelScript.Chart Specifies the type of the category axis.


AxisCategoryType

ExcelScript.ChartAxisDisplayUnit

ExcelScript.ChartAxisGroup

ExcelScript.ChartAxisPosition

ExcelScript.ChartAxisScaleType

ExcelScript.ChartAxisTickLabelPosition

ExcelScript.ChartAxisTickMark

ExcelScript.Chart Specifies the unit of time for chart axes and data series.
AxisTimeUnit

ExcelScript.ChartAxisType

ExcelScript.ChartBin Specifies the bin type of a histogram chart or pareto chart series.
Type

ExcelScript.ChartBox Represents the quartile calculation type of chart series layout. Only applies
QuartileCalculation to a box and whisker chart.

ExcelScript.ChartColorScheme

ExcelScript.ChartDataLabelPosition

ExcelScript.Chart Specifies the data source type of the chart series.


DataSourceType

ExcelScript.ChartDisplayBlanksAs

ExcelScript.Chart Represents which parts of the error bar to include.


ErrorBarsInclude
ExcelScript.Chart Represents the range type for error bars.
ErrorBarsType

ExcelScript.Chart Represents the gradient style of a chart series. This is only applicable for
GradientStyle region map charts.

ExcelScript.Chart Represents the gradient style type of a chart series. This is only applicable
GradientStyleType for region map charts.

ExcelScript.ChartLegendPosition

ExcelScript.ChartLineStyle

ExcelScript.Chart Represents the mapping level of a chart series. This only applies to region
MapAreaLevel map charts.

ExcelScript.Chart Represents the region level of a chart series layout. This only applies to
MapLabelStrategy region map charts.

ExcelScript.Chart Represents the region projection type of a chart series layout. This only
MapProjectionType applies to region map charts.

ExcelScript.ChartMarkerStyle

ExcelScript.Chart Represents the parent label strategy of the chart series layout. This only
ParentLabelStrategy applies to treemap charts

ExcelScript.ChartPlotAreaPosition

ExcelScript.ChartPlotBy

ExcelScript.Chart Specifies whether the series are by rows or by columns. In Excel on


SeriesBy desktop, the "auto" option will inspect the source data shape to
automatically guess whether the data is by rows or columns. In Excel on
the web, "auto" will simply default to "columns".

ExcelScript.Chart Represents the dimensions when getting values from chart series.
SeriesDimension

ExcelScript.ChartSplitType

ExcelScript.Chart Represents the horizontal alignment for the specified object.


TextHorizontal
Alignment

ExcelScript.Chart Represents the vertical alignment for the specified object.


TextVertical
Alignment

ExcelScript.ChartTickLabelAlignment

ExcelScript.Chart Represents the position of the chart title.


TitlePosition

ExcelScript.ChartTrendlineType

ExcelScript.ChartType

ExcelScript.ChartUnderlineStyle

ExcelScript.ClearApplyTo

ExcelScript. Represents the operator of the text conditional format type.


ConditionalCell
ValueOperator

ExcelScript. Represents the format options for a data bar axis.


ConditionalDataBar
AxisFormat

ExcelScript. Represents the data bar direction within a cell.


ConditionalDataBar
Direction

ExcelScript. Represents the types of color criterion for conditional formatting.


ConditionalFormat
ColorCriterionType

ExcelScript. Represents the direction for a selection.


ConditionalFormat
Direction

ExcelScript. Represents the types of icon conditional format.


ConditionalFormat
IconRuleType

ExcelScript. Represents the criteria of the preset criteria conditional format type.
ConditionalFormat
PresetCriterion

ExcelScript. Represents the types of conditional format values.


ConditionalFormat
RuleType

ExcelScript.ConditionalFormatType

ExcelScript. Represents the operator for each icon criteria.


ConditionalIcon
CriterionOperator

ExcelScript.ConditionalRangeBorderIndex

ExcelScript.ConditionalRangeBorderLineStyle
ExcelScript.ConditionalRangeFontUnderlineStyle

ExcelScript. Represents the operator of the text conditional format type.


ConditionalText
Operator

ExcelScript. Represents the criteria for the above/below average conditional format
ConditionalTop type.
BottomCriterion
Type

ExcelScript.ConnectorType

ExcelScript.ContentType

ExcelScript.Data Represents the data validation error alert style. The default is Stop .
ValidationAlertStyle

ExcelScript.Data Represents the data validation operator enum.


ValidationOperator

ExcelScript.Data Represents the data validation type enum.


ValidationType

ExcelScript.Date Enum representing all accepted conditions by which a date filter can be
FilterCondition applied. Used to configure the type of PivotFilter that is applied to the
field.

ExcelScript.DeleteShiftDirection

ExcelScript.DocumentPropertyType

ExcelScript.DynamicFilterCriteria

ExcelScript.FillPattern

ExcelScript.FilterDatetimeSpecificity

ExcelScript.FilterOn

ExcelScript.FilterOperator

ExcelScript. Specifies the shape type for a GeometricShape object.


GeometricShape
Type

ExcelScript.GroupOption

ExcelScript.HeaderFooterState

ExcelScript.HorizontalAlignment

ExcelScript.IconSet
ExcelScript.ImageFittingMode

ExcelScript.Insert Determines the direction in which existing cells will be shifted to


ShiftDirection accommodate what is being inserted.

ExcelScript.KeyboardDirection

ExcelScript.Label Enum representing all accepted conditions by which a label filter can be
FilterCondition applied. Used to configure the type of PivotFilter that is applied to the
field. PivotFilter.criteria.exclusive can be set to true to invert many of
these conditions.

ExcelScript.LinkedDataTypeState

ExcelScript.Load An enum that specifies the query load to destination.


ToType

ExcelScript.NamedItemScope

ExcelScript.NamedItemType

ExcelScript.Number Represents a category of number formats.


FormatCategory

ExcelScript.PageOrientation

ExcelScript.PaperType

ExcelScript.Picture The format of the image.


Format

ExcelScript.PivotAxis Represents the axis from which to get the PivotItems.

ExcelScript.Pivot Represents the criteria for the top/bottom values filter.


FilterTopBottom
Criterion

ExcelScript.Pivot A simple enum that represents a type of filter for a PivotField.


FilterType

ExcelScript.PivotLayoutType

ExcelScript. Specifies the way that an object is attached to its underlying cells.
Placement

ExcelScript.PrintComments

ExcelScript.PrintErrorType

ExcelScript.PrintMarginUnit

ExcelScript.PrintOrder
ExcelScript.ProtectionSelectionMode

ExcelScript.Query An enum that specifies the query load error message.


Error

ExcelScript.RangeCopyType

ExcelScript.RangeUnderlineStyle

ExcelScript.RangeValueType

ExcelScript.ReadingOrder

ExcelScript.Search Specifies the search direction.


Direction

ExcelScript.Shape Determines the type of automatic sizing allowed.


AutoSize

ExcelScript.ShapeFill Specifies a shape's fill type.


Type

ExcelScript.Shape The type of underline applied to a font.


FontUnderlineStyle

ExcelScript.Shape The dash style for a line.


LineDashStyle

ExcelScript.Shape The style for a line.


LineStyle

ExcelScript.Shape Specifies which part of the shape retains its position when the shape is
ScaleFrom scaled.

ExcelScript.Shape Specifies whether the shape is scaled relative to its original or current size.
ScaleType

ExcelScript.Shape Specifies the horizontal alignment for the text frame in a shape.
TextHorizontal
Alignment

ExcelScript.Shape Specifies the horizontal overflow for the text frame in a shape.
TextHorizontal
Overflow

ExcelScript.Shape Specifies the orientation for the text frame in a shape.


TextOrientation

ExcelScript.Shape Specifies the reading order for the text frame in a shape.
TextReadingOrder

ExcelScript.Shape Specifies the vertical alignment for the text frame in a shape.
TextVertical
Alignment

ExcelScript.Shape Specifies the vertical overflow for the text frame in a shape.
TextVerticalOverflow

ExcelScript.Shape Specifies the type of a shape.


Type

ExcelScript.Shape Specifies where in the z-order a shape should be moved relative to other
ZOrder shapes.

ExcelScript.SheetVisibility

ExcelScript.Show The ShowAs calculation function for the DataPivotField.


AsCalculation

ExcelScript.Slicer Specifies the slicer sort behavior for Slicer.sortBy .


SortType

ExcelScript.SortBy Represents the sort direction.

ExcelScript.SortDataOption

ExcelScript.Sort Represents the ordering method to be used when sorting Chinese


Method characters.

ExcelScript.SortOn Represents the part of the cell used as the sorting criteria.

ExcelScript.SortOrientation

ExcelScript.SpecialCellType

ExcelScript.SpecialCellValueType

ExcelScript.SubtotalLocationType

ExcelScript.Top A simple enum for top/bottom filters to select whether to filter by the top
BottomSelection N or bottom N percent, number, or sum of values.
Type

ExcelScript.Value Enum representing all accepted conditions by which a value filter can be
FilterCondition applied. Used to configure the type of PivotFilter that is applied to the
field. PivotFilter.exclusive can be set to true to invert many of these
conditions.

ExcelScript.VerticalAlignment

ExcelScript. Represents the refresh mode of the workbook links.


WorkbookLinks
RefreshMode

ExcelScript. The position of a worksheet relative to another worksheet or the entire


WorksheetPosition worksheet collection.
Type

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.AggregationFunction enum
Reference
Package: ExcelScript

Aggregation function for the DataPivotHierarchy .

Remarks

Examples

TypeScript

/**
* This script changes how the data in a PivotTable is aggregated.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first PivotTable in the workbook.
const pivotTable = workbook.getPivotTables()[0];

// Set the first data hierarchy to summarize with an average value,


instead of a sum.
const dataHierarchy = pivotTable.getDataHierarchies()[0];
dataHierarchy.setSummarizeBy(ExcelScript.AggregationFunction.average);
}

Fields
ノ Expand table

automatic Excel will automatically select the aggregation based on the data items.

average Aggregate using the average of the data, equivalent to the AVERAGE
function.

count Aggregate using the count of items in the data, equivalent to the COUNTA
function.

countNumbers Aggregate using the count of numbers in the data, equivalent to the
COUNT function.

max Aggregate using the maximum value of the data, equivalent to the MAX
function.
min Aggregate using the minimum value of the data, equivalent to the MIN
function.

product Aggregate using the product of the data, equivalent to the PRODUCT
function.

standardDeviation Aggregate using the standard deviation of the data, equivalent to the
STDEV function.

standardDeviationP Aggregate using the standard deviation of the data, equivalent to the
STDEVP function.

sum Aggregate using the sum of the data, equivalent to the SUM function.

unknown Aggregation function is unknown or unsupported.

variance Aggregate using the variance of the data, equivalent to the VAR function.

varianceP Aggregate using the variance of the data, equivalent to the VARP function.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ArrowheadLength enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script adds a line that goes from cell B2 to cell F4 on the current
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
const sheet = workbook.getActiveWorksheet();

// Get the ranges for the two cells.


const b2Range = sheet.getRange("B2");
const f4Range = sheet.getRange("F4");

// Add a straight line that connects the top-left corners of both cells.
const newShape = sheet.addLine(
b2Range.getLeft(),
b2Range.getTop(),
f4Range.getLeft(),
f4Range.getTop(),
ExcelScript.ConnectorType.straight);

// Add a long, open arrowhead to the end of the line, such that it points
at F4.
const line = newShape.getLine();
line.setEndArrowheadStyle(ExcelScript.ArrowheadStyle.open);
line.setEndArrowheadLength(ExcelScript.ArrowheadLength.long);
}

Fields
ノ Expand table

long

medium
short

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ArrowheadStyle enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script adds a line that goes from cell B2 to cell F4 on the current
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
const sheet = workbook.getActiveWorksheet();

// Get the ranges for the two cells.


const b2Range = sheet.getRange("B2");
const f4Range = sheet.getRange("F4");

// Add a straight line that connects the top-left corners of both cells.
const newShape = sheet.addLine(
b2Range.getLeft(),
b2Range.getTop(),
f4Range.getLeft(),
f4Range.getTop(),
ExcelScript.ConnectorType.straight);

// Add an open arrowhead to the end of the line, such that it points at
F4.
const line = newShape.getLine();
line.setEndArrowheadStyle(ExcelScript.ArrowheadStyle.open);
}

Fields
ノ Expand table

diamond

none

open
oval

stealth

triangle

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ArrowheadWidth enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script adds a line that goes from cell B2 to cell F4 on the current
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
const sheet = workbook.getActiveWorksheet();

// Get the ranges for the two cells.


const b2Range = sheet.getRange("B2");
const f4Range = sheet.getRange("F4");

// Add a straight line that connects the top-left corners of both cells.
const newShape = sheet.addLine(
b2Range.getLeft(),
b2Range.getTop(),
f4Range.getLeft(),
f4Range.getTop(),
ExcelScript.ConnectorType.straight);

// Add a wide, triangular arrowhead to the end of the line, such that it
points at F4.
const line = newShape.getLine();
line.setEndArrowheadStyle(ExcelScript.ArrowheadStyle.triangle);
line.setEndArrowheadWidth(ExcelScript.ArrowheadWidth.wide);
}

Fields
ノ Expand table

medium

narrow
wide

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.AutoFillType enum
Reference
Package: ExcelScript

The behavior types when AutoFill is used on a range in the workbook.

Remarks

Examples

TypeScript

/**
* This script uses the autofill feature to complete a table with days of
the month.
* See https://support.microsoft.com/office/74e31bdd-d993-45da-aa82-
35a236c5b5db
* for examples of autofill scenarios.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current, active worksheet.
let currentWorksheet = workbook.getActiveWorksheet();

// Get the data range that shows the pattern.


let dataRange = currentWorksheet.getRange("C2:C3");

// Autofill the connected range. C2:C3 are filled in with dates. C4:C54
are blank.
dataRange.autoFill("C2:C54", ExcelScript.AutoFillType.fillDays);
}

Fields
ノ Expand table

fillCopy Populates the adjacent cells with data based on the selected data.

fillDays A version of "FillSeries" for dates that bases the pattern on either the day of the
month or the day of the week, depending on the context.

fillDefault Populates the adjacent cells based on the surrounding data (the standard AutoFill
behavior).

fillFormats Populates the adjacent cells with the selected formats.


fillMonths A version of "FillSeries" for dates that bases the pattern on the month.

fillSeries Populates the adjacent cells with data that follows a pattern in the copied cells.

fillValues Populates the adjacent cells with the selected values.

fillWeekdays A version of "FillSeries" for dates that bases the pattern on the day of the week
and only includes weekdays.

fillYears A version of "FillSeries" for dates that bases the pattern on the year.

flashFill Populates the adjacent cells by using Excel's Flash Fill feature.

growthTrend A version of "FillSeries" for numbers that fills out the values in the adjacent cells
according to a growth trend model.

linearTrend A version of "FillSeries" for numbers that fills out the values in the adjacent cells
according to a linear trend model.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.BindingType enum
Reference
Package: ExcelScript

Fields
ノ Expand table

range

table

text

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.BorderIndex enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script creates a border around a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the RangeFormat object for the range "B2:G10".
const currentSheet = workbook.getActiveWorksheet();
const rangeForBorder = currentSheet.getRange("B2:G10");
const format = rangeForBorder.getFormat();

// Get a RangeBorder object for each edge of the range and set the border
properties.
let edgeTop = format.getRangeBorder(ExcelScript.BorderIndex.edgeTop);
edgeTop.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeTop.setWeight(ExcelScript.BorderWeight.thick);

let edgeBottom =
format.getRangeBorder(ExcelScript.BorderIndex.edgeBottom);
edgeBottom.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeBottom.setWeight(ExcelScript.BorderWeight.thick);

let edgeLeft = format.getRangeBorder(ExcelScript.BorderIndex.edgeLeft);


edgeLeft.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeLeft.setWeight(ExcelScript.BorderWeight.thick);

let edgeRight = format.getRangeBorder(ExcelScript.BorderIndex.edgeRight);


edgeRight.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeRight.setWeight(ExcelScript.BorderWeight.thick);
}

Fields
ノ Expand table

diagonalDown
diagonalUp

edgeBottom

edgeLeft

edgeRight

edgeTop

insideHorizontal

insideVertical

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.BorderLineStyle enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script creates a border around a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the RangeFormat object for the range "B2:G10".
const currentSheet = workbook.getActiveWorksheet();
const rangeForBorder = currentSheet.getRange("B2:G10");
const format = rangeForBorder.getFormat();

// Get a RangeBorder object for each edge of the range and set the border
properties.
let edgeTop = format.getRangeBorder(ExcelScript.BorderIndex.edgeTop);
edgeTop.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeTop.setWeight(ExcelScript.BorderWeight.thick);

let edgeBottom =
format.getRangeBorder(ExcelScript.BorderIndex.edgeBottom);
edgeBottom.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeBottom.setWeight(ExcelScript.BorderWeight.thick);

let edgeLeft = format.getRangeBorder(ExcelScript.BorderIndex.edgeLeft);


edgeLeft.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeLeft.setWeight(ExcelScript.BorderWeight.thick);

let edgeRight = format.getRangeBorder(ExcelScript.BorderIndex.edgeRight);


edgeRight.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeRight.setWeight(ExcelScript.BorderWeight.thick);
}

Fields
ノ Expand table

continuous
dash

dashDot

dashDotDot

dot

double

none

slantDashDot

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.BorderWeight enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script creates a border around a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the RangeFormat object for the range "B2:G10".
const currentSheet = workbook.getActiveWorksheet();
const rangeForBorder = currentSheet.getRange("B2:G10");
const format = rangeForBorder.getFormat();

// Get a RangeBorder object for each edge of the range and set the border
properties.
let edgeTop = format.getRangeBorder(ExcelScript.BorderIndex.edgeTop);
edgeTop.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeTop.setWeight(ExcelScript.BorderWeight.thick);

let edgeBottom =
format.getRangeBorder(ExcelScript.BorderIndex.edgeBottom);
edgeBottom.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeBottom.setWeight(ExcelScript.BorderWeight.thick);

let edgeLeft = format.getRangeBorder(ExcelScript.BorderIndex.edgeLeft);


edgeLeft.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeLeft.setWeight(ExcelScript.BorderWeight.thick);

let edgeRight = format.getRangeBorder(ExcelScript.BorderIndex.edgeRight);


edgeRight.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeRight.setWeight(ExcelScript.BorderWeight.thick);
}

Fields
ノ Expand table

hairline
medium

thick

thin

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.BuiltInStyle enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script sets the cell style to "warning text"
* on every cell with a formula error.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range in the current worksheet.
const sheet = workbook.getActiveWorksheet();
const usedRange = sheet.getUsedRange();

// Get any cells that are displaying errors.


const errorCells = usedRange.getSpecialCells(
ExcelScript.SpecialCellType.formulas,
ExcelScript.SpecialCellValueType.errors
);

// Check if there are error cells before proceeding.


if (errorCells) {
// Use the built-in warning text style on the error cells.
errorCells.setPredefinedCellStyle(
ExcelScript.BuiltInStyle.warningText.toString()
);
} else {
console.log("No formula errors in the worksheet.");
}
}

Fields
ノ Expand table

accent1

accent1_20

accent1_40
accent1_60

accent2

accent2_20

accent2_40

accent2_60

accent3

accent3_20

accent3_40

accent3_60

accent4

accent4_20

accent4_40

accent4_60

accent5

accent5_20

accent5_40

accent5_60

accent6

accent6_20

accent6_40

accent6_60

bad

calculation

checkCell

comma

currency

emphasis1
emphasis2

emphasis3

explanatoryText

good

heading1

heading2

heading3

heading4

hlink

hlinkTrav

input

linkedCell

neutral

normal

note

output

percent

sheetTitle

total

warningText

wholeComma

wholeDollar

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.CalculationMode enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script recalculates the used range of a specific worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Only recalculate if the calculation mode is not set to automatic.
if (workbook.getApplication().getCalculationMode() !==
ExcelScript.CalculationMode.automatic) {
// Get the used range from a worksheet named "Monthly Report".
const sheet = workbook.getWorksheet("Monthly Report");
const range = sheet.getUsedRange();
console.log(`Calculating ${range.getAddress()}`);

// Force all the used cells in that worksheet to calculate.


sheet.getUsedRange().calculate();
}
}

Fields
ノ Expand table

automatic The default recalculation behavior where Excel calculates new formula
results every time the relevant data is changed.

automaticExceptTables Calculates new formula results every time the relevant data is changed,
unless the formula is in a data table.

manual Calculations only occur when the user or add-in requests them.

6 Collaborate with us on
Office Scripts feedback
GitHub Office Scripts is an open source project.
Select a link to provide feedback:
The source for this content can
be found on GitHub, where you  Open a documentation issue
can also create and review
issues and pull requests. For  Provide product feedback
more information, see our
contributor guide.
ExcelScript.CalculationState enum
Reference
Package: ExcelScript

Represents the state of calculation across the entire Excel application.

Remarks

Examples

TypeScript

/**
* This script uses the fill color of the first cell to indicate the current
* calculation state of the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell in the first worksheet.
const cell = workbook.getWorksheets()[0].getCell(0,0);

// Get that cell's fill object.


const cellFill = cell.getFormat().getFill();

// Set the cell fill based on the calculation state.


const calcState = workbook.getApplication().getCalculationState();
switch (calcState) {
case ExcelScript.CalculationState.pending:
cellFill.setColor("Red");
break;
case ExcelScript.CalculationState.calculating:
cellFill.setColor("Yellow");
break;
case ExcelScript.CalculationState.done:
cellFill.setColor("Green");
break;
}
}

Fields
ノ Expand table

calculating Calculations in progress.


done Calculations complete.

pending Changes that trigger calculation have been made, but a recalculation has not yet
been performed.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CalculationType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script fully recalculates the entire workbook.
* This code is useful when automatic recalculation is turned off
* but later parts of the script rely on updated values.
*/
function main(workbook: ExcelScript.Workbook, workbookURL: string) {
const application = workbook.getApplication();
application.calculate(ExcelScript.CalculationType.fullRebuild);
}

Fields
ノ Expand table

full This will mark all cells as dirty and then recalculate them.

fullRebuild This will rebuild the full dependency chain, mark all cells as dirty and then recalculate
them.

recalculate Recalculates all cells that Excel has marked as dirty, that is, dependents of volatile or
changed data, and cells programmatically marked as dirty.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.ChartAxisCategoryType
enum
Reference
Package: ExcelScript

Specifies the type of the category axis.

Fields
ノ Expand table

automatic Excel controls the axis type.

dateAxis Axis groups data on a time scale.

textAxis Axis groups data by an arbitrary set of categories.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisDisplayUnit enum
Reference
Package: ExcelScript

Fields
ノ Expand table

billions This will set the axis in units of billions.

custom This will set the axis in units of custom value.

hundredMillions This will set the axis in units of hundreds of millions.

hundreds This will set the axis in units of hundreds.

hundredThousands This will set the axis in units of hundreds of thousands.

millions This will set the axis in units of millions.

none Default option. This will reset display unit to the axis, and set unit label
invisible.

tenMillions This will set the axis in units of tens of millions.

tenThousands This will set the axis in units of tens of thousands.

thousands This will set the axis in units of thousands.

trillions This will set the axis in units of trillions.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisGroup enum
Reference
Package: ExcelScript

Fields
ノ Expand table

primary

secondary

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisPosition enum
Reference
Package: ExcelScript

Fields
ノ Expand table

automatic

custom

maximum

minimum

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisScaleType enum
Reference
Package: ExcelScript

Fields
ノ Expand table

linear

logarithmic

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisTickLabelPosition
enum
Reference
Package: ExcelScript

Fields
ノ Expand table

high

low

nextToAxis

none

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisTickMark enum
Reference
Package: ExcelScript

Fields
ノ Expand table

cross

inside

none

outside

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisTimeUnit enum
Reference
Package: ExcelScript

Specifies the unit of time for chart axes and data series.

Fields
ノ Expand table

days

months

years

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisType enum
Reference
Package: ExcelScript

Fields
ノ Expand table

category Axis displays categories.

invalid

series Axis displays data series.

value Axis displays values.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartBinType enum
Reference
Package: ExcelScript

Specifies the bin type of a histogram chart or pareto chart series.

Fields
ノ Expand table

auto

binCount

binWidth

category

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartBoxQuartileCalculation
enum
Reference
Package: ExcelScript

Represents the quartile calculation type of chart series layout. Only applies to a box and
whisker chart.

Fields
ノ Expand table

exclusive

inclusive

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartColorScheme enum
Reference
Package: ExcelScript

Fields
ノ Expand table

colorfulPalette1

colorfulPalette2

colorfulPalette3

colorfulPalette4

monochromaticPalette1

monochromaticPalette10

monochromaticPalette11

monochromaticPalette12

monochromaticPalette13

monochromaticPalette2

monochromaticPalette3

monochromaticPalette4

monochromaticPalette5

monochromaticPalette6

monochromaticPalette7

monochromaticPalette8

monochromaticPalette9

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
be found on GitHub, where you Select a link to provide feedback:
can also create and review
issues and pull requests. For  Open a documentation issue
more information, see our
contributor guide.  Provide product feedback
ExcelScript.ChartDataLabelPosition
enum
Reference
Package: ExcelScript

Fields
ノ Expand table

bestFit

bottom

callout

center

insideBase

insideEnd

invalid

left

none

outsideEnd

right

top

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartDataSourceType enum
Reference
Package: ExcelScript

Specifies the data source type of the chart series.

Fields
ノ Expand table

externalRange The data source type of the chart series is an external range.

list The data source type of the chart series is a list.

localRange The data source type of the chart series is a local range.

unknown The data source type of the chart series is unknown or unsupported.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartDisplayBlanksAs enum
Reference
Package: ExcelScript

Fields
ノ Expand table

interplotted

notPlotted

zero

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartErrorBarsInclude enum
Reference
Package: ExcelScript

Represents which parts of the error bar to include.

Fields
ノ Expand table

both

minusValues

plusValues

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartErrorBarsType enum
Reference
Package: ExcelScript

Represents the range type for error bars.

Remarks

Examples

TypeScript

/**
* This script adds error bars for the standard error of each chart series
point.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range for the chart.
const worksheet = workbook.getWorksheet("Sample");
const dataRange = worksheet.getRange("A1:B15");

// Create a line chart.


const chart = worksheet.addChart(ExcelScript.ChartType.line, dataRange);

// For each series, add error bars for the standard error on each point.
const allSeries = chart.getSeries();
allSeries.forEach((series) => {
series.getYErrorBars().setType(ExcelScript.ChartErrorBarsType.stError);
series.getYErrorBars().setVisible(true);
});
}

Fields
ノ Expand table

custom

fixedValue

percent

stDev
stError

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartGradientStyle enum
Reference
Package: ExcelScript

Represents the gradient style of a chart series. This is only applicable for region map
charts.

Fields
ノ Expand table

threePhaseColor

twoPhaseColor

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartGradientStyleType
enum
Reference
Package: ExcelScript

Represents the gradient style type of a chart series. This is only applicable for region
map charts.

Fields
ノ Expand table

extremeValue

number

percent

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartLegendPosition enum
Reference
Package: ExcelScript

Fields
ノ Expand table

bottom

corner

custom

invalid

left

right

top

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartLineStyle enum
Reference
Package: ExcelScript

Fields
ノ Expand table

automatic

continuous

dash

dashDot

dashDotDot

dot

grey25

grey50

grey75

none

roundDot

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartMapAreaLevel enum
Reference
Package: ExcelScript

Represents the mapping level of a chart series. This only applies to region map charts.

Fields
ノ Expand table

automatic

city

continent

country

county

dataOnly

state

world

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartMapLabelStrategy
enum
Reference
Package: ExcelScript

Represents the region level of a chart series layout. This only applies to region map
charts.

Fields
ノ Expand table

bestFit

none

showAll

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartMapProjectionType
enum
Reference
Package: ExcelScript

Represents the region projection type of a chart series layout. This only applies to region
map charts.

Fields
ノ Expand table

albers

automatic

mercator

miller

robinson

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartMarkerStyle enum
Reference
Package: ExcelScript

Fields
ノ Expand table

automatic

circle

dash

diamond

dot

invalid

none

picture

plus

square

star

triangle

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartParentLabelStrategy
enum
Reference
Package: ExcelScript

Represents the parent label strategy of the chart series layout. This only applies to
treemap charts

Fields
ノ Expand table

banner

none

overlapping

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartPlotAreaPosition enum
Reference
Package: ExcelScript

Fields
ノ Expand table

automatic

custom

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartPlotBy enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This sample performs the "Switch Row/Column" action on a chart named
"ColumnClusteredChart".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get an existing chart named "ColumnClusteredChart".


let columnClusteredChart = selectedSheet.getChart("ColumnClusteredChart");

// Switch the row and column for the chart's data source.
if (columnClusteredChart.getPlotBy() === ExcelScript.ChartPlotBy.columns)
{
// If the chart is grouped by columns, switch it to rows.
columnClusteredChart.setPlotBy(ExcelScript.ChartPlotBy.rows);
} else {
// If the chart is grouped by rows, switch it to columns.
columnClusteredChart.setPlotBy(ExcelScript.ChartPlotBy.columns);
}
}

Fields
ノ Expand table

columns

rows
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartSeriesBy enum
Reference
Package: ExcelScript

Specifies whether the series are by rows or by columns. In Excel on desktop, the "auto"
option will inspect the source data shape to automatically guess whether the data is by
rows or columns. In Excel on the web, "auto" will simply default to "columns".

Remarks

Examples

TypeScript

/**
* This script creates a clustered-column chart using an existing table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
const sheet = workbook.getActiveWorksheet();
const table = sheet.getTables()[0];

// Add a clustered-column chart that clusters the data based on the


columns in the table.
const chart = sheet.addChart(
ExcelScript.ChartType.columnClustered,
table.getRange(),
ExcelScript.ChartSeriesBy.columns
);
}

Fields
ノ Expand table

auto In Excel on desktop, the "auto" option will inspect the source data shape to
automatically guess whether the data is by rows or columns. In Excel on the web,
"auto" will simply default to "columns".

columns

rows
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartSeriesDimension enum
Reference
Package: ExcelScript

Represents the dimensions when getting values from chart series.

Fields
ノ Expand table

bubbleSizes The chart series axis for the bubble sizes in bubble charts.

categories The chart series axis for the categories.

values The chart series axis for the values.

xvalues The chart series axis for the x-axis values in scatter and bubble charts.

yvalues The chart series axis for the y-axis values in scatter and bubble charts.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartSplitType enum
Reference
Package: ExcelScript

Fields
ノ Expand table

splitByCustomSplit

splitByPercentValue

splitByPosition

splitByValue

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTextHorizontal
Alignment enum
Reference
Package: ExcelScript

Represents the horizontal alignment for the specified object.

Fields
ノ Expand table

center

distributed

justify

left

right

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTextVerticalAlignment
enum
Reference
Package: ExcelScript

Represents the vertical alignment for the specified object.

Fields
ノ Expand table

bottom

center

distributed

justify

top

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTickLabelAlignment
enum
Reference
Package: ExcelScript

Fields
ノ Expand table

center

left

right

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTitlePosition enum
Reference
Package: ExcelScript

Represents the position of the chart title.

Fields
ノ Expand table

automatic

bottom

left

right

top

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTrendlineType enum
Reference
Package: ExcelScript

Fields
ノ Expand table

exponential

linear

logarithmic

movingAverage

polynomial

power

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This sample creates a column-clustered chart based on the current
worksheet's data.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get the data range.


let range = selectedSheet.getUsedRange();

// Insert a chart using the data on the current worksheet.


let chart = selectedSheet.addChart(ExcelScript.ChartType.columnClustered,
range);

// Name the chart for easy access in other scripts.


chart.setName("ColumnChart");
}

Fields
ノ Expand table

area

areaStacked

areaStacked100

barClustered

barOfPie

barStacked
barStacked100

boxwhisker

bubble

bubble3DEffect

columnClustered

columnStacked

columnStacked100

coneBarClustered

coneBarStacked

coneBarStacked100

coneCol

coneColClustered

coneColStacked

coneColStacked100

cylinderBarClustered

cylinderBarStacked

cylinderBarStacked100

cylinderCol

cylinderColClustered

cylinderColStacked

cylinderColStacked100

doughnut

doughnutExploded

funnel

histogram

invalid

line
lineMarkers

lineMarkersStacked

lineMarkersStacked100

lineStacked

lineStacked100

pareto

pie

pieExploded

pieOfPie

pyramidBarClustered

pyramidBarStacked

pyramidBarStacked100

pyramidCol

pyramidColClustered

pyramidColStacked

pyramidColStacked100

radar

radarFilled

radarMarkers

regionMap

stockHLC

stockOHLC

stockVHLC

stockVOHLC

sunburst

surface

surfaceTopView
surfaceTopViewWireframe

surfaceWireframe

treemap

waterfall

xyscatter

xyscatterLines

xyscatterLinesNoMarkers

xyscatterSmooth

xyscatterSmoothNoMarkers

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartUnderlineStyle enum
Reference
Package: ExcelScript

Fields
ノ Expand table

none

single

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ClearApplyTo enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script removes any extra formatting that's been applied to a table.
* This leaves only the base table style effects.
* Any formatting outside of the table will be left as is.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
let worksheet = workbook.getActiveWorksheet();
let table = worksheet.getTables()[0];

// Get the range used by the table.


let range = table.getRange();

// Clear all the formatting that is not applied by the table and the table
style.
range.clear(ExcelScript.ClearApplyTo.formats);
}

Fields
ノ Expand table

all

contents Clears the contents of the range.

formats Clears all formatting for the range.

hyperlinks Clears all hyperlinks, but leaves all content and formatting intact.

removeHyperlinks Removes hyperlinks and formatting for the cell but leaves content,
conditional formats, and data validation intact.
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalCellValue
Operator enum
Reference
Package: ExcelScript

Represents the operator of the text conditional format type.

Remarks

Examples

TypeScript

/**
* This script applies conditional formatting to a range.
* That formatting is conditional upon the cell's numerical value.
* Any value between 50 and 75 will have the cell fill color changed and the
font made italic.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range to format.
const sheet = workbook.getActiveWorksheet();
const ratingColumn = sheet.getRange("D2:D20");

// Add cell value conditional formatting.


const cellValueConditionalFormatting =

ratingColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.cellValu
e).getCellValue();

// Set the format to apply when the condition is met.


let format = cellValueConditionalFormatting.getFormat();
format.getFill().setColor("yellow");
format.getFont().setItalic(true);

// Create the condition, in this case when the cell value is between 50
and 75.
let rule: ExcelScript.ConditionalCellValueRule = {
formula1: "50",
formula2: "75",
operator: ExcelScript.ConditionalCellValueOperator.between
};
cellValueConditionalFormatting.setRule(rule);
}
Fields
ノ Expand table

between

equalTo

greaterThan

greaterThanOrEqual

invalid

lessThan

lessThanOrEqual

notBetween

notEqualTo

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalDataBarAxis
Format enum
Reference
Package: ExcelScript

Represents the format options for a data bar axis.

Fields
ノ Expand table

automatic

cellMidPoint

none

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalDataBarDirection
enum
Reference
Package: ExcelScript

Represents the data bar direction within a cell.

Fields
ノ Expand table

context

leftToRight

rightToLeft

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalFormatColor
CriterionType enum
Reference
Package: ExcelScript

Represents the types of color criterion for conditional formatting.

Remarks

Examples

TypeScript

/**
* This script applies a red, white, and blue color scale to the selected
range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected range.
let selectedRange = workbook.getSelectedRange();

// Create a new conditional formatting object by adding one to the range.


let conditionalFormatting =
selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.colorSc
ale);

// Set the colors for the three parts of the scale: minimum, midpoint, and
maximum.
conditionalFormatting.getColorScale().setCriteria({
minimum: {
color:"#F8696B", /* A pale red. */
type:ExcelScript.ConditionalFormatColorCriterionType.lowestValue
},
midpoint: {
color: "#FCFCFF", /* Slightly off-white. */

formula:'=50',type:ExcelScript.ConditionalFormatColorCriterionType.percentil
e
},
maximum: {
color: "#5A8AC6", /* A pale blue. */
type:ExcelScript.ConditionalFormatColorCriterionType.highestValue
}
});
}
Fields
ノ Expand table

formula

highestValue

invalid

lowestValue

number

percent

percentile

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalFormatDirection
enum
Reference
Package: ExcelScript

Represents the direction for a selection.

Fields
ノ Expand table

bottom

top

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalFormatIconRule
Type enum
Reference
Package: ExcelScript

Represents the types of icon conditional format.

Remarks

Examples

TypeScript

/**
* This script applies icon set conditional formatting to a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range "A1:A5" on the current worksheet.
const sheet = workbook.getActiveWorksheet();
const range = sheet.getRange("A1:A5");

// Create icon set conditional formatting on the range.


const conditionalFormatting =
range.addConditionalFormat(ExcelScript.ConditionalFormatType.iconSet);

// Use the "3 Traffic Lights (Unrimmed)" set.

conditionalFormatting.getIconSet().setStyle(ExcelScript.IconSet.threeTraffic
Lights1);

// Set the criteria to use a different icon for the bottom, middle, and
top thirds of the values in the range.
const criteria: ExcelScript.ConditionalIconCriterion[] = [
{
formula: '=0', operator:
ExcelScript.ConditionalIconCriterionOperator.greaterThanOrEqual,
type: ExcelScript.ConditionalFormatIconRuleType.percent
},
{
formula: '=33', operator:
ExcelScript.ConditionalIconCriterionOperator.greaterThanOrEqual,
type: ExcelScript.ConditionalFormatIconRuleType.percent
},
{
formula: '=67', operator:
ExcelScript.ConditionalIconCriterionOperator.greaterThanOrEqual,
type: ExcelScript.ConditionalFormatIconRuleType.percent
}];
conditionalFormatting.getIconSet().setCriteria(criteria);
}

Fields
ノ Expand table

formula

invalid

number

percent

percentile

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalFormatPreset
Criterion enum
Reference
Package: ExcelScript

Represents the criteria of the preset criteria conditional format type.

Remarks

Examples

TypeScript

/**
* This script applies a conditional format that uses a preset criterion.
* Any cell in row 1 will have the color fill set to green if it is a
duplicate value
* (of anything else in row 1).
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range for row 1.
const sheet = workbook.getActiveWorksheet();
const formattedRange = sheet.getRange("1:1");

// Add new conditional formatting to that range.


const conditionalFormat = formattedRange.addConditionalFormat(
ExcelScript.ConditionalFormatType.presetCriteria);

// Set the conditional formatting to apply a green fill.


const presetFormat = conditionalFormat.getPreset();
presetFormat.getFormat().getFill().setColor("green");

// Set a rule to apply the conditional format when values are duplicated
in the range.
const duplicateRule: ExcelScript.ConditionalPresetCriteriaRule = {
criterion: ExcelScript.ConditionalFormatPresetCriterion.duplicateValues
};
presetFormat.setRule(duplicateRule);
}

Fields
ノ Expand table
aboveAverage

belowAverage

blanks

duplicateValues

equalOrAboveAverage

equalOrBelowAverage

errors

invalid

lastMonth

lastSevenDays

lastWeek

nextMonth

nextWeek

nonBlanks

nonErrors

oneStdDevAboveAverage

oneStdDevBelowAverage

thisMonth

thisWeek

threeStdDevAboveAverage

threeStdDevBelowAverage

today

tomorrow

twoStdDevAboveAverage

twoStdDevBelowAverage

uniqueValues

yesterday
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalFormatRuleType
enum
Reference
Package: ExcelScript

Represents the types of conditional format values.

Remarks

Examples

TypeScript

/**
* This script creates data bar conditional formatting on the selected
range.
* The scale of the data bar goes from 0 to 1000.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected range.
const selected = workbook.getSelectedRange();

// Create new conditional formatting on the range.


const format =
selected.addConditionalFormat(ExcelScript.ConditionalFormatType.dataBar);
const dataBarFormat = format.getDataBar();

// Set the lower bound of the data bar formatting to be 0.


const lowerBound: ExcelScript.ConditionalDataBarRule = {
type: ExcelScript.ConditionalFormatRuleType.number,
formula: "0"
};
dataBarFormat.setLowerBoundRule(lowerBound);

// Set the upper bound of the data bar formatting to be 1000.


const upperBound: ExcelScript.ConditionalDataBarRule = {
type: ExcelScript.ConditionalFormatRuleType.number,
formula: "1000"
};
dataBarFormat.setUpperBoundRule(upperBound);
}

Fields
ノ Expand table

automatic

formula

highestValue

invalid

lowestValue

number

percent

percentile

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalFormatType
enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script applies a red, white, and blue color scale to the selected
range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected range.
let selectedRange = workbook.getSelectedRange();

// Create a new conditional formatting object by adding one to the range.


let conditionalFormatting =
selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.colorSc
ale);

// Set the colors for the three parts of the scale: minimum, midpoint, and
maximum.
conditionalFormatting.getColorScale().setCriteria({
minimum: {
color:"#F8696B", /* A pale red. */
type:ExcelScript.ConditionalFormatColorCriterionType.lowestValue
},
midpoint: {
color: "#FCFCFF", /* Slightly off-white. */

formula:'=50',type:ExcelScript.ConditionalFormatColorCriterionType.percentil
e
},
maximum: {
color: "#5A8AC6", /* A pale blue. */
type:ExcelScript.ConditionalFormatColorCriterionType.highestValue
}
});
}

Fields
ノ Expand table

cellValue

colorScale

containsText

custom

dataBar

iconSet

presetCriteria

topBottom

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalIconCriterion
Operator enum
Reference
Package: ExcelScript

Represents the operator for each icon criteria.

Remarks

Examples

TypeScript

/**
* This script applies icon set conditional formatting to a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range "A1:A5" on the current worksheet.
const sheet = workbook.getActiveWorksheet();
const range = sheet.getRange("A1:A5");

// Create icon set conditional formatting on the range.


const conditionalFormatting =
range.addConditionalFormat(ExcelScript.ConditionalFormatType.iconSet);

// Use the "3 Traffic Lights (Unrimmed)" set.

conditionalFormatting.getIconSet().setStyle(ExcelScript.IconSet.threeTraffic
Lights1);

// Set the criteria to use a different icon for the bottom, middle, and
top thirds of the values in the range.
const criteria: ExcelScript.ConditionalIconCriterion[] = [
{
formula: '=0', operator:
ExcelScript.ConditionalIconCriterionOperator.greaterThanOrEqual,
type: ExcelScript.ConditionalFormatIconRuleType.percent
},
{
formula: '=33', operator:
ExcelScript.ConditionalIconCriterionOperator.greaterThanOrEqual,
type: ExcelScript.ConditionalFormatIconRuleType.percent
},
{
formula: '=67', operator:
ExcelScript.ConditionalIconCriterionOperator.greaterThanOrEqual,
type: ExcelScript.ConditionalFormatIconRuleType.percent
}];
conditionalFormatting.getIconSet().setCriteria(criteria);
}

Fields
ノ Expand table

greaterThan

greaterThanOrEqual

invalid

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalRangeBorder
Index enum
Reference
Package: ExcelScript

Fields
ノ Expand table

edgeBottom

edgeLeft

edgeRight

edgeTop

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalRangeBorderLine
Style enum
Reference
Package: ExcelScript

Fields
ノ Expand table

continuous

dash

dashDot

dashDotDot

dot

none

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalRangeFont
UnderlineStyle enum
Reference
Package: ExcelScript

Fields
ノ Expand table

double

none

single

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalTextOperator
enum
Reference
Package: ExcelScript

Represents the operator of the text conditional format type.

Remarks

Examples

TypeScript

/**
* This script adds conditional formatting to the first column in the
worksheet.
* This formatting gives the cells a green fill if they have text starting
with "Excel".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first column in the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const firstColumn = currentSheet.getRange("A:A");

// Add conditional formatting based on the text in the cells.


const textConditionFormat =

firstColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.containsT
ext).getTextComparison();

// Set the conditional format to provide a green fill.


textConditionFormat.getFormat().getFill().setColor("green");

// Apply the condition rule that the text begins with "Excel".
const textRule: ExcelScript.ConditionalTextComparisonRule = {
operator: ExcelScript.ConditionalTextOperator.beginsWith,
text: "Excel"
};
textConditionFormat.setRule(textRule);
}

Fields
ノ Expand table

beginsWith

contains

endsWith

invalid

notContains

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalTopBottom
CriterionType enum
Reference
Package: ExcelScript

Represents the criteria for the above/below average conditional format type.

Fields
ノ Expand table

bottomItems

bottomPercent

invalid

topItems

topPercent

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConnectorType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script adds a line that goes from cell B2 to cell F4 on the current
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
const sheet = workbook.getActiveWorksheet();

// Get the ranges for the two cells.


const b2Range = sheet.getRange("B2");
const f4Range = sheet.getRange("F4");

// Add a straight line that connects the top-left corners of both cells.
const line = sheet.addLine(
b2Range.getLeft(),
b2Range.getTop(),
f4Range.getLeft(),
f4Range.getTop(),
ExcelScript.ConnectorType.straight);
}

Fields
ノ Expand table

curve

elbow

straight
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ContentType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This sample creates a comment that mentions a specific person.
* That person will get a notification and link to the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell in the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const cell = currentSheet.getCell(0,0);

/* Create a CommentMention object for the comment.


*
* A CommentMention's properties are:
* `name`: The name of the person being mentioned.
* `id`: The zero-based index of this mention in the comment.
* `email`: The email address of the person being mentioned.
*/
const mention: ExcelScript.CommentMention = {
name: "Alex",
id: 0,
email: "[email protected]"
};

/* Create comment content that uses the mention.


* The `<at id="0">` syntax embeds the mention with ID 0 in the comment
text.
* The name is displayed in the comment,
* while an email is sent to the given address.
*/
const content: ExcelScript.CommentRichContent = {
richContent: '<at id="0">' + mention.name + "</at> - Hello!",
mentions: [mention]
};

// Add the comment.


currentSheet.addComment(cell, content, ExcelScript.ContentType.mention);
}
Fields
ノ Expand table

mention Comment content containing mentions.

plain Indicates a plain format type for the comment content.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DataValidationAlertStyle
enum
Reference
Package: ExcelScript

Represents the data validation error alert style. The default is Stop .

Remarks

Examples

TypeScript

/**
* This script creates a data validation rule for the range B1: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 B1:B5 in the active worksheet.
const currentSheet = workbook.getActiveWorksheet();
const positiveNumberOnlyCells = currentSheet.getRange("B1: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);
}
Fields
ノ Expand table

information

stop

warning

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DataValidationOperator
enum
Reference
Package: ExcelScript

Represents the data validation operator enum.

Remarks

Examples

TypeScript

/**
* This script creates a data validation rule for the range B1:B5.
* All values in that range must be a positive number.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range B1:B5 in the active worksheet.
const currentSheet = workbook.getActiveWorksheet();
const positiveNumberOnlyCells = currentSheet.getRange("B1: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);
}

Fields
ノ Expand table

between

equalTo
greaterThan

greaterThanOrEqualTo

lessThan

lessThanOrEqualTo

notBetween

notEqualTo

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DataValidationType enum
Reference
Package: ExcelScript

Represents the data validation type enum.

Remarks

Examples

TypeScript

/**
* This sample reads and logs the data validation type of the currently
selected range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the currently selected range.
let range = workbook.getSelectedRange();

// Get the type (`DataValidationType`) of data validation applied to the


range.
let validationType = range.getDataValidation().getType();

/*
* Log the data validation type.
* If the range has a single value, it logs that type.
* If the range doesn't have data validation applied, it logs "None".
* If the range has multiple different types of data validation, it logs
"Inconsistent" or "MixedCriteria".
*/
console.log(validationType.toString());
}

Fields
ノ Expand table

custom The custom data validation type.

date The date data validation type.

decimal The decimal data validation type.


inconsistent Inconsistent means that the range has inconsistent data validation, indicating
that there are different rules on different cells.

list The list data validation type.

mixedCriteria Mixed criteria means that the range has data validation present on some but not
all cells.

none None means allow any value, indicating that there is no data validation in the
range.

textLength The text length data validation type.

time The time data validation type.

wholeNumber The whole number data validation type.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DateFilterCondition enum
Reference
Package: ExcelScript

Enum representing all accepted conditions by which a date filter can be applied. Used to
configure the type of PivotFilter that is applied to the field.

Remarks

Examples

TypeScript

/**
* This script applies a filter to a PivotTable that filters out rows
* that aren't from this month.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the "Date Recorded" field to filter.
// The data in this field must be dates in order for the filter to work.
const pivot = workbook.getPivotTables()[0];
const rowHierarchy = pivot.getRowHierarchy("Date Recorded");
const rowField = rowHierarchy.getFields()[0];

// Apply the date filter.


rowField.applyFilter({
dateFilter: {
// Setting the condition to `thisMonth` means items that are before or
// after this month will not be displayed.
condition: ExcelScript.DateFilterCondition.thisMonth
}
});
}

Fields
ノ Expand table

after Date is after comparator date.

Required Criteria: { comparator }. Optional Criteria: { wholeDays }.

afterOrEqualTo Date is after or equal to comparator date.


Required Criteria: { comparator }. Optional Criteria: { wholeDays }.

allDatesInPeriodApril Date is in April.

allDatesInPeriodAugust Date is in August.

allDatesInPeriodDecember Date is in December.

allDatesInPeriodFebruary Date is in February.

allDatesInPeriodJanuary Date is in January.

allDatesInPeriodJuly Date is in July.

allDatesInPeriodJune Date is in June.

allDatesInPeriodMarch Date is in March.

allDatesInPeriodMay Date is in May.

allDatesInPeriodNovember Date is in November.

allDatesInPeriodOctober Date is in October.

allDatesInPeriodQuarter1 Date is in Quarter 1.

allDatesInPeriodQuarter2 Date is in Quarter 2.

allDatesInPeriodQuarter3 Date is in Quarter 3.

allDatesInPeriodQuarter4 Date is in Quarter 4.

allDatesInPeriodSeptember Date is in September.

before Date is before comparator date.

Required Criteria: { comparator }. Optional Criteria: { wholeDays }.

beforeOrEqualTo Date is before or equal to comparator date.

Required Criteria: { comparator }. Optional Criteria: { wholeDays }.

between Between lowerBound and upperBound dates.

Required Criteria: { lowerBound , upperBound }. Optional Criteria:


{ wholeDays , exclusive }.

equals Equals comparator criterion.

Required Criteria: { comparator }. Optional Criteria: { wholeDays ,


exclusive }.

lastMonth Date is last month.


lastQuarter Date is last quarter.

lastWeek Date is last week.

lastYear Date is last year.

nextMonth Date is next month.

nextQuarter Date is next quarter.

nextWeek Date is next week.

nextYear Date is next year.

thisMonth Date is this month.

thisQuarter Date is this quarter.

thisWeek Date is this week.

thisYear Date is this year.

today Date is today.

tomorrow Date is tomorrow.

unknown DateFilterCondition is unknown or unsupported.

yearToDate Date is in the same year to date.

yesterday Date is yesterday.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DeleteShiftDirection enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This sample creates a sample range, then deletes
* "A1" using different DeleteShiftDirection values.
*/
function main(workbook: ExcelScript.Workbook) {
// Add sample data to better visualize the delete changes.
const currentSheet = workbook.getActiveWorksheet();
currentSheet.getRange("A1:D4").setValues([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]);

// Delete A1 and shift the cells from the right to fill the space.
// The value being deleted is 1.
currentSheet.getRange("A1").delete(ExcelScript.DeleteShiftDirection.left);

// Delete A1 and shift the cells from the bottom to fill the space.
// The value being deleted is 2.
currentSheet.getRange("A1").delete(ExcelScript.DeleteShiftDirection.up);

// Log the sample range. The values should be:


/*
5, 3, 4, "",
9, 6, 7, 8,
13, 10, 11, 12,
"", 14, 15, 16
*/
console.log(currentSheet.getRange("A1:D4").getValues());
}

Fields
ノ Expand table
left

up

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DocumentPropertyType
enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script uses a custom property to set the value and formatting of a
cell.
* If the value of "Routing Number" is not set or is not a number, the cell
will be red.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell from Sheet1.
const cell = workbook.getWorksheet("Sheet1").getCell(0,0);

// Get the "Routing Number" property.


const properties = workbook.getProperties();
const routingNumber = properties.getCustomProperty("Routing Number");

// If the property is missing or is not a number, change the formatting to


indicate a problem.
if (!routingNumber || routingNumber.getType() !=
ExcelScript.DocumentPropertyType.number) {
cell.getFormat().getFill().setColor("red");
}

// If the property exists, use it to set the value of A1.


if (routingNumber) {
cell.setValue(routingNumber.getValue());
}
}

Fields
ノ Expand table

boolean
date

float

number

string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DynamicFilterCriteria enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script applies a filter to a table that filters it
* to only show rows with dates from the previous month.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the table named "ReportTable".
const table = workbook.getTable("ReportTable");

// Get the column with the header "Date".


const dateColumn = table.getColumnByName("Date");

// Apply a dynamic filter to the column.


// `lastMonth` will only show rows with a date from the previous month.

dateColumn.getFilter().applyDynamicFilter(ExcelScript.DynamicFilterCriteria.
lastMonth);
}

Fields
ノ Expand table

aboveAverage

allDatesInPeriodApril

allDatesInPeriodAugust

allDatesInPeriodDecember

allDatesInPeriodFebruary

allDatesInPeriodJanuary

allDatesInPeriodJuly
allDatesInPeriodJune

allDatesInPeriodMarch

allDatesInPeriodMay

allDatesInPeriodNovember

allDatesInPeriodOctober

allDatesInPeriodQuarter1

allDatesInPeriodQuarter2

allDatesInPeriodQuarter3

allDatesInPeriodQuarter4

allDatesInPeriodSeptember

belowAverage

lastMonth

lastQuarter

lastWeek

lastYear

nextMonth

nextQuarter

nextWeek

nextYear

thisMonth

thisQuarter

thisWeek

thisYear

today

tomorrow

unknown

yearToDate
yesterday

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.FillPattern enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script sets a black-checkered fill on the selected range.
*/
function main(workbook: ExcelScript.Workbook) {
const selected = workbook.getSelectedRange();

selected.getFormat().getFill().setPattern(ExcelScript.FillPattern.checker);
selected.getFormat().getFill().setPatternColor("black");
}

Fields
ノ Expand table

checker

crissCross

down

gray16

gray25

gray50

gray75

gray8

grid

horizontal

lightDown
lightHorizontal

lightUp

lightVertical

linearGradient

none

rectangularGradient

semiGray75

solid

up

vertical

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.FilterDatetimeSpecificity
enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script applies a filter to a PivotTable that filters it
* to only show rows from between June 20th, 2022 and July 10th, 2022.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the "Date Recorded" field to filter.
// The data in this field must be dates in order for the filter to work.
const pivot = workbook.getPivotTables()[0];
const rowHierarchy = pivot.getRowHierarchy("Date Recorded");
const rowField = rowHierarchy.getFields()[0];

// Create the filter's date boundaries.


let earliestDate: ExcelScript.FilterDatetime = {
date: "2022-06-20",
specificity: ExcelScript.FilterDatetimeSpecificity.day
};
let latestDate: ExcelScript.FilterDatetime = {
date: "2022-07-10",
specificity: ExcelScript.FilterDatetimeSpecificity.day
};

// Apply the date filter.


rowField.applyFilter({
dateFilter: {
condition: ExcelScript.DateFilterCondition.between,
lowerBound: earliestDate,
upperBound: latestDate
}
});
}

Fields
ノ Expand table

day

hour

minute

month

second

year

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.FilterOn enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script applies a filter to a table so that
* only rows with values in column 1 that start with "L" are shown.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the autoFilter of the first table in the current worksheet.
const table = workbook.getActiveWorksheet().getTables()[0];
const autoFilter = table.getAutoFilter();

// Filter to only include values that start with "L".


const filterCriteria: ExcelScript.FilterCriteria = {
filterOn: ExcelScript.FilterOn.custom,
criterion1: "L*"
};

// Apply the filter to column 1 (zero-based).


autoFilter.apply(table.getRange(), 1, filterCriteria);
}

Fields
ノ Expand table

bottomItems

bottomPercent

cellColor

custom

dynamic

fontColor
icon

topItems

topPercent

values

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.FilterOperator enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* The script filters rows from a table based on a numerical range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const table = currentSheet.getTables()[0];

// Filter to only show rows with a value in the "Exam Score" column that
is
// greater than 0 and less than or equal to 60.
table.getColumnByName("Exam Score").getFilter().applyCustomFilter(">0", "
<=60", ExcelScript.FilterOperator.and);
}

Fields
ノ Expand table

and

or

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our  Provide product feedback
contributor guide.
ExcelScript.GeometricShapeType enum
Reference
Package: ExcelScript

Specifies the shape type for a GeometricShape object.

Remarks

Examples

TypeScript

/**
* This script creates a hexagon shape on the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const hexagon: ExcelScript.Shape =
currentSheet.addGeometricShape(ExcelScript.GeometricShapeType.hexagon);

// Set the hexagon size to 40x40 pixels.


hexagon.setHeight(40);
hexagon.setWidth(40);

// Position the hexagon at [100,100] pixels.


hexagon.setLeft(100);
hexagon.setTop(100);
}

Fields
ノ Expand table

accentBorderCallout1

accentBorderCallout2

accentBorderCallout3

accentCallout1

accentCallout2

accentCallout3
actionButtonBackPrevious

actionButtonBeginning

actionButtonBlank

actionButtonDocument

actionButtonEnd

actionButtonForwardNext

actionButtonHelp

actionButtonHome

actionButtonInformation

actionButtonMovie

actionButtonReturn

actionButtonSound

arc

bentArrow

bentUpArrow

bevel

blockArc

borderCallout1

borderCallout2

borderCallout3

bracePair

bracketPair

callout1

callout2

callout3

can

chartPlus
chartStar

chartX

chevron

chord

circularArrow

cloud

cloudCallout

corner

cornerTabs

cube

curvedDownArrow

curvedLeftArrow

curvedRightArrow

curvedUpArrow

decagon

diagonalStripe

diamond

dodecagon

donut

doubleWave

downArrow

downArrowCallout

ellipse

ellipseRibbon

ellipseRibbon2

flowChartAlternateProcess

flowChartCollate
flowChartConnector

flowChartDecision

flowChartDelay

flowChartDisplay

flowChartDocument

flowChartExtract

flowChartInputOutput

flowChartInternalStorage

flowChartMagneticDisk

flowChartMagneticDrum

flowChartMagneticTape

flowChartManualInput

flowChartManualOperation

flowChartMerge

flowChartMultidocument

flowChartOfflineStorage

flowChartOffpageConnector

flowChartOnlineStorage

flowChartOr

flowChartPredefinedProcess

flowChartPreparation

flowChartProcess

flowChartPunchedCard

flowChartPunchedTape

flowChartSort

flowChartSummingJunction

flowChartTerminator
foldedCorner

frame

funnel

gear6

gear9

halfFrame

heart

heptagon

hexagon

homePlate

horizontalScroll

irregularSeal1

irregularSeal2

leftArrow

leftArrowCallout

leftBrace

leftBracket

leftCircularArrow

leftRightArrow

leftRightArrowCallout

leftRightCircularArrow

leftRightRibbon

leftRightUpArrow

leftUpArrow

lightningBolt

lineInverse

mathDivide
mathEqual

mathMinus

mathMultiply

mathNotEqual

mathPlus

moon

nonIsoscelesTrapezoid

noSmoking

notchedRightArrow

octagon

parallelogram

pentagon

pie

pieWedge

plaque

plaqueTabs

plus

quadArrow

quadArrowCallout

rectangle

ribbon

ribbon2

rightArrow

rightArrowCallout

rightBrace

rightBracket

rightTriangle
round1Rectangle

round2DiagonalRectangle

round2SameRectangle

roundRectangle

smileyFace

snip1Rectangle

snip2DiagonalRectangle

snip2SameRectangle

snipRoundRectangle

squareTabs

star10

star12

star16

star24

star32

star4

star5

star6

star7

star8

stripedRightArrow

sun

swooshArrow

teardrop

trapezoid

triangle

upArrow
upArrowCallout

upDownArrow

upDownArrowCallout

uturnArrow

verticalScroll

wave

wedgeEllipseCallout

wedgeRectCallout

wedgeRRectCallout

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.GroupOption enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script creates a two-level column-based outline on Sheet1.
*/
function main(workbook: ExcelScript.Workbook) {
// Group columns A-F in the worksheet named Sheet1.
const sheet = workbook.getWorksheet("Sheet1");
const firstLevel = sheet.getRange("A:F");
firstLevel.group(ExcelScript.GroupOption.byColumns);

// Create a second level to the outline by grouping subsections.


sheet.getRange("A:B").group(ExcelScript.GroupOption.byColumns);
sheet.getRange("D:E").group(ExcelScript.GroupOption.byColumns);
}

Fields
ノ Expand table

byColumns Group by columns.

byRows Group by rows.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.HeaderFooterState enum
Reference
Package: ExcelScript

Fields
ノ Expand table

default Only one general header/footer is used for all pages printed.

firstAndDefault There is a separate first page header/footer, and a general header/footer used
for all other pages.

firstOddAndEven There is a separate first page header/footer, then there is a separate


header/footer for odd and even pages.

oddAndEven There is a different header/footer for odd and even pages.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.HorizontalAlignment enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script centers the text in a table's header row cells.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const table = currentSheet.getTables()[0];

// Get the header range.


const headerRange = table.getHeaderRowRange();

// Set the horizontal text alignment to `center`.

headerRange.getFormat().setHorizontalAlignment(ExcelScript.HorizontalAlignme
nt.center);
}

Fields
ノ Expand table

center

centerAcrossSelection

distributed

fill

general

justify

left
right

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.IconSet enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script applies icon set conditional formatting to a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range "A1:A5" on the current worksheet.
const sheet = workbook.getActiveWorksheet();
const range = sheet.getRange("A1:A5");

// Create icon set conditional formatting on the range.


const conditionalFormatting =
range.addConditionalFormat(ExcelScript.ConditionalFormatType.iconSet);

// Use the "3 Traffic Lights (Unrimmed)" set.

conditionalFormatting.getIconSet().setStyle(ExcelScript.IconSet.threeTraffic
Lights1);

// Set the criteria to use a different icon for the bottom, middle, and
top thirds of the values in the range.
conditionalFormatting.getIconSet().setCriteria([
{

formula:'=0',operator:ExcelScript.ConditionalIconCriterionOperator.greaterTh
anOrEqual,
type:ExcelScript.ConditionalFormatIconRuleType.percent
},
{

formula:'=33',operator:ExcelScript.ConditionalIconCriterionOperator.greaterT
hanOrEqual,
type:ExcelScript.ConditionalFormatIconRuleType.percent},
{

formula:'=67',operator:ExcelScript.ConditionalIconCriterionOperator.greaterT
hanOrEqual,
type:ExcelScript.ConditionalFormatIconRuleType.percent
}]);
}
Fields
ノ Expand table

fiveArrows

fiveArrowsGray

fiveBoxes

fiveQuarters

fiveRating

fourArrows

fourArrowsGray

fourRating

fourRedToBlack

fourTrafficLights

invalid

threeArrows

threeArrowsGray

threeFlags

threeSigns

threeStars

threeSymbols

threeSymbols2

threeTrafficLights1

threeTrafficLights2

threeTriangles

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
be found on GitHub, where you Select a link to provide feedback:
can also create and review
issues and pull requests. For  Open a documentation issue
more information, see our
contributor guide.  Provide product feedback
ExcelScript.ImageFittingMode enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script returns an image of the first chart in the first worksheet.
* That image is 600x400 pixels and the chart will be
* stretched to fill those dimensions.
* The returned image can be used in a Power Automate flow.
*/
function main(workbook: ExcelScript.Workbook): string {
// Get the first chart in the first worksheet.
const firstSheet = workbook.getFirstWorksheet();
const firstChart = firstSheet.getCharts()[0];

// Get an image of the chart as a base64-encoded string.


const base64String = firstChart.getImage(
600, /* Width */
400, /* Height */
ExcelScript.ImageFittingMode.fill /* Fill to match the dimensions. */
);

return base64String;
}

Fields
ノ Expand table

fill

fit

fitAndCenter
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.InsertShiftDirection enum
Reference
Package: ExcelScript

Determines the direction in which existing cells will be shifted to accommodate what is
being inserted.

Remarks

Examples

TypeScript

/**
* This script inserts headers at the top of the worksheet.
*/
function main(workbook: ExcelScript.Workbook)
{
let currentSheet = workbook.getActiveWorksheet();

// Create headers for 3 columns.


let myHeaders = [["NAME", "ID", "ROLE"]];

// Add a blank first row and push existing data down a row.
let firstRow = currentSheet.getRange("1:1");
firstRow.insert(ExcelScript.InsertShiftDirection.down);

// Add the headers.


currentSheet.getRange("A1:C1").setValues(myHeaders);
}

Fields
ノ Expand table

down

right
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.KeyboardDirection enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script makes the font bold on all the contiguous cells between
* A1 and the bottom of the used range of the first column.
*/
function main(workbook: ExcelScript.Workbook)
{
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get every cell that's used between A1 and the end of the column.
// This recreates the Ctrl+Shift+Down arrow key behavior.
let firstCell = selectedSheet.getRange("A1");
let firstColumn =
firstCell.getExtendedRange(ExcelScript.KeyboardDirection.down);

// Set the font to bold in that range.


firstColumn.getFormat().getFont().setBold(true);
}

Fields
ノ Expand table

down

left

right

up
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.LabelFilterCondition enum
Reference
Package: ExcelScript

Enum representing all accepted conditions by which a label filter can be applied. Used
to configure the type of PivotFilter that is applied to the field.
PivotFilter.criteria.exclusive can be set to true to invert many of these conditions.

Remarks

Examples

TypeScript

/**
* This script filters items that start with "L" from the "Type" field
* of the "Farm Sales" PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable.
const pivotTable = workbook.getActiveWorksheet().getPivotTable("Farm
Sales");

// Get the "Type" field.


const field = pivotTable.getHierarchy("Type").getPivotField("Type");

// Filter out any types that start with "L" (such as "Lemons" and
"Limes").
const filter: ExcelScript.PivotLabelFilter = {
condition: ExcelScript.LabelFilterCondition.beginsWith,
substring: "L",
exclusive: true
};

// Apply the label filter to the field.


field.applyFilter({ labelFilter: filter });
}

Fields
ノ Expand table

beginsWith Label begins with substring criterion.


Required Criteria: { substring }. Optional Criteria: { exclusive }.

between Between lowerBound and upperBound criteria.

Required Criteria: { lowerBound , upperBound }. Optional Criteria:


{ exclusive }.

contains Label contains substring criterion.

Required Criteria: { substring }. Optional Criteria: { exclusive }.

endsWith Label ends with substring criterion.

Required Criteria: { substring }. Optional Criteria: { exclusive }.

equals Equals comparator criterion.

Required Criteria: { comparator }. Optional Criteria: { exclusive }.

greaterThan Greater than comparator criterion.

Required Criteria: { comparator }.

greaterThanOrEqualTo Greater than or equal to comparator criterion.

Required Criteria: { comparator }.

lessThan Less than comparator criterion.

Required Criteria: { comparator }.

lessThanOrEqualTo Less than or equal to comparator criterion.

Required Criteria: { comparator }.

unknown LabelFilterCondition is unknown or unsupported.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.LinkedDataTypeState enum
Reference
Package: ExcelScript

Fields
ノ Expand table

brokenLinkedData

disambiguationNeeded

fetchingData

none

validLinkedData

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.LoadToType enum
Reference
Package: ExcelScript

An enum that specifies the query load to destination.

Fields
ノ Expand table

connectionOnly Load to connection only.

pivotChart Load to PivotChart.

pivotTable Load to PivotTable.

table Load to a table.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.NamedItemScope enum
Reference
Package: ExcelScript

Fields
ノ Expand table

workbook

worksheet

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.NamedItemType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script looks for every named range with "Review" in the name
* and marks the range with a yellow fill.
*/
function main(workbook: ExcelScript.Workbook) {
// Look at every named item in the workbook.
workbook.getNames().forEach((namedItem) => {
// Find names containing "Review".
if (namedItem.getName().includes("Review")) {
// Only change the fill color if the named item is a range (not a
formula).
let itemType: ExcelScript.NamedItemType = namedItem.getType();
if (itemType === ExcelScript.NamedItemType.range) {
// Set the range's fill color to yellow.
namedItem.getRange().getFormat().getFill().setColor("yellow");
}
}
});
}

Fields
ノ Expand table

array

boolean

double

error

integer

range
string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.NumberFormatCategory
enum
Reference
Package: ExcelScript

Represents a category of number formats.

Remarks

Examples

TypeScript

/**
* This script finds cells in a table column that are not formatted as
currency
* and sets the fill color to red.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the "Cost" column from the "Expenses" table.
const table = workbook.getTable("Expenses");
const costColumn = table.getColumnByName("Cost");
const costColumnRange = costColumn.getRangeBetweenHeaderAndTotal();

// Get the number format categories for the column's range.


const numberFormatCategories =
costColumnRange.getNumberFormatCategories();

// If any cell in the column doesn't have a currency format, make the cell
red.
numberFormatCategories.forEach((category, index) =>{
if (category[0] != ExcelScript.NumberFormatCategory.currency) {
costColumnRange.getCell(index,
0).getFormat().getFill().setColor("red");
}
});
}

Fields
ノ Expand table

accounting Accounting formats line up the currency symbols and decimal points in a column.
currency Currency formats are used for general monetary values. Use Accounting formats to
align decimal points in a column.

custom A custom format that is not a part of any category.

date Date formats display date and time serial numbers as date values. Date formats that
begin with an asterisk (*) respond to changes in regional date and time settings that
are specified for the operating system. Formats without an asterisk are not affected
by operating system settings.

fraction Fraction formats display the cell value as a whole number with the remainder
rounded to the nearest fraction value.

general General format cells have no specific number format.

number Number is used for general display of numbers. Currency and Accounting offer
specialized formatting for monetary value.

percentage Percentage formats multiply the cell value by 100 and displays the result with a
percent symbol.

scientific Scientific formats display the cell value as a number between 1 and 10 multiplied by
a power of 10.

special Special formats are useful for tracking list and database values.

text Text format cells are treated as text even when a number is in the cell. The cell is
displayed exactly as entered.

time Time formats display date and time serial numbers as date values. Time formats that
begin with an asterisk (*) respond to changes in regional date and time settings that
are specified for the operating system. Formats without an asterisk are not affected
by operating system settings.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PageOrientation enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script sets the printing orientation for the entire workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Go to each worksheet so the print settings are consistent.
workbook.getWorksheets().forEach((sheet) => {
const pageLayout = sheet.getPageLayout();

// Print every page with a landscape orientation.


pageLayout.setOrientation(ExcelScript.PageOrientation.landscape);
});
}

Fields
ノ Expand table

landscape

portrait
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PaperType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script sets the page size for printing.
*/
function main(workbook: ExcelScript.Workbook) {
// Go to each worksheet so the print settings are consistent.
workbook.getWorksheets().forEach((sheet) => {
const pageLayout = sheet.getPageLayout();
// Print on 8.5"x11" paper.
pageLayout.setPaperSize(ExcelScript.PaperType.letter);
});
}

Fields
ノ Expand table

a3

a4

a4Small

a5

b4

b5

csheet

dsheet

envelope10

envelope11
envelope12

envelope14

envelope9

envelopeB4

envelopeB5

envelopeB6

envelopeC3

envelopeC4

envelopeC5

envelopeC6

envelopeC65

envelopeDL

envelopeItaly

envelopeMonarch

envelopePersonal

esheet

executive

fanfoldLegalGerman

fanfoldStdGerman

fanfoldUS

folio

ledger

legal

letter

letterSmall

note

paper10x14
paper11x17

quatro

statement

tabloid

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PictureFormat enum
Reference
Package: ExcelScript

The format of the image.

Remarks

Examples

TypeScript

/**
* This script creates a star shape with the value from cell A1.
* It then returns the image as a base64-encoded string.
* This string would be used as part of a Power Automate flow to add the
image elsewhere.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the value of A1 from the worksheet named Sheet1.
const sheet = workbook.getWorksheet("Sheet1");
const value = sheet.getRange("A1").getValue();

// Create a Shape object that looks like a 5-pointed star.


const star =
sheet.addGeometricShape(ExcelScript.GeometricShapeType.star5);

// Set the text of star and make sure the shape fits the text.
const textFrame = star.getTextFrame();
textFrame.getTextRange().setText(value.toString());

textFrame.setAutoSizeSetting(ExcelScript.ShapeAutoSize.autoSizeShapeToFitTex
t);

// Return the shape as a PNG image represented by a base64-encoded string.


return star.getAsImage(ExcelScript.PictureFormat.png);
}

Fields
ノ Expand table

bmp Bitmap image.


gif Graphics Interchange Format.

jpeg Joint Photographic Experts Group.

png Portable Network Graphics.

svg Scalable Vector Graphic.

unknown

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotAxis enum
Reference
Package: ExcelScript

Represents the axis from which to get the PivotItems.

Fields
ノ Expand table

column The column axis.

data The data axis.

filter The filter axis.

row The row axis.

unknown The axis or region is unknown or unsupported.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotFilterTopBottom
Criterion enum
Reference
Package: ExcelScript

Represents the criteria for the top/bottom values filter.

Fields
ノ Expand table

bottomItems

bottomPercent

bottomSum

invalid

topItems

topPercent

topSum

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotFilterType enum
Reference
Package: ExcelScript

A simple enum that represents a type of filter for a PivotField.

Remarks

Examples

TypeScript

/**
* This script gets the "Type" field from the "Farms Sales" PivotTable
* and clears the value filter from it.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Sales".
const pivot = workbook.getPivotTable("Farm Sales");

// Get the "Type" field.


const typeField = pivot.getHierarchy("Type").getPivotField("Type");

// Clear the value filter (if there is one) from the field.
typeField.clearFilter(ExcelScript.PivotFilterType.value);
}

Fields
ノ Expand table

date Filters PivotItems with a date in place of a label. Note: A PivotField cannot
simultaneously have a label filter and a date filter applied.

label Filters PivotItems based on their labels. Note: A PivotField cannot simultaneously have
a label filter and a date filter applied.

manual Filters specific manually selected PivotItems from the PivotTable.

unknown PivotFilterType is unknown or unsupported.

value Filters based on the value of a PivotItem with respect to a DataPivotHierarchy .


6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotLayoutType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script sets the layout of the "Farms Sales" PivotTable to the
"tabular"
* setting. This places the fields from the Rows area in separate columns.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Sales".
const pivot = workbook.getPivotTable("Farm Sales");

// Get the PivotLayout object.


const layout = pivot.getLayout();

// Set the layout type to "tabular".


layout.setLayoutType(ExcelScript.PivotLayoutType.tabular);
}

Fields
ノ Expand table

compact A horizontally compressed form with labels from the next field in the same column.

outline Inner fields' items are on same row as outer fields' items and subtotals are always on
the bottom.

tabular Inner fields' items are always on a new line relative to the outer fields' items.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
Select a link to provide feedback:
The source for this content can
be found on GitHub, where you  Open a documentation issue
can also create and review
issues and pull requests. For  Provide product feedback
more information, see our
contributor guide.
ExcelScript.Placement enum
Reference
Package: ExcelScript

Specifies the way that an object is attached to its underlying cells.

Remarks

Examples

TypeScript

/**
* This script creates a diamond shape at cell C3.
* The shape moves and resizes as the grid underneath it changes.
*/
function main(workbook: ExcelScript.Workbook) {
// Get cell C3 in the current worksheet.
const sheet = workbook.getActiveWorksheet();
const cell = sheet.getRange("C3");

// Create a diamond that slightly overlaps the cell C3.


const diamond =
sheet.addGeometricShape(ExcelScript.GeometricShapeType.diamond);
// Set each dimension so that the shape extends 5 pixels beyond the cell
borders.
diamond.setLeft(cell.getLeft() - 5);
diamond.setTop(cell.getTop() - 5);
diamond.setHeight(cell.getHeight() + 10);
diamond.setWidth(cell.getWidth() + 10);

// Set the placement of the shape so that it resizes and moves with the
grid.
diamond.setPlacement(ExcelScript.Placement.twoCell);
}

Fields
ノ Expand table

absolute The object is free floating.

oneCell The object is moved with the cells.


twoCell The object is moved and sized with the cells.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PrintComments enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script makes the comments print at the end of the worksheet
* when the workbook is printed.
*/
function main(workbook: ExcelScript.Workbook) {
// Access every worksheet in the workbook.
workbook.getWorksheets().forEach(worksheet => {
// Get the page layout for each sheet.
const layout = worksheet.getPageLayout();

// Change the comment printing settings to print them at the end of the
sheet.
layout.setPrintComments(ExcelScript.PrintComments.endSheet);
});
}

Fields
ノ Expand table

endSheet Comments will be printed as end notes at the end of the worksheet.

inPlace Comments will be printed where they were inserted in the worksheet.

noComments Comments will not be printed.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review  Open a documentation issue
issues and pull requests. For
more information, see our  Provide product feedback
contributor guide.
ExcelScript.PrintErrorType enum
Reference
Package: ExcelScript

Fields
ノ Expand table

asDisplayed

blank

dash

notAvailable

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PrintMarginUnit enum
Reference
Package: ExcelScript

Fields
ノ Expand table

centimeters Assign the page margins in centimeters.

inches Assign the page margins in inches.

points Assign the page margins in points. A point is 1/72 of an inch.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PrintOrder enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script sets the print order for every worksheet in the workbook.
* The order of printed content will go over (e.g., left-to-right)
* then down (i.e., top-to-bottom).
*/
function main(workbook: ExcelScript.Workbook) {
// Access every worksheet in the workbook.
workbook.getWorksheets().forEach(worksheet => {
// Get the page layout for each sheet.
const layout: ExcelScript.PageLayout = worksheet.getPageLayout();

// Set the print order to over-then-down.


layout.setPrintOrder(ExcelScript.PrintOrder.overThenDown);
});
}

Fields
ノ Expand table

downThenOver Process down the rows before processing across pages or page fields to the
right.

overThenDown Process across pages or page fields to the right before moving down the rows.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our  Provide product feedback
contributor guide.
ExcelScript.ProtectionSelectionMode
enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script protects cells from being selected on the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the protection settings for the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const sheetProtection = currentSheet.getProtection();

// Create a new WorksheetProtectionOptions object with the selectionMode


property set to `none`.
let protectionOptions : ExcelScript.WorksheetProtectionOptions = {
selectionMode: ExcelScript.ProtectionSelectionMode.none
}

// Apply the given protection options.


sheetProtection.protect(protectionOptions);
}

Fields
ノ Expand table

none Selection is not allowed for any cells.

normal Selection is allowed for all cells.

unlocked Selection is allowed only for cells that are not locked.
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.QueryError enum
Reference
Package: ExcelScript

An enum that specifies the query load error message.

Fields
ノ Expand table

failedDownload Download failed.

failedLoadToDataModel Load to the data model failed.

failedLoadToWorksheet Load to the worksheet failed.

failedToCompleteDownload Download did not complete.

none No error.

unknown Unknown error.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RangeCopyType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script copies all of the values from the current worksheet to a new
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range on the current worksheet.
let usedRange = workbook.getActiveWorksheet().getUsedRange();

// Create a new worksheet with a default name.


let newSheet = workbook.addWorksheet();

// Copy the values from the used range to the new worksheet.
let copyType = ExcelScript.RangeCopyType.values; /* Change this to copy
different information, such as formats. */
let targetRange = newSheet.getRangeByIndexes(
usedRange.getRowIndex(),
usedRange.getColumnIndex(),
usedRange.getRowCount(),
usedRange.getColumnCount());
targetRange.copyFrom(usedRange, copyType);

// Switch the view to the new worksheet.


newSheet.activate();
}

Fields
ノ Expand table

all

formats

formulas
link

values

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RangeUnderlineStyle enum
Reference
Package: ExcelScript

Fields
ノ Expand table

double

doubleAccountant

none

single

singleAccountant

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RangeValueType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script formats rows in a worksheet based on the first value in that
row.
* If it's the boolean value TRUE, the row is bolded.
* If it's FALSE, nothing is changed.
* If the value type isn't a boolean, the row is italicized.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range in the active worksheet.
const sheet = workbook.getActiveWorksheet();
const usedRange = sheet.getUsedRange();

// Get the values in the first column.


const firstColumnValues = usedRange.getColumn(0).getValues();

// Look at the first cell in each row.


const rowCount = usedRange.getRowCount();
for (let i = 0; i < rowCount; i++) {
// Get the type of the first cell to make sure it's a boolean.
let firstValueType = usedRange.getCell(i, 0).getValueType();

// Set the bold or italic of the row as described earlier.


if (firstValueType === ExcelScript.RangeValueType.boolean) {
if (firstColumnValues[i][0] as boolean === true) {
usedRange.getRow(i).getFormat().getFont().setBold(true);
} else {
usedRange.getRow(i).getFormat().getFont().setBold(false);
}
} else {
usedRange.getRow(i).getFormat().getFont().setItalic(true);
}
}
}

Fields
ノ Expand table

boolean

double

empty

error

integer

richValue

string

unknown

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ReadingOrder enum
Reference
Package: ExcelScript

Fields
ノ Expand table

context Reading order is determined by the language of the first character entered. If a
right-to-left language character is entered first, reading order is right to left. If a left-
to-right language character is entered first, reading order is left to right.

leftToRight Left to right reading order

rightToLeft Right to left reading order

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SearchDirection enum
Reference
Package: ExcelScript

Specifies the search direction.

Remarks

Examples

TypeScript

/**
* This script searches for the next instance of the text "TK" on the
current worksheet.
* It then selects that cell and removes "TK" and all formatting from the
cell.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range on the current worksheet.
let range = workbook.getActiveWorksheet().getUsedRange();

// Get the next cell that contains "TK".


let tkCell = range.find("TK", {
completeMatch: true, /* Don't match if the cell text only contains "TK"
as part of another string. */
matchCase: false,
searchDirection: ExcelScript.SearchDirection.forward /* Start at the
beginning of the range and go to later columns and rows. */
});

// Set focus on the found cell.


tkCell.select();

// Remove the "TK" text value from the cell, as well as any formatting
that may have been added.
tkCell.clear(ExcelScript.ClearApplyTo.all);
}

Fields
ノ Expand table

backwards Search in reverse order.


forward Search in forward order.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeAutoSize enum
Reference
Package: ExcelScript

Determines the type of automatic sizing allowed.

Remarks

Examples

TypeScript

/**
* This script creates a star shape with the value from cell A1.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the value of A1 from the worksheet named Sheet1.
const sheet = workbook.getWorksheet("Sheet1");
const value = sheet.getRange("A1").getValue();

// Create a Shape object that looks like a 5-pointed star.


const star =
sheet.addGeometricShape(ExcelScript.GeometricShapeType.star5);

// Set the text of star and make sure the shape fits the text.
const textFrame = star.getTextFrame();
textFrame.getTextRange().setText(value.toString());

textFrame.setAutoSizeSetting(ExcelScript.ShapeAutoSize.autoSizeShapeToFitTex
t);
}

Fields
ノ Expand table

autoSizeMixed A combination of automatic sizing schemes are used.

autoSizeNone No autosizing.

autoSizeShapeToFitText The shape is adjusted to fit the text.

autoSizeTextToFitShape The text is adjusted to fit the shape.


6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeFillType enum
Reference
Package: ExcelScript

Specifies a shape's fill type.

Fields
ノ Expand table

gradient Gradient fill.

mixed Mixed fill.

noFill No fill.

pattern Pattern fill.

pictureAndTexture Picture and texture fill.

solid Solid fill.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeFontUnderlineStyle
enum
Reference
Package: ExcelScript

The type of underline applied to a font.

Fields
ノ Expand table

dash

dashHeavy

dashLong

dashLongHeavy

dotDash

dotDashHeavy

dotDotDash

dotDotDashHeavy

dotted

dottedHeavy

double

heavy

none

single

wavy

wavyDouble

wavyHeavy
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeLineDashStyle enum
Reference
Package: ExcelScript

The dash style for a line.

Fields
ノ Expand table

dash

dashDot

dashDotDot

longDash

longDashDot

longDashDotDot

roundDot

solid

squareDot

systemDash

systemDashDot

systemDot

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeLineStyle enum
Reference
Package: ExcelScript

The style for a line.

Fields
ノ Expand table

single Single line.

thickBetweenThin Thick line with a thin line on each side.

thickThin Thick line next to thin line. For horizontal lines, the thick line is above the thin
line. For vertical lines, the thick line is to the left of the thin line.

thinThick Thick line next to thin line. For horizontal lines, the thick line is below the thin
line. For vertical lines, the thick line is to the right of the thin line.

thinThin Two thin lines.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeScaleFrom enum
Reference
Package: ExcelScript

Specifies which part of the shape retains its position when the shape is scaled.

Fields
ノ Expand table

scaleFromBottomRight

scaleFromMiddle

scaleFromTopLeft

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeScaleType enum
Reference
Package: ExcelScript

Specifies whether the shape is scaled relative to its original or current size.

Fields
ノ Expand table

currentSize

originalSize

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeTextHorizontal
Alignment enum
Reference
Package: ExcelScript

Specifies the horizontal alignment for the text frame in a shape.

Fields
ノ Expand table

center

distributed

justify

justifyLow

left

right

thaiDistributed

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeTextHorizontal
Overflow enum
Reference
Package: ExcelScript

Specifies the horizontal overflow for the text frame in a shape.

Fields
ノ Expand table

clip

overflow

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeTextOrientation enum
Reference
Package: ExcelScript

Specifies the orientation for the text frame in a shape.

Fields
ノ Expand table

eastAsianVertical

horizontal

mongolianVertical

vertical

vertical270

wordArtVertical

wordArtVerticalRTL

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeTextReadingOrder
enum
Reference
Package: ExcelScript

Specifies the reading order for the text frame in a shape.

Fields
ノ Expand table

leftToRight

rightToLeft

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeTextVerticalAlignment
enum
Reference
Package: ExcelScript

Specifies the vertical alignment for the text frame in a shape.

Fields
ノ Expand table

bottom

distributed

justified

middle

top

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeTextVerticalOverflow
enum
Reference
Package: ExcelScript

Specifies the vertical overflow for the text frame in a shape.

Fields
ノ Expand table

clip Hide text that does not fit vertically within the text frame.

ellipsis Hide text that does not fit vertically within the text frame, and add an ellipsis (...) at the
end of the visible text.

overflow Allow text to overflow the text frame vertically (can be from the top, bottom, or both
depending on the text alignment).

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeType enum
Reference
Package: ExcelScript

Specifies the type of a shape.

Fields
ノ Expand table

geometricShape

group

image

line

unsupported

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeZOrder enum
Reference
Package: ExcelScript

Specifies where in the z-order a shape should be moved relative to other shapes.

Fields
ノ Expand table

bringForward

bringToFront

sendBackward

sendToBack

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SheetVisibility enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script unhides all the worksheets in the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Iterate over each worksheet.
workbook.getWorksheets().forEach((worksheet) => {
// Set the worksheet visibility to visible.
worksheet.setVisibility(ExcelScript.SheetVisibility.visible);
});
}

Fields
ノ Expand table

hidden

veryHidden

visible
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShowAsCalculation enum
Reference
Package: ExcelScript

The ShowAs calculation function for the DataPivotField.

Remarks

Examples

TypeScript

/**
* The script changes the display for "Crates Sold at Farm".
* It shows the percentage of the grand total,
* instead of the default sum.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Pivot".
const farmPivot = workbook.getPivotTable("Farm Pivot");

// Get the data hierarchy "Sum of Crates Sold at Farm".


const farmSales = farmPivot.getDataHierarchy("Sum of Crates Sold at
Farm");

// Show the data as a percentage of the grand total.


farmSales.setShowAs({
calculation: ExcelScript.ShowAsCalculation.percentOfGrandTotal
});
}

Fields
ノ Expand table

differenceFrom Difference from the specified Base field and Base item.

index Calculates the values as follows: ((value in cell) x (Grand Total of


Grand Totals)) / ((Grand Row Total) x (Grand Column Total))

none No calculation is applied.

percentDifferenceFrom Difference from the specified Base field and Base item.
percentOf Percent of the specified Base field and Base item.

percentOfColumnTotal Percent of the column total.

percentOfGrandTotal Percent of the grand total.

percentOfParentColumnTotal Percent of the column total for the specified Base field.

percentOfParentRowTotal Percent of the row total for the specified Base field.

percentOfParentTotal Percent of the grand total for the specified Base field.

percentOfRowTotal Percent of the row total.

percentRunningTotal Percent running total of the specified Base field.

rankAscending Ascending rank of the specified Base field.

rankDecending Descending rank of the specified Base field.

runningTotal Running total of the specified Base field.

unknown Calculation is unknown or unsupported.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SlicerSortType enum
Reference
Package: ExcelScript

Specifies the slicer sort behavior for Slicer.sortBy .

Fields
ノ Expand table

ascending Sort slicer items in ascending order by item captions.

dataSourceOrder Sort slicer items in the order provided by the data source.

descending Sort slicer items in descending order by item captions.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SortBy enum
Reference
Package: ExcelScript

Represents the sort direction.

Fields
ノ Expand table

ascending Ascending sort. Smallest to largest or A to Z.

descending Descending sort. Largest to smallest or Z to A.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SortDataOption enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script sorts a table based on the values in column 1.
* If the text of a column-1 value can be treated as a number,
* it will be sorted in numerical order, rather than Unicode order
* (so 123 will come before 12.3).
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const table = currentSheet.getTables()[0];

// Create the sorting parameters.


const countSortField: ExcelScript.SortField = {
key: 1,
ascending: true,
dataOption: ExcelScript.SortDataOption.textAsNumber
};

// Apply the sort to the table.


const sort = table.getSort();
sort.apply([countSortField]);
}

Fields
ノ Expand table

normal

textAsNumber
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SortMethod enum
Reference
Package: ExcelScript

Represents the ordering method to be used when sorting Chinese characters.

Remarks

Examples

TypeScript

/**
* This script sorts a range using the values in the first column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range (A1:D8) to sort from the current worksheet.
const worksheet = workbook.getActiveWorksheet();
const rangeToSort = worksheet.getRange("A1:D8");

// Create a SortField for text sorting.


let valueSort: ExcelScript.SortField = {
ascending: true,
key: 0, /* First column */
sortOn: ExcelScript.SortOn.value
};

// Apply the SortField to the range.


rangeToSort.getSort().apply(
[valueSort],
false, /* Don't let casing have an impact of sorting. */
true, /* The range has headers. */
ExcelScript.SortOrientation.rows,
ExcelScript.SortMethod.pinYin /* Use phonetic sorting for Chinese
characters. */
);
}

Fields
ノ Expand table

pinYin
strokeCount

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SortOn enum
Reference
Package: ExcelScript

Represents the part of the cell used as the sorting criteria.

Remarks

Examples

TypeScript

/**
* This script sorts a range based on the color of the cells.
* It brings all red cells to the top of the range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range (A1:D8) to sort from the current worksheet.
const worksheet = workbook.getActiveWorksheet();
const rangeToSort = worksheet.getRange("A1:D8");

// Create a SortField for color sorting.


// This sorts the rows based on the fill color of each row's cell in the
first column.
let colorSort: ExcelScript.SortField = {
ascending: true,
color: "FF0000", /* red */
key: 0,
sortOn: ExcelScript.SortOn.cellColor
};

// Apply the SortField to the range.


rangeToSort.getSort().apply([colorSort]);
}

Fields
ノ Expand table

cellColor

fontColor

icon
value

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SortOrientation enum
Reference
Package: ExcelScript

Fields
ノ Expand table

columns

rows

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SpecialCellType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script finds and highlights all the cells in the current worksheet
that contain a formula.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range on the current sheet.
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// Get the RangeAreas object for each cell with a formula.


const formulaCells =
usedRange.getSpecialCells(ExcelScript.SpecialCellType.formulas);

// Add a light blue background to the cells containing formulas.


formulaCells.getFormat().getFill().setColor("#ADD8E6");
}

Fields
ノ Expand table

blanks Cells with no content.

conditionalFormats All cells with conditional formats.

constants Cells containing constants.

dataValidations Cells with validation criteria.

formulas Cells containing formulas.

sameConditionalFormat Cells with the same conditional format as the first cell in the range.

sameDataValidation Cells with the same data validation criteria as the first cell in the range.
visible Cells that are visible.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SpecialCellValueType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script finds and bolds the text of cells containing strings (not
numbers or formulas).
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range on the current sheet.
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// Get the RangeAreas object for each cell with only text.
const textCells = usedRange.getSpecialCells(
ExcelScript.SpecialCellType.constants,
ExcelScript.SpecialCellValueType.text);

// Bold the text of those cells.


textCells.getFormat().getFont().setBold(true);
}

Fields
ノ Expand table

all Cells that have errors, boolean, numeric, or string values.

errors Cells that have errors.

errorsLogical Cells that have errors or boolean values.

errorsLogicalNumber Cells that have errors, boolean, or numeric values.

errorsLogicalText Cells that have errors, boolean, or string values.

errorsNumbers Cells that have errors or numeric values.

errorsNumberText Cells that have errors, numeric, or string values.


errorsText Cells that have errors or string values.

logical Cells that have a boolean value.

logicalNumbers Cells that have a boolean or numeric value.

logicalNumbersText Cells that have a boolean, numeric, or string value.

logicalText Cells that have a boolean or string value.

numbers Cells that have a numeric value.

numbersText Cells that have a numeric or string value.

text Cells that have a string value.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SubtotalLocationType enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script displays group subtotals of the "Farms Sales" PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Sales".
const pivot = workbook.getPivotTable("Farm Sales");

// Get the PivotLayout object.


const layout = pivot.getLayout();

// Show all the subtotals at the bottom of each group.


layout.setSubtotalLocation(ExcelScript.SubtotalLocationType.atBottom);
}

Fields
ノ Expand table

atBottom Subtotals are at the bottom.

atTop Subtotals are at the top.

off Subtotals are off.

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our  Provide product feedback
contributor guide.
ExcelScript.TopBottomSelectionType
enum
Reference
Package: ExcelScript

A simple enum for top/bottom filters to select whether to filter by the top N or bottom
N percent, number, or sum of values.

Fields
ノ Expand table

items Filter the top/bottom N number of items as measured by the chosen value.

percent Filter the top/bottom N percent of items as measured by the chosen value.

sum Filter the top/bottom N sum as measured by the chosen value.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ValueFilterCondition enum
Reference
Package: ExcelScript

Enum representing all accepted conditions by which a value filter can be applied. Used
to configure the type of PivotFilter that is applied to the field. PivotFilter.exclusive
can be set to true to invert many of these conditions.

Remarks

Examples

TypeScript

/**
* This script applies a PivotValueFilter to the first row hierarchy in the
PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable on the current worksheet.
let sheet = workbook.getActiveWorksheet();
let pivotTable = sheet.getPivotTables()[0];

// Get the first row hierarchy to use as the field which gets filtered.
let rowHierarchy = pivotTable.getRowHierarchies()[0];

// Get the first data hierarchy to use as the values for filtering the
rows.
let dataHierarchy = pivotTable.getDataHierarchies()[0];

// Create a filter that excludes values greater than 500.


let filter: ExcelScript.PivotValueFilter = {
condition: ExcelScript.ValueFilterCondition.greaterThan,
comparator: 500,
value: dataHierarchy.getName()
};

// Apply the filter.


rowHierarchy.getPivotField(rowHierarchy.getName()).applyFilter({
valueFilter: filter
});
}

Fields
ノ Expand table

between Between lowerBound and upperBound criteria.

Required Criteria: { value , lowerBound , upperBound }. Optional Criteria:


{ exclusive }.

bottomN In bottom N ( threshold ) [items, percent, sum] of value category.

Required Criteria: { value , threshold , selectionType }.

equals Equals comparator criterion.

Required Criteria: { value , comparator }. Optional Criteria: { exclusive }.

greaterThan Greater than comparator criterion.

Required Criteria: { value , comparator }.

greaterThanOrEqualTo Greater than or equal to comparator criterion.

Required Criteria: { value , comparator }.

lessThan Less than comparator criterion.

Required Criteria: { value , comparator }.

lessThanOrEqualTo Less than or equal to comparator criterion.

Required Criteria: { value , comparator }.

topN In top N ( threshold ) [items, percent, sum] of value category.

Required Criteria: { value , threshold , selectionType }.

unknown ValueFilterCondition is unknown or unsupported.

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.VerticalAlignment enum
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* This script sets the vertical alignment formatting to "top"
* for every cell in the row.
*/
function main(workbook: ExcelScript.Workbook) {
// Get row 1 for the current worksheet.
const sheet = workbook.getActiveWorksheet();
const firstRow = sheet.getRange("1:1");

// Set the vertical alignment formatting on the row.

firstRow.getFormat().setVerticalAlignment(ExcelScript.VerticalAlignment.top)
;
}

Fields
ノ Expand table

bottom

center

distributed

justify

top

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
be found on GitHub, where you Select a link to provide feedback:
can also create and review
issues and pull requests. For  Open a documentation issue
more information, see our
contributor guide.  Provide product feedback
ExcelScript.WorkbookLinksRefreshMode
enum
Reference
Package: ExcelScript

Represents the refresh mode of the workbook links.

Remarks

Examples

TypeScript

/**
* This script refreshes all the links to external workbooks,
* if the linked workbook refresh mode is set to manual.
* To learn about linked workbooks, see
https://support.microsoft.com/office/c98d1803-dd75-4668-ac6a-d7cca2a9b95f.
*/
function main(workbook: ExcelScript.Workbook) {
// Check the refresh mode.
if (workbook.getLinkedWorkbookRefreshMode() ===
ExcelScript.WorkbookLinksRefreshMode.manual) {
console.log("Refreshing workbook links");

// Trigger a refresh of linked workbook content.


workbook.refreshAllLinksToLinkedWorkbooks();
}
}

Fields
ノ Expand table

automatic The workbook links are updated at a set interval determined by the Excel application.

manual The workbook links are updated manually.


6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.WorksheetPositionType
enum
Reference
Package: ExcelScript

The position of a worksheet relative to another worksheet or the entire worksheet


collection.

Remarks

Examples

TypeScript

/**
* This script duplicates a worksheet named "Template".
* The new worksheet is added after the template.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the worksheet named "Template".
let template = workbook.getWorksheet("Template");

// Copy the worksheet.


let newSheet = template.copy(
ExcelScript.WorksheetPositionType.after,
template
);

// Name the worksheet using the current date.


let date = new Date(Date.now());
newSheet.setName(`${date.toDateString()}`);
}

Fields
ノ Expand table

after

before

beginning
end

none

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.AllowEditRange interface
Reference
Package: ExcelScript

Represents an AllowEditRange object found in a worksheet. This object works with


worksheet protection properties. When worksheet protection is enabled, an
AllowEditRange object can be used to allow editing of a specific range, while

maintaining protection on the rest of the worksheet.

Methods
ノ Expand table

delete() Deletes the object from the AllowEditRangeCollection . Worksheet


protection must be disabled or paused for this method to work properly.
If worksheet protection is enabled and not paused, this method throws
an AccessDenied error and fails the delete operation.

getAddress() Specifies the range associated with the object.

getIsPassword Specifies if the object is password protected.


Protected()

getTitle() Specifies the title of the object.

pause Pauses worksheet protection for the object for the user in the current
Protection(password) session. This method does nothing if worksheet protection isn't enabled
or is already paused. If worksheet protection cannot be paused, this
method throws an UnsupportedOperation error and fails to pause
protection for the object. If the password is incorrect, then this method
throws a BadPassword error and fails to pause protection for the object. If
a password is supplied but the object does not require a password, the
inputted password will be ignored and the operation will succeed.

setAddress(address) Specifies the range associated with the object. Worksheet protection
must be disabled or paused for this method to work properly. If
worksheet protection is enabled and not paused, this method throws an
AccessDenied error and fails to set the range.

set Changes the password associated with the object. Setting the password
Password(password) string as empty ("") or null will remove password protection from the
object. Worksheet protection must be disabled or paused for this method
to work properly. If worksheet protection is enabled and not paused, then
this method throws an AccessDenied error and the set operation fails.
setTitle(title) Specifies the title of the object. Worksheet protection must be disabled or
paused for this method to work properly. If worksheet protection is
enabled and not paused, this method throws an AccessDenied error and
fails to set the title. If there is already an existing AllowEditRange with the
same string, or if the string is null or empty (""), then this method throws
an InvalidArgument error and fails to set the title.

Method Details

delete()
Deletes the object from the AllowEditRangeCollection . Worksheet protection must
be disabled or paused for this method to work properly. If worksheet protection is
enabled and not paused, this method throws an AccessDenied error and fails the
delete operation.

TypeScript

delete(): void;

Returns
void

getAddress()
Specifies the range associated with the object.

TypeScript

getAddress(): string;

Returns
string

getIsPasswordProtected()
Specifies if the object is password protected.
TypeScript

getIsPasswordProtected(): boolean;

Returns
boolean

getTitle()
Specifies the title of the object.

TypeScript

getTitle(): string;

Returns
string

pauseProtection(password)
Pauses worksheet protection for the object for the user in the current session. This
method does nothing if worksheet protection isn't enabled or is already paused. If
worksheet protection cannot be paused, this method throws an
UnsupportedOperation error and fails to pause protection for the object. If the
password is incorrect, then this method throws a BadPassword error and fails to
pause protection for the object. If a password is supplied but the object does not
require a password, the inputted password will be ignored and the operation will
succeed.

TypeScript

pauseProtection(password?: string): void;

Parameters
password string
The password associated with the AllowEditRange object.
Returns
void

setAddress(address)
Specifies the range associated with the object. Worksheet protection must be
disabled or paused for this method to work properly. If worksheet protection is
enabled and not paused, this method throws an AccessDenied error and fails to set
the range.

TypeScript

setAddress(address: string): void;

Parameters
address string

Returns
void

setPassword(password)
Changes the password associated with the object. Setting the password string as
empty ("") or null will remove password protection from the object. Worksheet
protection must be disabled or paused for this method to work properly. If
worksheet protection is enabled and not paused, then this method throws an
AccessDenied error and the set operation fails.

TypeScript

setPassword(password?: string): void;

Parameters
password string
The password associated with the AllowEditRange object.

Returns
void

setTitle(title)
Specifies the title of the object. Worksheet protection must be disabled or paused for
this method to work properly. If worksheet protection is enabled and not paused,
this method throws an AccessDenied error and fails to set the title. If there is already
an existing AllowEditRange with the same string, or if the string is null or empty (""),
then this method throws an InvalidArgument error and fails to set the title.

TypeScript

setTitle(title: string): void;

Parameters
title string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.AllowEditRangeOptions
interface
Reference
Package: ExcelScript

The interface used to construct optional fields of the AllowEditRange object.

Remarks

Examples

TypeScript

/**
* This script adds a password-protected, editable range
* to an otherwise protected worksheet.
*/
function main(workbook: ExcelScript.Workbook, password: string) {
// Get the protection object for the "Data" worksheet.
const dataSheet = workbook.getWorksheet("Data");
const sheetProtection = dataSheet.getProtection();

// Set the password needed to edit the range to be the user provided
string.
const editRangeProperties : ExcelScript.AllowEditRangeOptions = {
password: password
};

// Set range "D2:D6" to be editable if the password is provided.


sheetProtection.addAllowEditRange("Notes Section", "D2:D6",
editRangeProperties);

// Protect the worksheet.


sheetProtection.protect();
}

Properties
ノ Expand table

password The password associated with the AllowEditRange .


Property Details

password
The password associated with the AllowEditRange .

TypeScript

password?: string;

Property Value
string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Application interface
Reference
Package: ExcelScript

Represents the Excel application that manages the workbook.

Methods
ノ Expand table

calculate(calculation Recalculate all currently opened workbooks in Excel.


Type)

getCalculationEngine Returns the Excel calculation engine version used for the last full
Version() recalculation.

getCalculationMode() Returns the calculation mode used in the workbook, as defined by the
constants in ExcelScript.CalculationMode . Possible values are:
Automatic , where Excel controls recalculation; AutomaticExceptTables ,
where Excel controls recalculation but ignores changes in tables; Manual ,
where calculation is done when the user requests it.

getCalculationState() Returns the calculation state of the application. See


ExcelScript.CalculationState for details.

getCultureInfo() Provides information based on current system culture settings. This


includes the culture names, number formatting, and other culturally
dependent settings.

getDecimalSeparator() Gets the string used as the decimal separator for numeric values. This is
based on the local Excel settings.

getIterative Returns the iterative calculation settings. In Excel on Windows and Mac,
Calculation() the settings will apply to the Excel Application. In Excel on the web and
other platforms, the settings will apply to the active workbook.

getThousands Gets the string used to separate groups of digits to the left of the
Separator() decimal for numeric values. This is based on the local Excel settings.

getUseSystem Specifies if the system separators of Excel are enabled. System


Separators() separators include the decimal separator and thousands separator.

setCalculation Returns the calculation mode used in the workbook, as defined by the
Mode(calculation constants in ExcelScript.CalculationMode . Possible values are:
Mode) Automatic , where Excel controls recalculation; AutomaticExceptTables ,
where Excel controls recalculation but ignores changes in tables; Manual ,
where calculation is done when the user requests it.

Method Details

calculate(calculationType)
Recalculate all currently opened workbooks in Excel.

TypeScript

calculate(calculationType: CalculationType): void;

Parameters
calculationType ExcelScript.CalculationType
Specifies the calculation type to use. See ExcelScript.CalculationType for details.

Returns
void

Examples

TypeScript

/**
* This script fully recalculates the entire workbook.
* This code is useful when automatic recalculation is turned off
* but later parts of the script rely on updated values.
*/
function main(workbook: ExcelScript.Workbook, workbookURL: string) {
const application = workbook.getApplication();
application.calculate(ExcelScript.CalculationType.fullRebuild);
}

getCalculationEngineVersion()
Returns the Excel calculation engine version used for the last full recalculation.

TypeScript
getCalculationEngineVersion(): number;

Returns
number

getCalculationMode()
Returns the calculation mode used in the workbook, as defined by the constants in
ExcelScript.CalculationMode . Possible values are: Automatic , where Excel controls

recalculation; AutomaticExceptTables , where Excel controls recalculation but ignores


changes in tables; Manual , where calculation is done when the user requests it.

TypeScript

getCalculationMode(): CalculationMode;

Returns
ExcelScript.CalculationMode

getCalculationState()
Returns the calculation state of the application. See ExcelScript.CalculationState
for details.

TypeScript

getCalculationState(): CalculationState;

Returns
ExcelScript.CalculationState

Examples

TypeScript

/**
* This script uses the fill color of the first cell to indicate the
current
* calculation state of the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell in the first worksheet.
const cell = workbook.getWorksheets()[0].getCell(0,0);

// Get that cell's fill object.


const cellFill = cell.getFormat().getFill();

// Set the cell fill based on the calculation state.


const calcState = workbook.getApplication().getCalculationState();
switch (calcState) {
case ExcelScript.CalculationState.pending:
cellFill.setColor("Red");
break;
case ExcelScript.CalculationState.calculating:
cellFill.setColor("Yellow");
break;
case ExcelScript.CalculationState.done:
cellFill.setColor("Green");
break;
}
}

getCultureInfo()
Provides information based on current system culture settings. This includes the
culture names, number formatting, and other culturally dependent settings.

TypeScript

getCultureInfo(): CultureInfo;

Returns
ExcelScript.CultureInfo

getDecimalSeparator()
Gets the string used as the decimal separator for numeric values. This is based on the
local Excel settings.

TypeScript

getDecimalSeparator(): string;
Returns
string

getIterativeCalculation()
Returns the iterative calculation settings. In Excel on Windows and Mac, the settings
will apply to the Excel Application. In Excel on the web and other platforms, the
settings will apply to the active workbook.

TypeScript

getIterativeCalculation(): IterativeCalculation;

Returns
ExcelScript.IterativeCalculation

getThousandsSeparator()
Gets the string used to separate groups of digits to the left of the decimal for
numeric values. This is based on the local Excel settings.

TypeScript

getThousandsSeparator(): string;

Returns
string

getUseSystemSeparators()
Specifies if the system separators of Excel are enabled. System separators include the
decimal separator and thousands separator.

TypeScript

getUseSystemSeparators(): boolean;

Returns
boolean

setCalculationMode(calculationMode)
Returns the calculation mode used in the workbook, as defined by the constants in
ExcelScript.CalculationMode . Possible values are: Automatic , where Excel controls

recalculation; AutomaticExceptTables , where Excel controls recalculation but ignores


changes in tables; Manual , where calculation is done when the user requests it.

TypeScript

setCalculationMode(calculationMode: CalculationMode): void;

Parameters
calculationMode ExcelScript.CalculationMode

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.AutoFilter interface
Reference
Package: ExcelScript

Represents the AutoFilter object. AutoFilter turns the values in Excel column into
specific filters based on the cell contents.

Remarks

Examples

TypeScript

/**
* This script creates an autoFilter on the worksheet that filters out rows
based on column values.
* The autoFilter filters to only include rows that have a value in column C
in the lowest 10 values
* (of column C values).
*/
function main(workbook: ExcelScript.Workbook) {
// Get the autoFilter of the first table in the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const dataRange = currentSheet.getUsedRange();
const autoFilter = currentSheet.getAutoFilter();

// Add a filter that will only show the rows with the lowest 10 values in
column C
// (index 2, assuming the used range spans from at least A:C).
autoFilter.apply(dataRange, 2, {
criterion1: "10",
filterOn: ExcelScript.FilterOn.bottomItems
});
}

Methods
ノ Expand table

apply(range, column Applies the AutoFilter to a range. This filters the column if column index
Index, criteria) and filter criteria are specified.

clearColumn Clears the column filter criteria of the AutoFilter.


Criteria(columnIndex)

clearCriteria() Clears the filter criteria and sort state of the AutoFilter.

getCriteria() An array that holds all the filter criteria in the autofiltered range.

getEnabled() Specifies if the AutoFilter is enabled.

getIsDataFiltered() Specifies if the AutoFilter has filter criteria.

getRange() Returns the Range object that represents the range to which the
AutoFilter applies. If there is no Range object associated with the
AutoFilter, then this method returns undefined .

reapply() Applies the specified AutoFilter object currently on the range.

remove() Removes the AutoFilter for the range.

Method Details

apply(range, columnIndex, criteria)


Applies the AutoFilter to a range. This filters the column if column index and filter
criteria are specified.

TypeScript

apply(
range: Range | string,
columnIndex?: number,
criteria?: FilterCriteria
): void;

Parameters
range ExcelScript.Range | string
The range on which the AutoFilter will apply.

columnIndex number
The zero-based column index to which the AutoFilter is applied.

criteria ExcelScript.FilterCriteria
The filter criteria.
Returns
void

Examples

TypeScript

/**
* This script applies a filter to a table so that
* only rows with values in column 1 that start with "L" are shown.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the autoFilter of the first table in the current worksheet.
const table = workbook.getActiveWorksheet().getTables()[0];
const autoFilter = table.getAutoFilter();

// Filter to only include values that start with "L".


const filterCriteria: ExcelScript.FilterCriteria = {
filterOn: ExcelScript.FilterOn.custom,
criterion1: "L*"
};

// Apply the filter to column 1 (zero-based).


autoFilter.apply(table.getRange(), 1, filterCriteria);
}

clearColumnCriteria(columnIndex)
Clears the column filter criteria of the AutoFilter.

TypeScript

clearColumnCriteria(columnIndex: number): void;

Parameters
columnIndex number
The zero-based column index, which represents which column filter needs to be
cleared. If the index value is not supported (for example, if the value is a negative
number, or if the value is greater than the number of available columns in the range),
then an InvalidArgument error will be thrown.

Returns
void

clearCriteria()
Clears the filter criteria and sort state of the AutoFilter.

TypeScript

clearCriteria(): void;

Returns
void

Examples

TypeScript

/**
* This script clears any applied criteria from the worksheet's
autoFilter.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();

// Clear all the criteria currently applied to the autoFilter.


currentSheet.getAutoFilter().clearCriteria();
}

getCriteria()
An array that holds all the filter criteria in the autofiltered range.

TypeScript

getCriteria(): FilterCriteria[];

Returns
ExcelScript.FilterCriteria[]

getEnabled()
Specifies if the AutoFilter is enabled.

TypeScript

getEnabled(): boolean;

Returns
boolean

getIsDataFiltered()
Specifies if the AutoFilter has filter criteria.

TypeScript

getIsDataFiltered(): boolean;

Returns
boolean

getRange()
Returns the Range object that represents the range to which the AutoFilter applies. If
there is no Range object associated with the AutoFilter, then this method returns
undefined .

TypeScript

getRange(): Range;

Returns
ExcelScript.Range

reapply()
Applies the specified AutoFilter object currently on the range.

TypeScript
reapply(): void;

Returns
void

remove()
Removes the AutoFilter for the range.

TypeScript

remove(): void;

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.BasicDataValidation interface
Reference
Package: ExcelScript

Represents the basic type data validation criteria.

Remarks

Examples

TypeScript

/**
* This script creates a data validation rule for the range B1: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 B1:B5 in the active worksheet.
const currentSheet = workbook.getActiveWorksheet();
const positiveNumberOnlyCells = currentSheet.getRange("B1: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);
}
Properties
ノ Expand table

formula1 Specifies the right-hand operand when the operator property is set to a binary
operator such as GreaterThan (the left-hand operand is the value the user tries to
enter in the cell). With the ternary operators Between and NotBetween, specifies the
lower bound operand. For example, setting formula1 to 10 and operator to
GreaterThan means that valid data for the range must be greater than 10. When
setting the value, it can be passed in as a number, a range object, or a string formula
(where the string is either a stringified number, a cell reference like "=A1", or a formula
like "=MIN(A1, B1)"). When retrieving the value, it will always be returned as a string
formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.

formula2 With the ternary operators Between and NotBetween, specifies the upper bound
operand. Is not used with the binary operators, such as GreaterThan. When setting the
value, it can be passed in as a number, a range object, or a string formula (where the
string is either a stringified number, a cell reference like "=A1", or a formula like
"=MIN(A1, B1)"). When retrieving the value, it will always be returned as a string
formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.

operator The operator to use for validating the data.

Property Details

formula1
Specifies the right-hand operand when the operator property is set to a binary
operator such as GreaterThan (the left-hand operand is the value the user tries to
enter in the cell). With the ternary operators Between and NotBetween, specifies the
lower bound operand. For example, setting formula1 to 10 and operator to
GreaterThan means that valid data for the range must be greater than 10. When
setting the value, it can be passed in as a number, a range object, or a string formula
(where the string is either a stringified number, a cell reference like "=A1", or a
formula like "=MIN(A1, B1)"). When retrieving the value, it will always be returned as
a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.

TypeScript

formula1: string | number | Range;

Property Value
string | number | ExcelScript.Range

formula2
With the ternary operators Between and NotBetween, specifies the upper bound
operand. Is not used with the binary operators, such as GreaterThan. When setting
the value, it can be passed in as a number, a range object, or a string formula (where
the string is either a stringified number, a cell reference like "=A1", or a formula like
"=MIN(A1, B1)"). When retrieving the value, it will always be returned as a string
formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.

TypeScript

formula2?: string | number | Range;

Property Value
string | number | ExcelScript.Range

operator
The operator to use for validating the data.

TypeScript

operator: DataValidationOperator;

Property Value
ExcelScript.DataValidationOperator

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Binding interface
Reference
Package: ExcelScript

Represents an Office.js binding that is defined in the workbook.

Methods
ノ Expand table

delete() Deletes the binding.

getId() Represents the binding identifier.

get Returns the range represented by the binding. Will throw an error if the binding is
Range() not of the correct type.

getTable() Returns the table represented by the binding. Will throw an error if the binding is not
of the correct type.

getText() Returns the text represented by the binding. Will throw an error if the binding is not
of the correct type.

getType() Returns the type of the binding. See ExcelScript.BindingType for details.

Method Details

delete()
Deletes the binding.

TypeScript

delete(): void;

Returns
void

getId()
Represents the binding identifier.

TypeScript

getId(): string;

Returns
string

getRange()
Returns the range represented by the binding. Will throw an error if the binding is
not of the correct type.

TypeScript

getRange(): Range;

Returns
ExcelScript.Range

getTable()
Returns the table represented by the binding. Will throw an error if the binding is not
of the correct type.

TypeScript

getTable(): Table;

Returns
ExcelScript.Table

getText()
Returns the text represented by the binding. Will throw an error if the binding is not
of the correct type.
TypeScript

getText(): string;

Returns
string

getType()
Returns the type of the binding. See ExcelScript.BindingType for details.

TypeScript

getType(): BindingType;

Returns
ExcelScript.BindingType

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CellValueConditionalFormat
interface
Reference
Package: ExcelScript

Represents a cell value conditional format.

Remarks

Examples

TypeScript

/**
* This script applies conditional formatting to a range.
* That formatting is conditional upon the cell's numerical value.
* Any value between 50 and 75 will have the cell fill color changed and the
font made italic.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range to format.
const sheet = workbook.getActiveWorksheet();
const ratingColumn = sheet.getRange("D2:D20");

// Add cell value conditional formatting.


const cellValueConditionalFormatting :
ExcelScript.CellValueConditionalFormat
=
ratingColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.cellValu
e).getCellValue();

// Create the condition, in this case when the cell value is between 50
and 75.
let rule: ExcelScript.ConditionalCellValueRule = {
formula1: "50",
formula2: "75",
operator: ExcelScript.ConditionalCellValueOperator.between
};
cellValueConditionalFormatting.setRule(rule);

// Set the format to apply when the condition is met.


let format = cellValueConditionalFormatting.getFormat();
format.getFill().setColor("yellow");
format.getFont().setItalic(true);
}
Methods
ノ Expand table

getFormat() Returns a format object, encapsulating the conditional formats font, fill, borders,
and other properties.

getRule() Specifies the rule object on this conditional format.

set Specifies the rule object on this conditional format.


Rule(rule)

Method Details

getFormat()
Returns a format object, encapsulating the conditional formats font, fill, borders, and
other properties.

TypeScript

getFormat(): ConditionalRangeFormat;

Returns
ExcelScript.ConditionalRangeFormat

getRule()
Specifies the rule object on this conditional format.

TypeScript

getRule(): ConditionalCellValueRule;

Returns
ExcelScript.ConditionalCellValueRule

setRule(rule)
Specifies the rule object on this conditional format.

TypeScript

setRule(rule: ConditionalCellValueRule): void;

Parameters
rule ExcelScript.ConditionalCellValueRule

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Chart interface
Reference
Package: ExcelScript

Represents a chart object in a workbook.

Methods
ノ Expand table

activate() Activates the chart in the Excel UI.

addChartSeries(name, Add a new series to the collection. The new added series is not visible
index) until values, x-axis values, or bubble sizes for it are set (depending on
chart type).

delete() Deletes the chart object.

getAxes() Represents chart axes.

getCategoryLabelLevel() Specifies a chart category label level enumeration constant, referring


to the level of the source category labels.

getChartType() Specifies the type of the chart. See ExcelScript.ChartType for details.

getDataLabels() Represents the data labels on the chart.

getDataTable() Gets the data table on the chart. If the chart doesn't allow a data table,
then this method returns undefined .

getDisplayBlanksAs() Specifies the way that blank cells are plotted on a chart.

getFormat() Encapsulates the format properties for the chart area.

getHeight() Specifies the height, in points, of the chart object.

getId() The unique ID of chart.

getImage(width, height, Renders the chart as a base64-encoded image by scaling the chart to
fittingMode) fit the specified dimensions. The aspect ratio is preserved as part of
the resizing.

getLeft() The distance, in points, from the left side of the chart to the worksheet
origin.

getLegend() Represents the legend for the chart.


getName() Specifies the name of a chart object.

getPivotOptions() Encapsulates the options for a pivot chart.

getPlotArea() Represents the plot area for the chart.

getPlotBy() Specifies the way columns or rows are used as data series on the
chart.

getPlotVisibleOnly() True if only visible cells are plotted. False if both visible and hidden
cells are plotted.

getSeries() Represents either a single series or collection of series in the chart.

getSeriesNameLevel() Specifies a chart series name level enumeration constant, referring to


the level of the source series names.

getShowAllFieldButtons() Specifies whether to display all field buttons on a PivotChart.

getShowDataLabelsOver Specifies whether to show the data labels when the value is greater
Maximum() than the maximum value on the value axis. If the value axis becomes
smaller than the size of the data points, you can use this property to
set whether to show the data labels. This property applies to 2-D
charts only.

getStyle() Specifies the chart style for the chart.

getTitle() Represents the title of the specified chart, including the text, visibility,
position, and formatting of the title.

getTop() Specifies the distance, in points, from the top edge of the object to
the top of row 1 (on a worksheet) or the top of the chart area (on a
chart).

getWidth() Specifies the width, in points, of the chart object.

getWorksheet() The worksheet containing the current chart.

setCategoryLabel Specifies a chart category label level enumeration constant, referring


Level(categoryLabel to the level of the source category labels.
Level)

setChartType(chartType) Specifies the type of the chart. See ExcelScript.ChartType for details.

setData(sourceData, Resets the source data for the chart.


seriesBy)

setDisplayBlanks Specifies the way that blank cells are plotted on a chart.
As(displayBlanksAs)

setHeight(height) Specifies the height, in points, of the chart object.


setLeft(left) The distance, in points, from the left side of the chart to the worksheet
origin.

setName(name) Specifies the name of a chart object.

setPlotBy(plotBy) Specifies the way columns or rows are used as data series on the
chart.

setPlotVisibleOnly(plot True if only visible cells are plotted. False if both visible and hidden
VisibleOnly) cells are plotted.

setPosition(startCell, end Positions the chart relative to cells on the worksheet.


Cell)

setSeriesName Specifies a chart series name level enumeration constant, referring to


Level(seriesNameLevel) the level of the source series names.

setShowAllField Specifies whether to display all field buttons on a PivotChart.


Buttons(showAllField
Buttons)

setShowDataLabelsOver Specifies whether to show the data labels when the value is greater
Maximum(showData than the maximum value on the value axis. If the value axis becomes
LabelsOverMaximum) smaller than the size of the data points, you can use this property to
set whether to show the data labels. This property applies to 2-D
charts only.

setStyle(style) Specifies the chart style for the chart.

setTop(top) Specifies the distance, in points, from the top edge of the object to
the top of row 1 (on a worksheet) or the top of the chart area (on a
chart).

setWidth(width) Specifies the width, in points, of the chart object.

Method Details

activate()
Activates the chart in the Excel UI.

TypeScript

activate(): void;

Returns
void

addChartSeries(name, index)
Add a new series to the collection. The new added series is not visible until values, x-
axis values, or bubble sizes for it are set (depending on chart type).

TypeScript

addChartSeries(name?: string, index?: number): ChartSeries;

Parameters
name string
Optional. Name of the series.

index number
Optional. Index value of the series to be added. Zero-indexed.

Returns
ExcelScript.ChartSeries

Examples

TypeScript

/**
* This sample produces a line chart with two series.
* The chart assumes data in A1:E5 that looks like this:
* Product Qtr1 Qtr2 Qtr3 Qtr4
* Frames 5000 7000 6544 4377
* Saddles 400 323 276 651
*/
function main(workbook: ExcelScript.Workbook) {
// Establish the ranges to use.
const sheet = workbook.getActiveWorksheet();
const headerRange = sheet.getRange("A1:E1");
const firstSeriesRange = sheet.getRange("A2:E2");
const secondSeriesRange = sheet.getRange("A3:E3");

// Create the chart.


const lineChart = sheet.addChart(ExcelScript.ChartType.line,
headerRange);

// Add the first chart series.


const firstSeries = lineChart.addChartSeries();
firstSeries.setXAxisValues(headerRange);
firstSeries.setValues(firstSeriesRange);

// Add the second chart series.


const secondSeries = lineChart.addChartSeries();
secondSeries.setXAxisValues(headerRange);
secondSeries.setValues(secondSeriesRange);
}

delete()
Deletes the chart object.

TypeScript

delete(): void;

Returns
void

getAxes()
Represents chart axes.

TypeScript

getAxes(): ChartAxes;

Returns
ExcelScript.ChartAxes

getCategoryLabelLevel()
Specifies a chart category label level enumeration constant, referring to the level of
the source category labels.

TypeScript

getCategoryLabelLevel(): number;
Returns
number

getChartType()
Specifies the type of the chart. See ExcelScript.ChartType for details.

TypeScript

getChartType(): ChartType;

Returns
ExcelScript.ChartType

getDataLabels()
Represents the data labels on the chart.

TypeScript

getDataLabels(): ChartDataLabels;

Returns
ExcelScript.ChartDataLabels

getDataTable()
Gets the data table on the chart. If the chart doesn't allow a data table, then this
method returns undefined .

TypeScript

getDataTable(): ChartDataTable;

Returns
ExcelScript.ChartDataTable
getDisplayBlanksAs()
Specifies the way that blank cells are plotted on a chart.

TypeScript

getDisplayBlanksAs(): ChartDisplayBlanksAs;

Returns
ExcelScript.ChartDisplayBlanksAs

getFormat()
Encapsulates the format properties for the chart area.

TypeScript

getFormat(): ChartAreaFormat;

Returns
ExcelScript.ChartAreaFormat

getHeight()
Specifies the height, in points, of the chart object.

TypeScript

getHeight(): number;

Returns
number

getId()
The unique ID of chart.

TypeScript
getId(): string;

Returns
string

getImage(width, height, fittingMode)


Renders the chart as a base64-encoded image by scaling the chart to fit the specified
dimensions. The aspect ratio is preserved as part of the resizing.

TypeScript

getImage(
width?: number,
height?: number,
fittingMode?: ImageFittingMode
): string;

Parameters
width number
Optional. The desired width of the resulting image.

height number
Optional. The desired height of the resulting image.

fittingMode ExcelScript.ImageFittingMode
Optional. The method used to scale the chart to the specified dimensions (if both
height and width are set).

Returns
string

Examples

TypeScript

/**
* This script returns an image of the first chart in the first
worksheet.
* That image is 600x400 pixels and the chart will be
* stretched to fill those dimensions.
* The returned image can be used in a Power Automate flow.
*/
function main(workbook: ExcelScript.Workbook): string {
// Get the first chart in the first worksheet.
const firstSheet = workbook.getFirstWorksheet();
const firstChart = firstSheet.getCharts()[0];

// Get an image of the chart as a base64-encoded string.


const base64String = firstChart.getImage(
600, /* Width */
400, /* Height */
ExcelScript.ImageFittingMode.fill /* Fill to match the dimensions. */
);

return base64String;
}

getLeft()
The distance, in points, from the left side of the chart to the worksheet origin.

TypeScript

getLeft(): number;

Returns
number

getLegend()
Represents the legend for the chart.

TypeScript

getLegend(): ChartLegend;

Returns
ExcelScript.ChartLegend

getName()
Specifies the name of a chart object.

TypeScript

getName(): string;

Returns
string

getPivotOptions()
Encapsulates the options for a pivot chart.

TypeScript

getPivotOptions(): ChartPivotOptions;

Returns
ExcelScript.ChartPivotOptions

getPlotArea()
Represents the plot area for the chart.

TypeScript

getPlotArea(): ChartPlotArea;

Returns
ExcelScript.ChartPlotArea

getPlotBy()
Specifies the way columns or rows are used as data series on the chart.

TypeScript

getPlotBy(): ChartPlotBy;
Returns
ExcelScript.ChartPlotBy

Examples

TypeScript

/**
* This sample performs the "Switch Row/Column" action on a chart named
"ColumnClusteredChart".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get an existing chart named "ColumnClusteredChart".


let columnClusteredChart =
selectedSheet.getChart("ColumnClusteredChart");

// Switch the row and column for the chart's data source.
if (columnClusteredChart.getPlotBy() ===
ExcelScript.ChartPlotBy.columns) {
// If the chart is grouped by columns, switch it to rows.
columnClusteredChart.setPlotBy(ExcelScript.ChartPlotBy.rows);
} else {
// If the chart is grouped by rows, switch it to columns.
columnClusteredChart.setPlotBy(ExcelScript.ChartPlotBy.columns);
}
}

getPlotVisibleOnly()
True if only visible cells are plotted. False if both visible and hidden cells are plotted.

TypeScript

getPlotVisibleOnly(): boolean;

Returns
boolean

getSeries()
Represents either a single series or collection of series in the chart.
TypeScript

getSeries(): ChartSeries[];

Returns
ExcelScript.ChartSeries[]

Examples

TypeScript

/**
* This sample sets the overlap of the columns in a chart named
"ColumnClusteredChart".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get an existing chart named "ColumnClusteredChart".


let chart = selectedSheet.getChart("ColumnClusteredChart");

// Set the overlap of every column of each series within a category.


let seriesList = chart.getSeries();
seriesList.forEach((series) => {
// An overlap of 25 means the columns have 25% of their length
overlapping with the adjacent columns in the same category.
series.setOverlap(25);
});
}

getSeriesNameLevel()
Specifies a chart series name level enumeration constant, referring to the level of the
source series names.

TypeScript

getSeriesNameLevel(): number;

Returns
number
getShowAllFieldButtons()
Specifies whether to display all field buttons on a PivotChart.

TypeScript

getShowAllFieldButtons(): boolean;

Returns
boolean

getShowDataLabelsOverMaximum()
Specifies whether to show the data labels when the value is greater than the
maximum value on the value axis. If the value axis becomes smaller than the size of
the data points, you can use this property to set whether to show the data labels.
This property applies to 2-D charts only.

TypeScript

getShowDataLabelsOverMaximum(): boolean;

Returns
boolean

getStyle()
Specifies the chart style for the chart.

TypeScript

getStyle(): number;

Returns
number

getTitle()
Represents the title of the specified chart, including the text, visibility, position, and
formatting of the title.

TypeScript

getTitle(): ChartTitle;

Returns
ExcelScript.ChartTitle

getTop()
Specifies the distance, in points, from the top edge of the object to the top of row 1
(on a worksheet) or the top of the chart area (on a chart).

TypeScript

getTop(): number;

Returns
number

getWidth()
Specifies the width, in points, of the chart object.

TypeScript

getWidth(): number;

Returns
number

getWorksheet()
The worksheet containing the current chart.

TypeScript
getWorksheet(): Worksheet;

Returns
ExcelScript.Worksheet

setCategoryLabelLevel(categoryLabelLevel)
Specifies a chart category label level enumeration constant, referring to the level of
the source category labels.

TypeScript

setCategoryLabelLevel(categoryLabelLevel: number): void;

Parameters
categoryLabelLevel number

Returns
void

setChartType(chartType)
Specifies the type of the chart. See ExcelScript.ChartType for details.

TypeScript

setChartType(chartType: ChartType): void;

Parameters
chartType ExcelScript.ChartType

Returns
void

setData(sourceData, seriesBy)
Resets the source data for the chart.

TypeScript

setData(sourceData: Range, seriesBy?: ChartSeriesBy): void;

Parameters
sourceData ExcelScript.Range
The range object corresponding to the source data.

seriesBy ExcelScript.ChartSeriesBy
Specifies the way columns or rows are used as data series on the chart. Can be one
of the following: Auto (default), Rows, and Columns. See ExcelScript.ChartSeriesBy
for details.

Returns
void

setDisplayBlanksAs(displayBlanksAs)
Specifies the way that blank cells are plotted on a chart.

TypeScript

setDisplayBlanksAs(displayBlanksAs: ChartDisplayBlanksAs): void;

Parameters
displayBlanksAs ExcelScript.ChartDisplayBlanksAs

Returns
void

setHeight(height)
Specifies the height, in points, of the chart object.

TypeScript
setHeight(height: number): void;

Parameters
height number

Returns
void

setLeft(left)
The distance, in points, from the left side of the chart to the worksheet origin.

TypeScript

setLeft(left: number): void;

Parameters
left number

Returns
void

setName(name)
Specifies the name of a chart object.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void
Examples

TypeScript

/**
* This sample creates a column-clustered chart based on the current
worksheet's data.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get the data range.


let range = selectedSheet.getUsedRange();

// Insert a chart using the data on the current worksheet.


let chart =
selectedSheet.addChart(ExcelScript.ChartType.columnClustered, range);

// Name the chart for easy access in other scripts.


chart.setName("ColumnChart");
}

setPlotBy(plotBy)
Specifies the way columns or rows are used as data series on the chart.

TypeScript

setPlotBy(plotBy: ChartPlotBy): void;

Parameters
plotBy ExcelScript.ChartPlotBy

Returns
void

Examples

TypeScript

/**
* This sample performs the "Switch Row/Column" action on a chart named
"ColumnClusteredChart".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get an existing chart named "ColumnClusteredChart".


let columnClusteredChart =
selectedSheet.getChart("ColumnClusteredChart");

// Switch the row and column for the chart's data source.
if (columnClusteredChart.getPlotBy() ===
ExcelScript.ChartPlotBy.columns) {
// If the chart is grouped by columns, switch it to rows.
columnClusteredChart.setPlotBy(ExcelScript.ChartPlotBy.rows);
} else {
// If the chart is grouped by rows, switch it to columns.
columnClusteredChart.setPlotBy(ExcelScript.ChartPlotBy.columns);
}
}

setPlotVisibleOnly(plotVisibleOnly)
True if only visible cells are plotted. False if both visible and hidden cells are plotted.

TypeScript

setPlotVisibleOnly(plotVisibleOnly: boolean): void;

Parameters
plotVisibleOnly boolean

Returns
void

setPosition(startCell, endCell)
Positions the chart relative to cells on the worksheet.

TypeScript

setPosition(startCell: Range | string, endCell?: Range | string): void;

Parameters
startCell ExcelScript.Range | string
The start cell. This is where the chart will be moved to. The start cell is the top-left or
top-right cell, depending on the user's right-to-left display settings.

endCell ExcelScript.Range | string


Optional. The end cell. If specified, the chart's width and height will be set to fully
cover up this cell/range.

Returns
void

Examples

TypeScript

/**
* This sample moves an existing chart to a specific place on the
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get an existing chart named "ColumnChart".


let chart = selectedSheet.getChart("ColumnChart");

// Place the chart over the range "F1:L13".


chart.setPosition("F1", "L13");
}

setSeriesNameLevel(seriesNameLevel)
Specifies a chart series name level enumeration constant, referring to the level of the
source series names.

TypeScript

setSeriesNameLevel(seriesNameLevel: number): void;

Parameters
seriesNameLevel number
Returns
void

setShowAllFieldButtons(showAllFieldButtons)
Specifies whether to display all field buttons on a PivotChart.

TypeScript

setShowAllFieldButtons(showAllFieldButtons: boolean): void;

Parameters
showAllFieldButtons boolean

Returns
void

setShowDataLabelsOverMaximum(showDataLabelsOver
Maximum)
Specifies whether to show the data labels when the value is greater than the
maximum value on the value axis. If the value axis becomes smaller than the size of
the data points, you can use this property to set whether to show the data labels.
This property applies to 2-D charts only.

TypeScript

setShowDataLabelsOverMaximum(showDataLabelsOverMaximum: boolean): void;

Parameters
showDataLabelsOverMaximum boolean

Returns
void

setStyle(style)
Specifies the chart style for the chart.

TypeScript

setStyle(style: number): void;

Parameters
style number

Returns
void

setTop(top)
Specifies the distance, in points, from the top edge of the object to the top of row 1
(on a worksheet) or the top of the chart area (on a chart).

TypeScript

setTop(top: number): void;

Parameters
top number

Returns
void

setWidth(width)
Specifies the width, in points, of the chart object.

TypeScript

setWidth(width: number): void;

Parameters
width number
Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAreaFormat interface
Reference
Package: ExcelScript

Encapsulates the format properties for the overall chart area.

Methods
ノ Expand table

getBorder() Represents the border format of chart area, which includes color,
linestyle, and weight.

getColorScheme() Specifies the color scheme of the chart.

getFill() Represents the fill format of an object, which includes


background formatting information.

getFont() Represents the font attributes (font name, font size, color, etc.)
for the current object.

getRoundedCorners() Specifies if the chart area of the chart has rounded corners.

setColorScheme(colorScheme) Specifies the color scheme of the chart.

setRoundedCorners(rounded Specifies if the chart area of the chart has rounded corners.
Corners)

Method Details

getBorder()
Represents the border format of chart area, which includes color, linestyle, and
weight.

TypeScript

getBorder(): ChartBorder;

Returns
ExcelScript.ChartBorder
getColorScheme()
Specifies the color scheme of the chart.

TypeScript

getColorScheme(): ChartColorScheme;

Returns
ExcelScript.ChartColorScheme

getFill()
Represents the fill format of an object, which includes background formatting
information.

TypeScript

getFill(): ChartFill;

Returns
ExcelScript.ChartFill

getFont()
Represents the font attributes (font name, font size, color, etc.) for the current object.

TypeScript

getFont(): ChartFont;

Returns
ExcelScript.ChartFont

getRoundedCorners()
Specifies if the chart area of the chart has rounded corners.

TypeScript
getRoundedCorners(): boolean;

Returns
boolean

setColorScheme(colorScheme)
Specifies the color scheme of the chart.

TypeScript

setColorScheme(colorScheme: ChartColorScheme): void;

Parameters
colorScheme ExcelScript.ChartColorScheme

Returns
void

setRoundedCorners(roundedCorners)
Specifies if the chart area of the chart has rounded corners.

TypeScript

setRoundedCorners(roundedCorners: boolean): void;

Parameters
roundedCorners boolean

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxes interface
Reference
Package: ExcelScript

Represents the chart axes.

Methods
ノ Expand table

getCategoryAxis() Represents the category axis in a chart.

getChartAxis(type, group) Returns the specific axis identified by type and group.

getSeriesAxis() Represents the series axis of a 3-D chart.

getValueAxis() Represents the value axis in an axis.

Method Details

getCategoryAxis()
Represents the category axis in a chart.

TypeScript

getCategoryAxis(): ChartAxis;

Returns
ExcelScript.ChartAxis

getChartAxis(type, group)
Returns the specific axis identified by type and group.

TypeScript

getChartAxis(type: ChartAxisType, group?: ChartAxisGroup): ChartAxis;


Parameters
type ExcelScript.ChartAxisType
Specifies the axis type. See ExcelScript.ChartAxisType for details.

group ExcelScript.ChartAxisGroup
Optional. Specifies the axis group. See ExcelScript.ChartAxisGroup for details.

Returns
ExcelScript.ChartAxis

getSeriesAxis()
Represents the series axis of a 3-D chart.

TypeScript

getSeriesAxis(): ChartAxis;

Returns
ExcelScript.ChartAxis

getValueAxis()
Represents the value axis in an axis.

TypeScript

getValueAxis(): ChartAxis;

Returns
ExcelScript.ChartAxis

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review  Open a documentation issue
issues and pull requests. For
more information, see our  Provide product feedback
contributor guide.
ExcelScript.ChartAxis interface
Reference
Package: ExcelScript

Represents a single axis in a chart.

Methods
ノ Expand table

getAlignment() Specifies the alignment for the specified axis tick label. See
ExcelScript.ChartTextHorizontalAlignment for detail.

getAxisGroup() Specifies the group for the specified axis. See


ExcelScript.ChartAxisGroup for details.

getBaseTimeUnit() Specifies the base unit for the specified category axis.

getCategoryType() Specifies the category axis type.

getCustomDisplayUnit() Specifies the custom axis display unit value. To set this property,
please use the SetCustomDisplayUnit(double) method.

getDisplayUnit() Represents the axis display unit. See


ExcelScript.ChartAxisDisplayUnit for details.

getFormat() Represents the formatting of a chart object, which includes line and
font formatting.

getHeight() Specifies the height, in points, of the chart axis. Returns null if the
axis is not visible.

getIsBetweenCategories() Specifies if the value axis crosses the category axis between
categories.

getLeft() Specifies the distance, in points, from the left edge of the axis to the
left of chart area. Returns null if the axis is not visible.

getLinkNumberFormat() Specifies if the number format is linked to the cells. If true , the
number format will change in the labels when it changes in the cells.

getLogBase() Specifies the base of the logarithm when using logarithmic scales.

getMajorGridlines() Returns an object that represents the major gridlines for the
specified axis.
getMajorTickMark() Specifies the type of major tick mark for the specified axis. See
ExcelScript.ChartAxisTickMark for details.

getMajorTimeUnitScale() Specifies the major unit scale value for the category axis when the
categoryType property is set to dateAxis .

getMajorUnit() Specifies the interval between two major tick marks.

getMaximum() Specifies the maximum value on the value axis.

getMinimum() Specifies the minimum value on the value axis.

getMinorGridlines() Returns an object that represents the minor gridlines for the
specified axis.

getMinorTickMark() Specifies the type of minor tick mark for the specified axis. See
ExcelScript.ChartAxisTickMark for details.

getMinorTimeUnitScale() Specifies the minor unit scale value for the category axis when the
categoryType property is set to dateAxis .

getMinorUnit() Specifies the interval between two minor tick marks.

getMultiLevel() Specifies if an axis is multilevel.

getNumberFormat() Specifies the format code for the axis tick label.

getOffset() Specifies the distance between the levels of labels, and the distance
between the first level and the axis line. The value should be an
integer from 0 to 1000.

getPosition() Specifies the specified axis position where the other axis crosses. See
ExcelScript.ChartAxisPosition for details.

getPositionAt() Specifies the axis position where the other axis crosses. You should
use the SetPositionAt(double) method to set this property.

getReversePlotOrder() Specifies if Excel plots data points from last to first.

getScaleType() Specifies the value axis scale type. See


ExcelScript.ChartAxisScaleType for details.

getShowDisplayUnitLabel() Specifies if the axis display unit label is visible.

getTextOrientation() Specifies the angle to which the text is oriented for the chart axis
tick label. The value should either be an integer from -90 to 90 or
the integer 180 for vertically-oriented text.

getTickLabelPosition() Specifies the position of tick-mark labels on the specified axis. See
ExcelScript.ChartAxisTickLabelPosition for details.
getTickLabelSpacing() Specifies the number of categories or series between tick-mark
labels. Can be a value from 1 through 31999.

getTickMarkSpacing() Specifies the number of categories or series between tick marks.

getTitle() Represents the axis title.

getTop() Specifies the distance, in points, from the top edge of the axis to the
top of chart area. Returns null if the axis is not visible.

getType() Specifies the axis type. See ExcelScript.ChartAxisType for details.

getVisible() Specifies if the axis is visible.

getWidth() Specifies the width, in points, of the chart axis. Returns null if the
axis is not visible.

setAlignment(alignment) Specifies the alignment for the specified axis tick label. See
ExcelScript.ChartTextHorizontalAlignment for detail.

setBaseTimeUnit(baseTime Specifies the base unit for the specified category axis.
Unit)

setCategoryNames(source Sets all the category names for the specified axis.
Data)

setCategoryType(category Specifies the category axis type.


Type)

setCustomDisplay Sets the axis display unit to a custom value.


Unit(value)

setDisplayUnit(displayUnit) Represents the axis display unit. See


ExcelScript.ChartAxisDisplayUnit for details.

setIsBetweenCategories(is Specifies if the value axis crosses the category axis between
BetweenCategories) categories.

setLinkNumberFormat(link Specifies if the number format is linked to the cells. If true , the
NumberFormat) number format will change in the labels when it changes in the cells.

setLogBase(logBase) Specifies the base of the logarithm when using logarithmic scales.

setMajorTickMark(major Specifies the type of major tick mark for the specified axis. See
TickMark) ExcelScript.ChartAxisTickMark for details.

setMajorTimeUnit Specifies the major unit scale value for the category axis when the
Scale(majorTimeUnitScale) categoryType property is set to dateAxis .

setMajorUnit(majorUnit) Specifies the interval between two major tick marks.

setMaximum(maximum) Specifies the maximum value on the value axis.


setMinimum(minimum) Specifies the minimum value on the value axis.

setMinorTickMark(minor Specifies the type of minor tick mark for the specified axis. See
TickMark) ExcelScript.ChartAxisTickMark for details.

setMinorTimeUnit Specifies the minor unit scale value for the category axis when the
Scale(minorTimeUnitScale) categoryType property is set to dateAxis .

setMinorUnit(minorUnit) Specifies the interval between two minor tick marks.

setMultiLevel(multiLevel) Specifies if an axis is multilevel.

setNumberFormat(number Specifies the format code for the axis tick label.
Format)

setOffset(offset) Specifies the distance between the levels of labels, and the distance
between the first level and the axis line. The value should be an
integer from 0 to 1000.

setPosition(position) Specifies the specified axis position where the other axis crosses. See
ExcelScript.ChartAxisPosition for details.

setPositionAt(value) Sets the specified axis position where the other axis crosses.

setReversePlot Specifies if Excel plots data points from last to first.


Order(reversePlotOrder)

setScaleType(scaleType) Specifies the value axis scale type. See


ExcelScript.ChartAxisScaleType for details.

setShowDisplayUnit Specifies if the axis display unit label is visible.


Label(showDisplayUnit
Label)

setTextOrientation(text Specifies the angle to which the text is oriented for the chart axis
Orientation) tick label. The value should either be an integer from -90 to 90 or
the integer 180 for vertically-oriented text.

setTickLabelPosition(tick Specifies the position of tick-mark labels on the specified axis. See
LabelPosition) ExcelScript.ChartAxisTickLabelPosition for details.

setTickLabelSpacing(tick Specifies the number of categories or series between tick-mark


LabelSpacing) labels. Can be a value from 1 through 31999.

setTickMarkSpacing(tick Specifies the number of categories or series between tick marks.


MarkSpacing)

setVisible(visible) Specifies if the axis is visible.

Method Details
getAlignment()
Specifies the alignment for the specified axis tick label. See
ExcelScript.ChartTextHorizontalAlignment for detail.

TypeScript

getAlignment(): ChartTickLabelAlignment;

Returns
ExcelScript.ChartTickLabelAlignment

getAxisGroup()
Specifies the group for the specified axis. See ExcelScript.ChartAxisGroup for
details.

TypeScript

getAxisGroup(): ChartAxisGroup;

Returns
ExcelScript.ChartAxisGroup

getBaseTimeUnit()
Specifies the base unit for the specified category axis.

TypeScript

getBaseTimeUnit(): ChartAxisTimeUnit;

Returns
ExcelScript.ChartAxisTimeUnit

getCategoryType()
Specifies the category axis type.
TypeScript

getCategoryType(): ChartAxisCategoryType;

Returns
ExcelScript.ChartAxisCategoryType

getCustomDisplayUnit()
Specifies the custom axis display unit value. To set this property, please use the
SetCustomDisplayUnit(double) method.

TypeScript

getCustomDisplayUnit(): number;

Returns
number

getDisplayUnit()
Represents the axis display unit. See ExcelScript.ChartAxisDisplayUnit for details.

TypeScript

getDisplayUnit(): ChartAxisDisplayUnit;

Returns
ExcelScript.ChartAxisDisplayUnit

getFormat()
Represents the formatting of a chart object, which includes line and font formatting.

TypeScript

getFormat(): ChartAxisFormat;
Returns
ExcelScript.ChartAxisFormat

getHeight()
Specifies the height, in points, of the chart axis. Returns null if the axis is not visible.

TypeScript

getHeight(): number;

Returns
number

getIsBetweenCategories()
Specifies if the value axis crosses the category axis between categories.

TypeScript

getIsBetweenCategories(): boolean;

Returns
boolean

getLeft()
Specifies the distance, in points, from the left edge of the axis to the left of chart
area. Returns null if the axis is not visible.

TypeScript

getLeft(): number;

Returns
number
getLinkNumberFormat()
Specifies if the number format is linked to the cells. If true , the number format will
change in the labels when it changes in the cells.

TypeScript

getLinkNumberFormat(): boolean;

Returns
boolean

getLogBase()
Specifies the base of the logarithm when using logarithmic scales.

TypeScript

getLogBase(): number;

Returns
number

getMajorGridlines()
Returns an object that represents the major gridlines for the specified axis.

TypeScript

getMajorGridlines(): ChartGridlines;

Returns
ExcelScript.ChartGridlines

getMajorTickMark()
Specifies the type of major tick mark for the specified axis. See
ExcelScript.ChartAxisTickMark for details.
TypeScript

getMajorTickMark(): ChartAxisTickMark;

Returns
ExcelScript.ChartAxisTickMark

getMajorTimeUnitScale()
Specifies the major unit scale value for the category axis when the categoryType
property is set to dateAxis .

TypeScript

getMajorTimeUnitScale(): ChartAxisTimeUnit;

Returns
ExcelScript.ChartAxisTimeUnit

getMajorUnit()
Specifies the interval between two major tick marks.

TypeScript

getMajorUnit(): number;

Returns
number

getMaximum()
Specifies the maximum value on the value axis.

TypeScript

getMaximum(): number;
Returns
number

getMinimum()
Specifies the minimum value on the value axis.

TypeScript

getMinimum(): number;

Returns
number

getMinorGridlines()
Returns an object that represents the minor gridlines for the specified axis.

TypeScript

getMinorGridlines(): ChartGridlines;

Returns
ExcelScript.ChartGridlines

getMinorTickMark()
Specifies the type of minor tick mark for the specified axis. See
ExcelScript.ChartAxisTickMark for details.

TypeScript

getMinorTickMark(): ChartAxisTickMark;

Returns
ExcelScript.ChartAxisTickMark
getMinorTimeUnitScale()
Specifies the minor unit scale value for the category axis when the categoryType
property is set to dateAxis .

TypeScript

getMinorTimeUnitScale(): ChartAxisTimeUnit;

Returns
ExcelScript.ChartAxisTimeUnit

getMinorUnit()
Specifies the interval between two minor tick marks.

TypeScript

getMinorUnit(): number;

Returns
number

getMultiLevel()
Specifies if an axis is multilevel.

TypeScript

getMultiLevel(): boolean;

Returns
boolean

getNumberFormat()
Specifies the format code for the axis tick label.
TypeScript

getNumberFormat(): string;

Returns
string

getOffset()
Specifies the distance between the levels of labels, and the distance between the first
level and the axis line. The value should be an integer from 0 to 1000.

TypeScript

getOffset(): number;

Returns
number

getPosition()
Specifies the specified axis position where the other axis crosses. See
ExcelScript.ChartAxisPosition for details.

TypeScript

getPosition(): ChartAxisPosition;

Returns
ExcelScript.ChartAxisPosition

getPositionAt()
Specifies the axis position where the other axis crosses. You should use the
SetPositionAt(double) method to set this property.

TypeScript
getPositionAt(): number;

Returns
number

getReversePlotOrder()
Specifies if Excel plots data points from last to first.

TypeScript

getReversePlotOrder(): boolean;

Returns
boolean

getScaleType()
Specifies the value axis scale type. See ExcelScript.ChartAxisScaleType for details.

TypeScript

getScaleType(): ChartAxisScaleType;

Returns
ExcelScript.ChartAxisScaleType

getShowDisplayUnitLabel()
Specifies if the axis display unit label is visible.

TypeScript

getShowDisplayUnitLabel(): boolean;

Returns
boolean

getTextOrientation()
Specifies the angle to which the text is oriented for the chart axis tick label. The value
should either be an integer from -90 to 90 or the integer 180 for vertically-oriented
text.

TypeScript

getTextOrientation(): number;

Returns
number

getTickLabelPosition()
Specifies the position of tick-mark labels on the specified axis. See
ExcelScript.ChartAxisTickLabelPosition for details.

TypeScript

getTickLabelPosition(): ChartAxisTickLabelPosition;

Returns
ExcelScript.ChartAxisTickLabelPosition

getTickLabelSpacing()
Specifies the number of categories or series between tick-mark labels. Can be a value
from 1 through 31999.

TypeScript

getTickLabelSpacing(): number;

Returns
number
getTickMarkSpacing()
Specifies the number of categories or series between tick marks.

TypeScript

getTickMarkSpacing(): number;

Returns
number

getTitle()
Represents the axis title.

TypeScript

getTitle(): ChartAxisTitle;

Returns
ExcelScript.ChartAxisTitle

getTop()
Specifies the distance, in points, from the top edge of the axis to the top of chart
area. Returns null if the axis is not visible.

TypeScript

getTop(): number;

Returns
number

getType()
Specifies the axis type. See ExcelScript.ChartAxisType for details.
TypeScript

getType(): ChartAxisType;

Returns
ExcelScript.ChartAxisType

getVisible()
Specifies if the axis is visible.

TypeScript

getVisible(): boolean;

Returns
boolean

getWidth()
Specifies the width, in points, of the chart axis. Returns null if the axis is not visible.

TypeScript

getWidth(): number;

Returns
number

setAlignment(alignment)
Specifies the alignment for the specified axis tick label. See
ExcelScript.ChartTextHorizontalAlignment for detail.

TypeScript

setAlignment(alignment: ChartTickLabelAlignment): void;


Parameters
alignment ExcelScript.ChartTickLabelAlignment

Returns
void

setBaseTimeUnit(baseTimeUnit)
Specifies the base unit for the specified category axis.

TypeScript

setBaseTimeUnit(baseTimeUnit: ChartAxisTimeUnit): void;

Parameters
baseTimeUnit ExcelScript.ChartAxisTimeUnit

Returns
void

setCategoryNames(sourceData)
Sets all the category names for the specified axis.

TypeScript

setCategoryNames(sourceData: Range): void;

Parameters
sourceData ExcelScript.Range
The Range object corresponding to the source data.

Returns
void

setCategoryType(categoryType)
Specifies the category axis type.

TypeScript

setCategoryType(categoryType: ChartAxisCategoryType): void;

Parameters
categoryType ExcelScript.ChartAxisCategoryType

Returns
void

setCustomDisplayUnit(value)
Sets the axis display unit to a custom value.

TypeScript

setCustomDisplayUnit(value: number): void;

Parameters
value number
Custom value of the display unit.

Returns
void

setDisplayUnit(displayUnit)
Represents the axis display unit. See ExcelScript.ChartAxisDisplayUnit for details.

TypeScript

setDisplayUnit(displayUnit: ChartAxisDisplayUnit): void;

Parameters
displayUnit ExcelScript.ChartAxisDisplayUnit

Returns
void

setIsBetweenCategories(isBetweenCategories)
Specifies if the value axis crosses the category axis between categories.

TypeScript

setIsBetweenCategories(isBetweenCategories: boolean): void;

Parameters
isBetweenCategories boolean

Returns
void

setLinkNumberFormat(linkNumberFormat)
Specifies if the number format is linked to the cells. If true , the number format will
change in the labels when it changes in the cells.

TypeScript

setLinkNumberFormat(linkNumberFormat: boolean): void;

Parameters
linkNumberFormat boolean

Returns
void

setLogBase(logBase)
Specifies the base of the logarithm when using logarithmic scales.

TypeScript

setLogBase(logBase: number): void;

Parameters
logBase number

Returns
void

setMajorTickMark(majorTickMark)
Specifies the type of major tick mark for the specified axis. See
ExcelScript.ChartAxisTickMark for details.

TypeScript

setMajorTickMark(majorTickMark: ChartAxisTickMark): void;

Parameters
majorTickMark ExcelScript.ChartAxisTickMark

Returns
void

setMajorTimeUnitScale(majorTimeUnitScale)
Specifies the major unit scale value for the category axis when the categoryType
property is set to dateAxis .

TypeScript

setMajorTimeUnitScale(majorTimeUnitScale: ChartAxisTimeUnit): void;

Parameters
majorTimeUnitScale ExcelScript.ChartAxisTimeUnit

Returns
void

setMajorUnit(majorUnit)
Specifies the interval between two major tick marks.

TypeScript

setMajorUnit(majorUnit: number): void;

Parameters
majorUnit number

Returns
void

setMaximum(maximum)
Specifies the maximum value on the value axis.

TypeScript

setMaximum(maximum: number): void;

Parameters
maximum number

Returns
void

setMinimum(minimum)
Specifies the minimum value on the value axis.
TypeScript

setMinimum(minimum: number): void;

Parameters
minimum number

Returns
void

setMinorTickMark(minorTickMark)
Specifies the type of minor tick mark for the specified axis. See
ExcelScript.ChartAxisTickMark for details.

TypeScript

setMinorTickMark(minorTickMark: ChartAxisTickMark): void;

Parameters
minorTickMark ExcelScript.ChartAxisTickMark

Returns
void

setMinorTimeUnitScale(minorTimeUnitScale)
Specifies the minor unit scale value for the category axis when the categoryType
property is set to dateAxis .

TypeScript

setMinorTimeUnitScale(minorTimeUnitScale: ChartAxisTimeUnit): void;

Parameters
minorTimeUnitScale ExcelScript.ChartAxisTimeUnit
Returns
void

setMinorUnit(minorUnit)
Specifies the interval between two minor tick marks.

TypeScript

setMinorUnit(minorUnit: number): void;

Parameters
minorUnit number

Returns
void

setMultiLevel(multiLevel)
Specifies if an axis is multilevel.

TypeScript

setMultiLevel(multiLevel: boolean): void;

Parameters
multiLevel boolean

Returns
void

setNumberFormat(numberFormat)
Specifies the format code for the axis tick label.

TypeScript
setNumberFormat(numberFormat: string): void;

Parameters
numberFormat string

Returns
void

setOffset(offset)
Specifies the distance between the levels of labels, and the distance between the first
level and the axis line. The value should be an integer from 0 to 1000.

TypeScript

setOffset(offset: number): void;

Parameters
offset number

Returns
void

setPosition(position)
Specifies the specified axis position where the other axis crosses. See
ExcelScript.ChartAxisPosition for details.

TypeScript

setPosition(position: ChartAxisPosition): void;

Parameters
position ExcelScript.ChartAxisPosition
Returns
void

setPositionAt(value)
Sets the specified axis position where the other axis crosses.

TypeScript

setPositionAt(value: number): void;

Parameters
value number
Custom value of the crossing point.

Returns
void

setReversePlotOrder(reversePlotOrder)
Specifies if Excel plots data points from last to first.

TypeScript

setReversePlotOrder(reversePlotOrder: boolean): void;

Parameters
reversePlotOrder boolean

Returns
void

setScaleType(scaleType)
Specifies the value axis scale type. See ExcelScript.ChartAxisScaleType for details.

TypeScript
setScaleType(scaleType: ChartAxisScaleType): void;

Parameters
scaleType ExcelScript.ChartAxisScaleType

Returns
void

setShowDisplayUnitLabel(showDisplayUnitLabel)
Specifies if the axis display unit label is visible.

TypeScript

setShowDisplayUnitLabel(showDisplayUnitLabel: boolean): void;

Parameters
showDisplayUnitLabel boolean

Returns
void

setTextOrientation(textOrientation)
Specifies the angle to which the text is oriented for the chart axis tick label. The value
should either be an integer from -90 to 90 or the integer 180 for vertically-oriented
text.

TypeScript

setTextOrientation(textOrientation: number): void;

Parameters
textOrientation number
Returns
void

setTickLabelPosition(tickLabelPosition)
Specifies the position of tick-mark labels on the specified axis. See
ExcelScript.ChartAxisTickLabelPosition for details.

TypeScript

setTickLabelPosition(
tickLabelPosition: ChartAxisTickLabelPosition
): void;

Parameters
tickLabelPosition ExcelScript.ChartAxisTickLabelPosition

Returns
void

setTickLabelSpacing(tickLabelSpacing)
Specifies the number of categories or series between tick-mark labels. Can be a value
from 1 through 31999.

TypeScript

setTickLabelSpacing(tickLabelSpacing: number): void;

Parameters
tickLabelSpacing number

Returns
void

setTickMarkSpacing(tickMarkSpacing)
Specifies the number of categories or series between tick marks.

TypeScript

setTickMarkSpacing(tickMarkSpacing: number): void;

Parameters
tickMarkSpacing number

Returns
void

setVisible(visible)
Specifies if the axis is visible.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisFormat interface
Reference
Package: ExcelScript

Encapsulates the format properties for the chart axis.

Methods
ノ Expand table

getFill() Specifies chart fill formatting.

getFont() Specifies the font attributes (font name, font size, color, etc.) for a chart axis element.

getLine() Specifies chart line formatting.

Method Details

getFill()
Specifies chart fill formatting.

TypeScript

getFill(): ChartFill;

Returns
ExcelScript.ChartFill

getFont()
Specifies the font attributes (font name, font size, color, etc.) for a chart axis element.

TypeScript

getFont(): ChartFont;

Returns
ExcelScript.ChartFont

getLine()
Specifies chart line formatting.

TypeScript

getLine(): ChartLineFormat;

Returns
ExcelScript.ChartLineFormat

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisTitle interface
Reference
Package: ExcelScript

Represents the title of a chart axis.

Methods
ノ Expand table

getFormat() Specifies the formatting of the chart axis title.

getText() Specifies the axis title.

getTextOrientation() Specifies the angle to which the text is oriented for the chart axis title.
The value should either be an integer from -90 to 90 or the integer 180
for vertically-oriented text.

getVisible() Specifies if the axis title is visible.

setFormula(formula) A string value that represents the formula of chart axis title using A1-
style notation.

setText(text) Specifies the axis title.

setTextOrientation(text Specifies the angle to which the text is oriented for the chart axis title.
Orientation) The value should either be an integer from -90 to 90 or the integer 180
for vertically-oriented text.

setVisible(visible) Specifies if the axis title is visible.

Method Details

getFormat()
Specifies the formatting of the chart axis title.

TypeScript

getFormat(): ChartAxisTitleFormat;

Returns
ExcelScript.ChartAxisTitleFormat

getText()
Specifies the axis title.

TypeScript

getText(): string;

Returns
string

getTextOrientation()
Specifies the angle to which the text is oriented for the chart axis title. The value
should either be an integer from -90 to 90 or the integer 180 for vertically-oriented
text.

TypeScript

getTextOrientation(): number;

Returns
number

getVisible()
Specifies if the axis title is visible.

TypeScript

getVisible(): boolean;

Returns
boolean

setFormula(formula)
A string value that represents the formula of chart axis title using A1-style notation.

TypeScript

setFormula(formula: string): void;

Parameters
formula string
A string that represents the formula to set.

Returns
void

setText(text)
Specifies the axis title.

TypeScript

setText(text: string): void;

Parameters
text string

Returns
void

setTextOrientation(textOrientation)
Specifies the angle to which the text is oriented for the chart axis title. The value
should either be an integer from -90 to 90 or the integer 180 for vertically-oriented
text.

TypeScript

setTextOrientation(textOrientation: number): void;


Parameters
textOrientation number

Returns
void

setVisible(visible)
Specifies if the axis title is visible.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartAxisTitleFormat
interface
Reference
Package: ExcelScript

Represents the chart axis title formatting.

Methods
ノ Expand table

get Specifies the chart axis title's border format, which includes color, linestyle, and
Border() weight.

getFill() Specifies the chart axis title's fill formatting.

getFont() Specifies the chart axis title's font attributes, such as font name, font size, or color, of
the chart axis title object.

Method Details

getBorder()
Specifies the chart axis title's border format, which includes color, linestyle, and
weight.

TypeScript

getBorder(): ChartBorder;

Returns
ExcelScript.ChartBorder

getFill()
Specifies the chart axis title's fill formatting.

TypeScript
getFill(): ChartFill;

Returns
ExcelScript.ChartFill

getFont()
Specifies the chart axis title's font attributes, such as font name, font size, or color, of
the chart axis title object.

TypeScript

getFont(): ChartFont;

Returns
ExcelScript.ChartFont

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartBinOptions interface
Reference
Package: ExcelScript

Encapsulates the bin options for histogram charts and pareto charts.

Methods
ノ Expand table

getAllowOverflow() Specifies if bin overflow is enabled in a histogram chart or


pareto chart.

getAllowUnderflow() Specifies if bin underflow is enabled in a histogram chart or


pareto chart.

getCount() Specifies the bin count of a histogram chart or pareto chart.

getOverflowValue() Specifies the bin overflow value of a histogram chart or pareto


chart.

getType() Specifies the bin's type for a histogram chart or pareto chart.

getUnderflowValue() Specifies the bin underflow value of a histogram chart or


pareto chart.

getWidth() Specifies the bin width value of a histogram chart or pareto


chart.

setAllowOverflow(allow Specifies if bin overflow is enabled in a histogram chart or


Overflow) pareto chart.

setAllowUnderflow(allow Specifies if bin underflow is enabled in a histogram chart or


Underflow) pareto chart.

setCount(count) Specifies the bin count of a histogram chart or pareto chart.

setOverflowValue(overflowValue) Specifies the bin overflow value of a histogram chart or pareto


chart.

setType(type) Specifies the bin's type for a histogram chart or pareto chart.

setUnderflowValue(underflow Specifies the bin underflow value of a histogram chart or


Value) pareto chart.

setWidth(width) Specifies the bin width value of a histogram chart or pareto


chart.
Method Details

getAllowOverflow()
Specifies if bin overflow is enabled in a histogram chart or pareto chart.

TypeScript

getAllowOverflow(): boolean;

Returns
boolean

getAllowUnderflow()
Specifies if bin underflow is enabled in a histogram chart or pareto chart.

TypeScript

getAllowUnderflow(): boolean;

Returns
boolean

getCount()
Specifies the bin count of a histogram chart or pareto chart.

TypeScript

getCount(): number;

Returns
number

getOverflowValue()
Specifies the bin overflow value of a histogram chart or pareto chart.
TypeScript

getOverflowValue(): number;

Returns
number

getType()
Specifies the bin's type for a histogram chart or pareto chart.

TypeScript

getType(): ChartBinType;

Returns
ExcelScript.ChartBinType

getUnderflowValue()
Specifies the bin underflow value of a histogram chart or pareto chart.

TypeScript

getUnderflowValue(): number;

Returns
number

getWidth()
Specifies the bin width value of a histogram chart or pareto chart.

TypeScript

getWidth(): number;
Returns
number

setAllowOverflow(allowOverflow)
Specifies if bin overflow is enabled in a histogram chart or pareto chart.

TypeScript

setAllowOverflow(allowOverflow: boolean): void;

Parameters
allowOverflow boolean

Returns
void

setAllowUnderflow(allowUnderflow)
Specifies if bin underflow is enabled in a histogram chart or pareto chart.

TypeScript

setAllowUnderflow(allowUnderflow: boolean): void;

Parameters
allowUnderflow boolean

Returns
void

setCount(count)
Specifies the bin count of a histogram chart or pareto chart.

TypeScript
setCount(count: number): void;

Parameters
count number

Returns
void

setOverflowValue(overflowValue)
Specifies the bin overflow value of a histogram chart or pareto chart.

TypeScript

setOverflowValue(overflowValue: number): void;

Parameters
overflowValue number

Returns
void

setType(type)
Specifies the bin's type for a histogram chart or pareto chart.

TypeScript

setType(type: ChartBinType): void;

Parameters
type ExcelScript.ChartBinType

Returns
void
setUnderflowValue(underflowValue)
Specifies the bin underflow value of a histogram chart or pareto chart.

TypeScript

setUnderflowValue(underflowValue: number): void;

Parameters
underflowValue number

Returns
void

setWidth(width)
Specifies the bin width value of a histogram chart or pareto chart.

TypeScript

setWidth(width: number): void;

Parameters
width number

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartBorder interface
Reference
Package: ExcelScript

Represents the border formatting of a chart element.

Methods
ノ Expand table

clear() Clear the border format of a chart element.

getColor() HTML color code representing the color of borders in the chart.

getLineStyle() Represents the line style of the border. See ExcelScript.ChartLineStyle


for details.

getWeight() Represents weight of the border, in points.

setColor(color) HTML color code representing the color of borders in the chart.

setLineStyle(line Represents the line style of the border. See ExcelScript.ChartLineStyle


Style) for details.

setWeight(weight) Represents weight of the border, in points.

Method Details

clear()
Clear the border format of a chart element.

TypeScript

clear(): void;

Returns
void

getColor()
HTML color code representing the color of borders in the chart.

TypeScript

getColor(): string;

Returns
string

getLineStyle()
Represents the line style of the border. See ExcelScript.ChartLineStyle for details.

TypeScript

getLineStyle(): ChartLineStyle;

Returns
ExcelScript.ChartLineStyle

getWeight()
Represents weight of the border, in points.

TypeScript

getWeight(): number;

Returns
number

setColor(color)
HTML color code representing the color of borders in the chart.

TypeScript

setColor(color: string): void;


Parameters
color string

Returns
void

setLineStyle(lineStyle)
Represents the line style of the border. See ExcelScript.ChartLineStyle for details.

TypeScript

setLineStyle(lineStyle: ChartLineStyle): void;

Parameters
lineStyle ExcelScript.ChartLineStyle

Returns
void

setWeight(weight)
Represents weight of the border, in points.

TypeScript

setWeight(weight: number): void;

Parameters
weight number

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartBoxwhiskerOptions
interface
Reference
Package: ExcelScript

Represents the properties of a box and whisker chart.

Methods
ノ Expand table

getQuartileCalculation() Specifies if the quartile calculation type of a box and


whisker chart.

getShowInnerPoints() Specifies if inner points are shown in a box and whisker


chart.

getShowMeanLine() Specifies if the mean line is shown in a box and whisker


chart.

getShowMeanMarker() Specifies if the mean marker is shown in a box and


whisker chart.

getShowOutlierPoints() Specifies if outlier points are shown in a box and whisker


chart.

setQuartileCalculation(quartile Specifies if the quartile calculation type of a box and


Calculation) whisker chart.

setShowInnerPoints(showInnerPoints) Specifies if inner points are shown in a box and whisker


chart.

setShowMeanLine(showMeanLine) Specifies if the mean line is shown in a box and whisker


chart.

setShowMeanMarker(showMean Specifies if the mean marker is shown in a box and


Marker) whisker chart.

setShowOutlierPoints(showOutlier Specifies if outlier points are shown in a box and whisker


Points) chart.

Method Details
getQuartileCalculation()
Specifies if the quartile calculation type of a box and whisker chart.

TypeScript

getQuartileCalculation(): ChartBoxQuartileCalculation;

Returns
ExcelScript.ChartBoxQuartileCalculation

getShowInnerPoints()
Specifies if inner points are shown in a box and whisker chart.

TypeScript

getShowInnerPoints(): boolean;

Returns
boolean

getShowMeanLine()
Specifies if the mean line is shown in a box and whisker chart.

TypeScript

getShowMeanLine(): boolean;

Returns
boolean

getShowMeanMarker()
Specifies if the mean marker is shown in a box and whisker chart.

TypeScript
getShowMeanMarker(): boolean;

Returns
boolean

getShowOutlierPoints()
Specifies if outlier points are shown in a box and whisker chart.

TypeScript

getShowOutlierPoints(): boolean;

Returns
boolean

setQuartileCalculation(quartileCalculation)
Specifies if the quartile calculation type of a box and whisker chart.

TypeScript

setQuartileCalculation(
quartileCalculation: ChartBoxQuartileCalculation
): void;

Parameters
quartileCalculation ExcelScript.ChartBoxQuartileCalculation

Returns
void

setShowInnerPoints(showInnerPoints)
Specifies if inner points are shown in a box and whisker chart.

TypeScript
setShowInnerPoints(showInnerPoints: boolean): void;

Parameters
showInnerPoints boolean

Returns
void

setShowMeanLine(showMeanLine)
Specifies if the mean line is shown in a box and whisker chart.

TypeScript

setShowMeanLine(showMeanLine: boolean): void;

Parameters
showMeanLine boolean

Returns
void

setShowMeanMarker(showMeanMarker)
Specifies if the mean marker is shown in a box and whisker chart.

TypeScript

setShowMeanMarker(showMeanMarker: boolean): void;

Parameters
showMeanMarker boolean

Returns
void
setShowOutlierPoints(showOutlierPoints)
Specifies if outlier points are shown in a box and whisker chart.

TypeScript

setShowOutlierPoints(showOutlierPoints: boolean): void;

Parameters
showOutlierPoints boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartDataLabel interface
Reference
Package: ExcelScript

Represents the data label of a chart point.

Methods
ノ Expand table

getAutoText() Specifies if the data label automatically generates appropriate text


based on context.

getFormat() Represents the format of chart data label.

getFormula() String value that represents the formula of chart data label using A1-
style notation.

getHeight() Returns the height, in points, of the chart data label. Value is null if
the chart data label is not visible.

getHorizontalAlignment() Represents the horizontal alignment for chart data label. See
ExcelScript.ChartTextHorizontalAlignment for details. This property
is valid only when TextOrientation of data label is -90, 90, or 180.

getLeft() Represents the distance, in points, from the left edge of chart data
label to the left edge of chart area. Value is null if the chart data
label is not visible.

getLinkNumberFormat() Specifies if the number format is linked to the cells (so that the
number format changes in the labels when it changes in the cells).

getNumberFormat() String value that represents the format code for data label.

getPosition() Value that represents the position of the data label. See
ExcelScript.ChartDataLabelPosition for details.

getSeparator() String representing the separator used for the data label on a chart.

getShowBubbleSize() Specifies if the data label bubble size is visible.

getShowCategoryName() Specifies if the data label category name is visible.

getShowLegendKey() Specifies if the data label legend key is visible.

getShowPercentage() Specifies if the data label percentage is visible.


getShowSeriesName() Specifies if the data label series name is visible.

getShowValue() Specifies if the data label value is visible.

getText() String representing the text of the data label on a chart.

getTextOrientation() Represents the angle to which the text is oriented for the chart data
label. The value should either be an integer from -90 to 90 or the
integer 180 for vertically-oriented text.

getTop() Represents the distance, in points, from the top edge of chart data
label to the top of chart area. Value is null if the chart data label is
not visible.

getVerticalAlignment() Represents the vertical alignment of chart data label. See


ExcelScript.ChartTextVerticalAlignment for details. This property is
valid only when TextOrientation of data label is 0.

getWidth() Returns the width, in points, of the chart data label. Value is null if
the chart data label is not visible.

setAutoText(autoText) Specifies if the data label automatically generates appropriate text


based on context.

setFormula(formula) String value that represents the formula of chart data label using A1-
style notation.

setHorizontal Represents the horizontal alignment for chart data label. See
Alignment(horizontal ExcelScript.ChartTextHorizontalAlignment for details. This property
Alignment) is valid only when TextOrientation of data label is -90, 90, or 180.

setLeft(left) Represents the distance, in points, from the left edge of chart data
label to the left edge of chart area. Value is null if the chart data
label is not visible.

setLinkNumber Specifies if the number format is linked to the cells (so that the
Format(linkNumber number format changes in the labels when it changes in the cells).
Format)

setNumber String value that represents the format code for data label.
Format(numberFormat)

setPosition(position) Value that represents the position of the data label. See
ExcelScript.ChartDataLabelPosition for details.

setSeparator(separator) String representing the separator used for the data label on a chart.

setShowBubbleSize(show Specifies if the data label bubble size is visible.


BubbleSize)

setShowCategory Specifies if the data label category name is visible.


Name(showCategory
Name)

setShowLegendKey(show Specifies if the data label legend key is visible.


LegendKey)

setShowPercentage(show Specifies if the data label percentage is visible.


Percentage)

setShowSeries Specifies if the data label series name is visible.


Name(showSeriesName)

setShowValue(show Specifies if the data label value is visible.


Value)

setText(text) String representing the text of the data label on a chart.

setTextOrientation(text Represents the angle to which the text is oriented for the chart data
Orientation) label. The value should either be an integer from -90 to 90 or the
integer 180 for vertically-oriented text.

setTop(top) Represents the distance, in points, from the top edge of chart data
label to the top of chart area. Value is null if the chart data label is
not visible.

setVertical Represents the vertical alignment of chart data label. See


Alignment(vertical ExcelScript.ChartTextVerticalAlignment for details. This property is
Alignment) valid only when TextOrientation of data label is 0.

Method Details

getAutoText()
Specifies if the data label automatically generates appropriate text based on context.

TypeScript

getAutoText(): boolean;

Returns
boolean

getFormat()
Represents the format of chart data label.
TypeScript

getFormat(): ChartDataLabelFormat;

Returns
ExcelScript.ChartDataLabelFormat

getFormula()
String value that represents the formula of chart data label using A1-style notation.

TypeScript

getFormula(): string;

Returns
string

getHeight()
Returns the height, in points, of the chart data label. Value is null if the chart data
label is not visible.

TypeScript

getHeight(): number;

Returns
number

getHorizontalAlignment()
Represents the horizontal alignment for chart data label. See
ExcelScript.ChartTextHorizontalAlignment for details. This property is valid only

when TextOrientation of data label is -90, 90, or 180.

TypeScript
getHorizontalAlignment(): ChartTextHorizontalAlignment;

Returns
ExcelScript.ChartTextHorizontalAlignment

getLeft()
Represents the distance, in points, from the left edge of chart data label to the left
edge of chart area. Value is null if the chart data label is not visible.

TypeScript

getLeft(): number;

Returns
number

getLinkNumberFormat()
Specifies if the number format is linked to the cells (so that the number format
changes in the labels when it changes in the cells).

TypeScript

getLinkNumberFormat(): boolean;

Returns
boolean

getNumberFormat()
String value that represents the format code for data label.

TypeScript

getNumberFormat(): string;
Returns
string

getPosition()
Value that represents the position of the data label. See
ExcelScript.ChartDataLabelPosition for details.

TypeScript

getPosition(): ChartDataLabelPosition;

Returns
ExcelScript.ChartDataLabelPosition

getSeparator()
String representing the separator used for the data label on a chart.

TypeScript

getSeparator(): string;

Returns
string

getShowBubbleSize()
Specifies if the data label bubble size is visible.

TypeScript

getShowBubbleSize(): boolean;

Returns
boolean
getShowCategoryName()
Specifies if the data label category name is visible.

TypeScript

getShowCategoryName(): boolean;

Returns
boolean

getShowLegendKey()
Specifies if the data label legend key is visible.

TypeScript

getShowLegendKey(): boolean;

Returns
boolean

getShowPercentage()
Specifies if the data label percentage is visible.

TypeScript

getShowPercentage(): boolean;

Returns
boolean

getShowSeriesName()
Specifies if the data label series name is visible.

TypeScript
getShowSeriesName(): boolean;

Returns
boolean

getShowValue()
Specifies if the data label value is visible.

TypeScript

getShowValue(): boolean;

Returns
boolean

getText()
String representing the text of the data label on a chart.

TypeScript

getText(): string;

Returns
string

getTextOrientation()
Represents the angle to which the text is oriented for the chart data label. The value
should either be an integer from -90 to 90 or the integer 180 for vertically-oriented
text.

TypeScript

getTextOrientation(): number;
Returns
number

getTop()
Represents the distance, in points, from the top edge of chart data label to the top of
chart area. Value is null if the chart data label is not visible.

TypeScript

getTop(): number;

Returns
number

getVerticalAlignment()
Represents the vertical alignment of chart data label. See
ExcelScript.ChartTextVerticalAlignment for details. This property is valid only when

TextOrientation of data label is 0.

TypeScript

getVerticalAlignment(): ChartTextVerticalAlignment;

Returns
ExcelScript.ChartTextVerticalAlignment

getWidth()
Returns the width, in points, of the chart data label. Value is null if the chart data
label is not visible.

TypeScript

getWidth(): number;

Returns
number

setAutoText(autoText)
Specifies if the data label automatically generates appropriate text based on context.

TypeScript

setAutoText(autoText: boolean): void;

Parameters
autoText boolean

Returns
void

setFormula(formula)
String value that represents the formula of chart data label using A1-style notation.

TypeScript

setFormula(formula: string): void;

Parameters
formula string

Returns
void

setHorizontalAlignment(horizontalAlignment)
Represents the horizontal alignment for chart data label. See
ExcelScript.ChartTextHorizontalAlignment for details. This property is valid only

when TextOrientation of data label is -90, 90, or 180.

TypeScript
setHorizontalAlignment(
horizontalAlignment: ChartTextHorizontalAlignment
): void;

Parameters
horizontalAlignment ExcelScript.ChartTextHorizontalAlignment

Returns
void

setLeft(left)
Represents the distance, in points, from the left edge of chart data label to the left
edge of chart area. Value is null if the chart data label is not visible.

TypeScript

setLeft(left: number): void;

Parameters
left number

Returns
void

setLinkNumberFormat(linkNumberFormat)
Specifies if the number format is linked to the cells (so that the number format
changes in the labels when it changes in the cells).

TypeScript

setLinkNumberFormat(linkNumberFormat: boolean): void;

Parameters
linkNumberFormat boolean
Returns
void

setNumberFormat(numberFormat)
String value that represents the format code for data label.

TypeScript

setNumberFormat(numberFormat: string): void;

Parameters
numberFormat string

Returns
void

setPosition(position)
Value that represents the position of the data label. See
ExcelScript.ChartDataLabelPosition for details.

TypeScript

setPosition(position: ChartDataLabelPosition): void;

Parameters
position ExcelScript.ChartDataLabelPosition

Returns
void

setSeparator(separator)
String representing the separator used for the data label on a chart.

TypeScript
setSeparator(separator: string): void;

Parameters
separator string

Returns
void

setShowBubbleSize(showBubbleSize)
Specifies if the data label bubble size is visible.

TypeScript

setShowBubbleSize(showBubbleSize: boolean): void;

Parameters
showBubbleSize boolean

Returns
void

setShowCategoryName(showCategoryName)
Specifies if the data label category name is visible.

TypeScript

setShowCategoryName(showCategoryName: boolean): void;

Parameters
showCategoryName boolean

Returns
void
setShowLegendKey(showLegendKey)
Specifies if the data label legend key is visible.

TypeScript

setShowLegendKey(showLegendKey: boolean): void;

Parameters
showLegendKey boolean

Returns
void

setShowPercentage(showPercentage)
Specifies if the data label percentage is visible.

TypeScript

setShowPercentage(showPercentage: boolean): void;

Parameters
showPercentage boolean

Returns
void

setShowSeriesName(showSeriesName)
Specifies if the data label series name is visible.

TypeScript

setShowSeriesName(showSeriesName: boolean): void;

Parameters
showSeriesName boolean

Returns
void

setShowValue(showValue)
Specifies if the data label value is visible.

TypeScript

setShowValue(showValue: boolean): void;

Parameters
showValue boolean

Returns
void

setText(text)
String representing the text of the data label on a chart.

TypeScript

setText(text: string): void;

Parameters
text string

Returns
void

setTextOrientation(textOrientation)
Represents the angle to which the text is oriented for the chart data label. The value
should either be an integer from -90 to 90 or the integer 180 for vertically-oriented
text.

TypeScript

setTextOrientation(textOrientation: number): void;

Parameters
textOrientation number

Returns
void

setTop(top)
Represents the distance, in points, from the top edge of chart data label to the top of
chart area. Value is null if the chart data label is not visible.

TypeScript

setTop(top: number): void;

Parameters
top number

Returns
void

setVerticalAlignment(verticalAlignment)
Represents the vertical alignment of chart data label. See
ExcelScript.ChartTextVerticalAlignment for details. This property is valid only when

TextOrientation of data label is 0.

TypeScript
setVerticalAlignment(
verticalAlignment: ChartTextVerticalAlignment
): void;

Parameters
verticalAlignment ExcelScript.ChartTextVerticalAlignment

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartDataLabelFormat
interface
Reference
Package: ExcelScript

Encapsulates the format properties for the chart data labels.

Methods
ノ Expand table

get Represents the border format, which includes color, linestyle, and weight.
Border()

getFill() Represents the fill format of the current chart data label.

getFont() Represents the font attributes (such as font name, font size, and color) for a chart
data label.

Method Details

getBorder()
Represents the border format, which includes color, linestyle, and weight.

TypeScript

getBorder(): ChartBorder;

Returns
ExcelScript.ChartBorder

getFill()
Represents the fill format of the current chart data label.

TypeScript
getFill(): ChartFill;

Returns
ExcelScript.ChartFill

getFont()
Represents the font attributes (such as font name, font size, and color) for a chart
data label.

TypeScript

getFont(): ChartFont;

Returns
ExcelScript.ChartFont

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartDataLabels interface
Reference
Package: ExcelScript

Represents a collection of all the data labels on a chart point.

Methods
ノ Expand table

getAutoText() Specifies if data labels automatically generate appropriate text based


on context.

getFormat() Specifies the format of chart data labels, which includes fill and font
formatting.

getHorizontalAlignment() Specifies the horizontal alignment for chart data label. See
ExcelScript.ChartTextHorizontalAlignment for details. This property
is valid only when the TextOrientation of data label is 0.

getLinkNumberFormat() Specifies if the number format is linked to the cells. If true , the
number format will change in the labels when it changes in the cells.

getNumberFormat() Specifies the format code for data labels.

getPosition() Value that represents the position of the data label. See
ExcelScript.ChartDataLabelPosition for details.

getSeparator() String representing the separator used for the data labels on a chart.

getShowBubbleSize() Specifies if the data label bubble size is visible.

getShowCategoryName() Specifies if the data label category name is visible.

getShowLegendKey() Specifies if the data label legend key is visible.

getShowPercentage() Specifies if the data label percentage is visible.

getShowSeriesName() Specifies if the data label series name is visible.

getShowValue() Specifies if the data label value is visible.

getTextOrientation() Represents the angle to which the text is oriented for data labels. The
value should either be an integer from -90 to 90 or the integer 180
for vertically-oriented text.

getVerticalAlignment() Represents the vertical alignment of chart data label. See


ExcelScript.ChartTextVerticalAlignment for details. This property is
valid only when TextOrientation of the data label is -90, 90, or 180.

setAutoText(autoText) Specifies if data labels automatically generate appropriate text based


on context.

setHorizontal Specifies the horizontal alignment for chart data label. See
Alignment(horizontal ExcelScript.ChartTextHorizontalAlignment for details. This property
Alignment) is valid only when the TextOrientation of data label is 0.

setLinkNumber Specifies if the number format is linked to the cells. If true , the
Format(linkNumber number format will change in the labels when it changes in the cells.
Format)

setNumber Specifies the format code for data labels.


Format(numberFormat)

setPosition(position) Value that represents the position of the data label. See
ExcelScript.ChartDataLabelPosition for details.

setSeparator(separator) String representing the separator used for the data labels on a chart.

setShowBubbleSize(show Specifies if the data label bubble size is visible.


BubbleSize)

setShowCategory Specifies if the data label category name is visible.


Name(showCategory
Name)

setShowLegendKey(show Specifies if the data label legend key is visible.


LegendKey)

setShowPercentage(show Specifies if the data label percentage is visible.


Percentage)

setShowSeries Specifies if the data label series name is visible.


Name(showSeriesName)

setShowValue(show Specifies if the data label value is visible.


Value)

setTextOrientation(text Represents the angle to which the text is oriented for data labels. The
Orientation) value should either be an integer from -90 to 90 or the integer 180
for vertically-oriented text.

setVertical Represents the vertical alignment of chart data label. See


Alignment(vertical ExcelScript.ChartTextVerticalAlignment for details. This property is
Alignment) valid only when TextOrientation of the data label is -90, 90, or 180.

Method Details
getAutoText()
Specifies if data labels automatically generate appropriate text based on context.

TypeScript

getAutoText(): boolean;

Returns
boolean

getFormat()
Specifies the format of chart data labels, which includes fill and font formatting.

TypeScript

getFormat(): ChartDataLabelFormat;

Returns
ExcelScript.ChartDataLabelFormat

getHorizontalAlignment()
Specifies the horizontal alignment for chart data label. See
ExcelScript.ChartTextHorizontalAlignment for details. This property is valid only

when the TextOrientation of data label is 0.

TypeScript

getHorizontalAlignment(): ChartTextHorizontalAlignment;

Returns
ExcelScript.ChartTextHorizontalAlignment

getLinkNumberFormat()
Specifies if the number format is linked to the cells. If true , the number format will
change in the labels when it changes in the cells.

TypeScript

getLinkNumberFormat(): boolean;

Returns
boolean

getNumberFormat()
Specifies the format code for data labels.

TypeScript

getNumberFormat(): string;

Returns
string

getPosition()
Value that represents the position of the data label. See
ExcelScript.ChartDataLabelPosition for details.

TypeScript

getPosition(): ChartDataLabelPosition;

Returns
ExcelScript.ChartDataLabelPosition

getSeparator()
String representing the separator used for the data labels on a chart.

TypeScript
getSeparator(): string;

Returns
string

getShowBubbleSize()
Specifies if the data label bubble size is visible.

TypeScript

getShowBubbleSize(): boolean;

Returns
boolean

getShowCategoryName()
Specifies if the data label category name is visible.

TypeScript

getShowCategoryName(): boolean;

Returns
boolean

getShowLegendKey()
Specifies if the data label legend key is visible.

TypeScript

getShowLegendKey(): boolean;

Returns
boolean

getShowPercentage()
Specifies if the data label percentage is visible.

TypeScript

getShowPercentage(): boolean;

Returns
boolean

getShowSeriesName()
Specifies if the data label series name is visible.

TypeScript

getShowSeriesName(): boolean;

Returns
boolean

getShowValue()
Specifies if the data label value is visible.

TypeScript

getShowValue(): boolean;

Returns
boolean

getTextOrientation()
Represents the angle to which the text is oriented for data labels. The value should
either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.

TypeScript

getTextOrientation(): number;

Returns
number

getVerticalAlignment()
Represents the vertical alignment of chart data label. See
ExcelScript.ChartTextVerticalAlignment for details. This property is valid only when

TextOrientation of the data label is -90, 90, or 180.

TypeScript

getVerticalAlignment(): ChartTextVerticalAlignment;

Returns
ExcelScript.ChartTextVerticalAlignment

setAutoText(autoText)
Specifies if data labels automatically generate appropriate text based on context.

TypeScript

setAutoText(autoText: boolean): void;

Parameters
autoText boolean

Returns
void
setHorizontalAlignment(horizontalAlignment)
Specifies the horizontal alignment for chart data label. See
ExcelScript.ChartTextHorizontalAlignment for details. This property is valid only

when the TextOrientation of data label is 0.

TypeScript

setHorizontalAlignment(
horizontalAlignment: ChartTextHorizontalAlignment
): void;

Parameters
horizontalAlignment ExcelScript.ChartTextHorizontalAlignment

Returns
void

setLinkNumberFormat(linkNumberFormat)
Specifies if the number format is linked to the cells. If true , the number format will
change in the labels when it changes in the cells.

TypeScript

setLinkNumberFormat(linkNumberFormat: boolean): void;

Parameters
linkNumberFormat boolean

Returns
void

setNumberFormat(numberFormat)
Specifies the format code for data labels.

TypeScript
setNumberFormat(numberFormat: string): void;

Parameters
numberFormat string

Returns
void

setPosition(position)
Value that represents the position of the data label. See
ExcelScript.ChartDataLabelPosition for details.

TypeScript

setPosition(position: ChartDataLabelPosition): void;

Parameters
position ExcelScript.ChartDataLabelPosition

Returns
void

setSeparator(separator)
String representing the separator used for the data labels on a chart.

TypeScript

setSeparator(separator: string): void;

Parameters
separator string

Returns
void

setShowBubbleSize(showBubbleSize)
Specifies if the data label bubble size is visible.

TypeScript

setShowBubbleSize(showBubbleSize: boolean): void;

Parameters
showBubbleSize boolean

Returns
void

setShowCategoryName(showCategoryName)
Specifies if the data label category name is visible.

TypeScript

setShowCategoryName(showCategoryName: boolean): void;

Parameters
showCategoryName boolean

Returns
void

setShowLegendKey(showLegendKey)
Specifies if the data label legend key is visible.

TypeScript

setShowLegendKey(showLegendKey: boolean): void;


Parameters
showLegendKey boolean

Returns
void

setShowPercentage(showPercentage)
Specifies if the data label percentage is visible.

TypeScript

setShowPercentage(showPercentage: boolean): void;

Parameters
showPercentage boolean

Returns
void

setShowSeriesName(showSeriesName)
Specifies if the data label series name is visible.

TypeScript

setShowSeriesName(showSeriesName: boolean): void;

Parameters
showSeriesName boolean

Returns
void

setShowValue(showValue)
Specifies if the data label value is visible.

TypeScript

setShowValue(showValue: boolean): void;

Parameters
showValue boolean

Returns
void

setTextOrientation(textOrientation)
Represents the angle to which the text is oriented for data labels. The value should
either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.

TypeScript

setTextOrientation(textOrientation: number): void;

Parameters
textOrientation number

Returns
void

setVerticalAlignment(verticalAlignment)
Represents the vertical alignment of chart data label. See
ExcelScript.ChartTextVerticalAlignment for details. This property is valid only when

TextOrientation of the data label is -90, 90, or 180.

TypeScript

setVerticalAlignment(
verticalAlignment: ChartTextVerticalAlignment
): void;
Parameters
verticalAlignment ExcelScript.ChartTextVerticalAlignment

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartDataTable interface
Reference
Package: ExcelScript

Represents the data table object of a chart.

Methods
ノ Expand table

getFormat() Represents the format of a chart data table, which includes


fill, font, and border format.

getShowHorizontalBorder() Specifies whether to display the horizontal border of the


data table.

getShowLegendKey() Specifies whether to show the legend key of the data table.

getShowOutlineBorder() Specifies whether to display the outline border of the data


table.

getShowVerticalBorder() Specifies whether to display the vertical border of the data


table.

getVisible() Specifies whether to show the data table of the chart.

setShowHorizontalBorder(show Specifies whether to display the horizontal border of the


HorizontalBorder) data table.

setShowLegendKey(showLegend Specifies whether to show the legend key of the data table.
Key)

setShowOutlineBorder(showOutline Specifies whether to display the outline border of the data


Border) table.

setShowVerticalBorder(showVertical Specifies whether to display the vertical border of the data


Border) table.

setVisible(visible) Specifies whether to show the data table of the chart.

Method Details

getFormat()
Represents the format of a chart data table, which includes fill, font, and border
format.

TypeScript

getFormat(): ChartDataTableFormat;

Returns
ExcelScript.ChartDataTableFormat

getShowHorizontalBorder()
Specifies whether to display the horizontal border of the data table.

TypeScript

getShowHorizontalBorder(): boolean;

Returns
boolean

getShowLegendKey()
Specifies whether to show the legend key of the data table.

TypeScript

getShowLegendKey(): boolean;

Returns
boolean

getShowOutlineBorder()
Specifies whether to display the outline border of the data table.

TypeScript
getShowOutlineBorder(): boolean;

Returns
boolean

getShowVerticalBorder()
Specifies whether to display the vertical border of the data table.

TypeScript

getShowVerticalBorder(): boolean;

Returns
boolean

getVisible()
Specifies whether to show the data table of the chart.

TypeScript

getVisible(): boolean;

Returns
boolean

setShowHorizontalBorder(showHorizontalBorder)
Specifies whether to display the horizontal border of the data table.

TypeScript

setShowHorizontalBorder(showHorizontalBorder: boolean): void;

Parameters
showHorizontalBorder boolean

Returns
void

setShowLegendKey(showLegendKey)
Specifies whether to show the legend key of the data table.

TypeScript

setShowLegendKey(showLegendKey: boolean): void;

Parameters
showLegendKey boolean

Returns
void

setShowOutlineBorder(showOutlineBorder)
Specifies whether to display the outline border of the data table.

TypeScript

setShowOutlineBorder(showOutlineBorder: boolean): void;

Parameters
showOutlineBorder boolean

Returns
void

setShowVerticalBorder(showVerticalBorder)
Specifies whether to display the vertical border of the data table.
TypeScript

setShowVerticalBorder(showVerticalBorder: boolean): void;

Parameters
showVerticalBorder boolean

Returns
void

setVisible(visible)
Specifies whether to show the data table of the chart.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartDataTableFormat
interface
Reference
Package: ExcelScript

Represents the format of a chart data table.

Methods
ノ Expand table

get Represents the border format of chart data table, which includes color, line style,
Border() and weight.

getFill() Represents the fill format of an object, which includes background formatting
information.

getFont() Represents the font attributes (such as font name, font size, and color) for the
current object.

Method Details

getBorder()
Represents the border format of chart data table, which includes color, line style, and
weight.

TypeScript

getBorder(): ChartBorder;

Returns
ExcelScript.ChartBorder

getFill()
Represents the fill format of an object, which includes background formatting
information.
TypeScript

getFill(): ChartFill;

Returns
ExcelScript.ChartFill

getFont()
Represents the font attributes (such as font name, font size, and color) for the
current object.

TypeScript

getFont(): ChartFont;

Returns
ExcelScript.ChartFont

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartErrorBars interface
Reference
Package: ExcelScript

This object represents the attributes for a chart's error bars.

Methods
ノ Expand table

getEndStyleCap() Specifies if error bars have an end style cap.

getFormat() Specifies the formatting type of the error bars.

getInclude() Specifies which parts of the error bars to include.

getType() The type of range marked by the error bars.

getVisible() Specifies whether the error bars are displayed.

setEndStyleCap(endStyleCap) Specifies if error bars have an end style cap.

setInclude(include) Specifies which parts of the error bars to include.

setType(type) The type of range marked by the error bars.

setVisible(visible) Specifies whether the error bars are displayed.

Method Details

getEndStyleCap()
Specifies if error bars have an end style cap.

TypeScript

getEndStyleCap(): boolean;

Returns
boolean
getFormat()
Specifies the formatting type of the error bars.

TypeScript

getFormat(): ChartErrorBarsFormat;

Returns
ExcelScript.ChartErrorBarsFormat

getInclude()
Specifies which parts of the error bars to include.

TypeScript

getInclude(): ChartErrorBarsInclude;

Returns
ExcelScript.ChartErrorBarsInclude

getType()
The type of range marked by the error bars.

TypeScript

getType(): ChartErrorBarsType;

Returns
ExcelScript.ChartErrorBarsType

getVisible()
Specifies whether the error bars are displayed.

TypeScript
getVisible(): boolean;

Returns
boolean

setEndStyleCap(endStyleCap)
Specifies if error bars have an end style cap.

TypeScript

setEndStyleCap(endStyleCap: boolean): void;

Parameters
endStyleCap boolean

Returns
void

setInclude(include)
Specifies which parts of the error bars to include.

TypeScript

setInclude(include: ChartErrorBarsInclude): void;

Parameters
include ExcelScript.ChartErrorBarsInclude

Returns
void

setType(type)
The type of range marked by the error bars.

TypeScript

setType(type: ChartErrorBarsType): void;

Parameters
type ExcelScript.ChartErrorBarsType

Returns
void

setVisible(visible)
Specifies whether the error bars are displayed.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartErrorBarsFormat
interface
Reference
Package: ExcelScript

Encapsulates the format properties for chart error bars.

Methods
ノ Expand table

getLine() Represents the chart line formatting.

Method Details

getLine()
Represents the chart line formatting.

TypeScript

getLine(): ChartLineFormat;

Returns
ExcelScript.ChartLineFormat

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartFill interface
Reference
Package: ExcelScript

Represents the fill formatting for a chart element.

Methods
ノ Expand table

clear() Clears the fill color of a chart element.

getSolidColor() Gets the uniform color fill formatting of a chart element.

setSolidColor(color) Sets the fill formatting of a chart element to a uniform color.

Method Details

clear()
Clears the fill color of a chart element.

TypeScript

clear(): void;

Returns
void

getSolidColor()
Gets the uniform color fill formatting of a chart element.

TypeScript

getSolidColor(): string;

Returns
string

setSolidColor(color)
Sets the fill formatting of a chart element to a uniform color.

TypeScript

setSolidColor(color: string): void;

Parameters
color string
HTML color code representing the color of the background, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange").

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartFont interface
Reference
Package: ExcelScript

This object represents the font attributes (such as font name, font size, and color) for a
chart object.

Methods
ノ Expand table

getBold() Represents the bold status of font.

getColor() HTML color code representation of the text color (e.g., #FF0000
represents Red).

getItalic() Represents the italic status of the font.

getName() Font name (e.g., "Calibri")

getSize() Size of the font (e.g., 11)

getUnderline() Type of underline applied to the font. See


ExcelScript.ChartUnderlineStyle for details.

setBold(bold) Represents the bold status of font.

setColor(color) HTML color code representation of the text color (e.g., #FF0000
represents Red).

setItalic(italic) Represents the italic status of the font.

setName(name) Font name (e.g., "Calibri")

setSize(size) Size of the font (e.g., 11)

set Type of underline applied to the font. See


Underline(underline) ExcelScript.ChartUnderlineStyle for details.

Method Details

getBold()
Represents the bold status of font.
TypeScript

getBold(): boolean;

Returns
boolean

getColor()
HTML color code representation of the text color (e.g., #FF0000 represents Red).

TypeScript

getColor(): string;

Returns
string

getItalic()
Represents the italic status of the font.

TypeScript

getItalic(): boolean;

Returns
boolean

getName()
Font name (e.g., "Calibri")

TypeScript

getName(): string;
Returns
string

getSize()
Size of the font (e.g., 11)

TypeScript

getSize(): number;

Returns
number

getUnderline()
Type of underline applied to the font. See ExcelScript.ChartUnderlineStyle for
details.

TypeScript

getUnderline(): ChartUnderlineStyle;

Returns
ExcelScript.ChartUnderlineStyle

setBold(bold)
Represents the bold status of font.

TypeScript

setBold(bold: boolean): void;

Parameters
bold boolean
Returns
void

setColor(color)
HTML color code representation of the text color (e.g., #FF0000 represents Red).

TypeScript

setColor(color: string): void;

Parameters
color string

Returns
void

setItalic(italic)
Represents the italic status of the font.

TypeScript

setItalic(italic: boolean): void;

Parameters
italic boolean

Returns
void

setName(name)
Font name (e.g., "Calibri")

TypeScript
setName(name: string): void;

Parameters
name string

Returns
void

setSize(size)
Size of the font (e.g., 11)

TypeScript

setSize(size: number): void;

Parameters
size number

Returns
void

setUnderline(underline)
Type of underline applied to the font. See ExcelScript.ChartUnderlineStyle for
details.

TypeScript

setUnderline(underline: ChartUnderlineStyle): void;

Parameters
underline ExcelScript.ChartUnderlineStyle

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartFormatString interface
Reference
Package: ExcelScript

Represents the substring in chart related objects that contain text, like a ChartTitle
object or ChartAxisTitle object.

Methods
ノ Expand table

get Represents the font attributes, such as font name, font size, and color of a chart
Font() characters object.

Method Details

getFont()
Represents the font attributes, such as font name, font size, and color of a chart
characters object.

TypeScript

getFont(): ChartFont;

Returns
ExcelScript.ChartFont

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.ChartGridlines interface
Reference
Package: ExcelScript

Represents major or minor gridlines on a chart axis.

Methods
ノ Expand table

getFormat() Represents the formatting of chart gridlines.

getVisible() Specifies if the axis gridlines are visible.

setVisible(visible) Specifies if the axis gridlines are visible.

Method Details

getFormat()
Represents the formatting of chart gridlines.

TypeScript

getFormat(): ChartGridlinesFormat;

Returns
ExcelScript.ChartGridlinesFormat

getVisible()
Specifies if the axis gridlines are visible.

TypeScript

getVisible(): boolean;

Returns
boolean

setVisible(visible)
Specifies if the axis gridlines are visible.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartGridlinesFormat
interface
Reference
Package: ExcelScript

Encapsulates the format properties for chart gridlines.

Methods
ノ Expand table

getLine() Represents chart line formatting.

Method Details

getLine()
Represents chart line formatting.

TypeScript

getLine(): ChartLineFormat;

Returns
ExcelScript.ChartLineFormat

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartLegend interface
Reference
Package: ExcelScript

Represents the legend in a chart.

Methods
ノ Expand table

getFormat() Represents the formatting of a chart legend, which includes fill and
font formatting.

getHeight() Specifies the height, in points, of the legend on the chart. Value is
null if the legend is not visible.

getLeft() Specifies the left value, in points, of the legend on the chart. Value is
null if the legend is not visible.

getLegendEntries() Represents a collection of legendEntries in the legend.

getOverlay() Specifies if the chart legend should overlap with the main body of the
chart.

getPosition() Specifies the position of the legend on the chart. See


ExcelScript.ChartLegendPosition for details.

getShowShadow() Specifies if the legend has a shadow on the chart.

getTop() Specifies the top of a chart legend.

getVisible() Specifies if the chart legend is visible.

getWidth() Specifies the width, in points, of the legend on the chart. Value is null
if the legend is not visible.

setHeight(height) Specifies the height, in points, of the legend on the chart. Value is
null if the legend is not visible.

setLeft(left) Specifies the left value, in points, of the legend on the chart. Value is
null if the legend is not visible.

setOverlay(overlay) Specifies if the chart legend should overlap with the main body of the
chart.

setPosition(position) Specifies the position of the legend on the chart. See


ExcelScript.ChartLegendPosition for details.
setShowShadow(show Specifies if the legend has a shadow on the chart.
Shadow)

setTop(top) Specifies the top of a chart legend.

setVisible(visible) Specifies if the chart legend is visible.

setWidth(width) Specifies the width, in points, of the legend on the chart. Value is null
if the legend is not visible.

Method Details

getFormat()
Represents the formatting of a chart legend, which includes fill and font formatting.

TypeScript

getFormat(): ChartLegendFormat;

Returns
ExcelScript.ChartLegendFormat

getHeight()
Specifies the height, in points, of the legend on the chart. Value is null if the legend
is not visible.

TypeScript

getHeight(): number;

Returns
number

getLeft()
Specifies the left value, in points, of the legend on the chart. Value is null if the
legend is not visible.
TypeScript

getLeft(): number;

Returns
number

getLegendEntries()
Represents a collection of legendEntries in the legend.

TypeScript

getLegendEntries(): ChartLegendEntry[];

Returns
ExcelScript.ChartLegendEntry[]

getOverlay()
Specifies if the chart legend should overlap with the main body of the chart.

TypeScript

getOverlay(): boolean;

Returns
boolean

getPosition()
Specifies the position of the legend on the chart. See
ExcelScript.ChartLegendPosition for details.

TypeScript

getPosition(): ChartLegendPosition;
Returns
ExcelScript.ChartLegendPosition

getShowShadow()
Specifies if the legend has a shadow on the chart.

TypeScript

getShowShadow(): boolean;

Returns
boolean

getTop()
Specifies the top of a chart legend.

TypeScript

getTop(): number;

Returns
number

getVisible()
Specifies if the chart legend is visible.

TypeScript

getVisible(): boolean;

Returns
boolean

getWidth()
Specifies the width, in points, of the legend on the chart. Value is null if the legend
is not visible.

TypeScript

getWidth(): number;

Returns
number

setHeight(height)
Specifies the height, in points, of the legend on the chart. Value is null if the legend
is not visible.

TypeScript

setHeight(height: number): void;

Parameters
height number

Returns
void

setLeft(left)
Specifies the left value, in points, of the legend on the chart. Value is null if the
legend is not visible.

TypeScript

setLeft(left: number): void;

Parameters
left number
Returns
void

setOverlay(overlay)
Specifies if the chart legend should overlap with the main body of the chart.

TypeScript

setOverlay(overlay: boolean): void;

Parameters
overlay boolean

Returns
void

setPosition(position)
Specifies the position of the legend on the chart. See
ExcelScript.ChartLegendPosition for details.

TypeScript

setPosition(position: ChartLegendPosition): void;

Parameters
position ExcelScript.ChartLegendPosition

Returns
void

setShowShadow(showShadow)
Specifies if the legend has a shadow on the chart.

TypeScript
setShowShadow(showShadow: boolean): void;

Parameters
showShadow boolean

Returns
void

setTop(top)
Specifies the top of a chart legend.

TypeScript

setTop(top: number): void;

Parameters
top number

Returns
void

setVisible(visible)
Specifies if the chart legend is visible.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void
setWidth(width)
Specifies the width, in points, of the legend on the chart. Value is null if the legend
is not visible.

TypeScript

setWidth(width: number): void;

Parameters
width number

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartLegendEntry interface
Reference
Package: ExcelScript

Represents the legend entry in legendEntryCollection .

Methods
ノ Expand table

getHeight() Specifies the height of the legend entry on the chart legend.

getIndex() Specifies the index of the legend entry in the chart legend.

getLeft() Specifies the left value of a chart legend entry.

getTop() Specifies the top of a chart legend entry.

getVisible() Represents the visibility of a chart legend entry.

getWidth() Represents the width of the legend entry on the chart Legend.

setVisible(visible) Represents the visibility of a chart legend entry.

Method Details

getHeight()
Specifies the height of the legend entry on the chart legend.

TypeScript

getHeight(): number;

Returns
number

getIndex()
Specifies the index of the legend entry in the chart legend.
TypeScript

getIndex(): number;

Returns
number

getLeft()
Specifies the left value of a chart legend entry.

TypeScript

getLeft(): number;

Returns
number

getTop()
Specifies the top of a chart legend entry.

TypeScript

getTop(): number;

Returns
number

getVisible()
Represents the visibility of a chart legend entry.

TypeScript

getVisible(): boolean;
Returns
boolean

getWidth()
Represents the width of the legend entry on the chart Legend.

TypeScript

getWidth(): number;

Returns
number

setVisible(visible)
Represents the visibility of a chart legend entry.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartLegendFormat
interface
Reference
Package: ExcelScript

Encapsulates the format properties of a chart legend.

Methods
ノ Expand table

get Represents the border format, which includes color, linestyle, and weight.
Border()

getFill() Represents the fill format of an object, which includes background formatting
information.

getFont() Represents the font attributes such as font name, font size, and color of a chart
legend.

Method Details

getBorder()
Represents the border format, which includes color, linestyle, and weight.

TypeScript

getBorder(): ChartBorder;

Returns
ExcelScript.ChartBorder

getFill()
Represents the fill format of an object, which includes background formatting
information.
TypeScript

getFill(): ChartFill;

Returns
ExcelScript.ChartFill

getFont()
Represents the font attributes such as font name, font size, and color of a chart
legend.

TypeScript

getFont(): ChartFont;

Returns
ExcelScript.ChartFont

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartLineFormat interface
Reference
Package: ExcelScript

Encapsulates the formatting options for line elements.

Methods
ノ Expand table

clear() Clears the line format of a chart element.

getColor() HTML color code representing the color of lines in the chart.

getLineStyle() Represents the line style. See ExcelScript.ChartLineStyle for details.

getWeight() Represents weight of the line, in points.

setColor(color) HTML color code representing the color of lines in the chart.

setLineStyle(lineStyle) Represents the line style. See ExcelScript.ChartLineStyle for details.

setWeight(weight) Represents weight of the line, in points.

Method Details

clear()
Clears the line format of a chart element.

TypeScript

clear(): void;

Returns
void

getColor()
HTML color code representing the color of lines in the chart.
TypeScript

getColor(): string;

Returns
string

getLineStyle()
Represents the line style. See ExcelScript.ChartLineStyle for details.

TypeScript

getLineStyle(): ChartLineStyle;

Returns
ExcelScript.ChartLineStyle

getWeight()
Represents weight of the line, in points.

TypeScript

getWeight(): number;

Returns
number

setColor(color)
HTML color code representing the color of lines in the chart.

TypeScript

setColor(color: string): void;


Parameters
color string

Returns
void

setLineStyle(lineStyle)
Represents the line style. See ExcelScript.ChartLineStyle for details.

TypeScript

setLineStyle(lineStyle: ChartLineStyle): void;

Parameters
lineStyle ExcelScript.ChartLineStyle

Returns
void

setWeight(weight)
Represents weight of the line, in points.

TypeScript

setWeight(weight: number): void;

Parameters
weight number

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartMapOptions interface
Reference
Package: ExcelScript

Encapsulates the properties for a region map chart.

Methods
ノ Expand table

getLabelStrategy() Specifies the series map labels strategy of a region map


chart.

getLevel() Specifies the series mapping level of a region map chart.

getProjectionType() Specifies the series projection type of a region map chart.

setLabelStrategy(labelStrategy) Specifies the series map labels strategy of a region map


chart.

setLevel(level) Specifies the series mapping level of a region map chart.

setProjectionType(projection Specifies the series projection type of a region map chart.


Type)

Method Details

getLabelStrategy()
Specifies the series map labels strategy of a region map chart.

TypeScript

getLabelStrategy(): ChartMapLabelStrategy;

Returns
ExcelScript.ChartMapLabelStrategy

getLevel()
Specifies the series mapping level of a region map chart.

TypeScript

getLevel(): ChartMapAreaLevel;

Returns
ExcelScript.ChartMapAreaLevel

getProjectionType()
Specifies the series projection type of a region map chart.

TypeScript

getProjectionType(): ChartMapProjectionType;

Returns
ExcelScript.ChartMapProjectionType

setLabelStrategy(labelStrategy)
Specifies the series map labels strategy of a region map chart.

TypeScript

setLabelStrategy(labelStrategy: ChartMapLabelStrategy): void;

Parameters
labelStrategy ExcelScript.ChartMapLabelStrategy

Returns
void

setLevel(level)
Specifies the series mapping level of a region map chart.
TypeScript

setLevel(level: ChartMapAreaLevel): void;

Parameters
level ExcelScript.ChartMapAreaLevel

Returns
void

setProjectionType(projectionType)
Specifies the series projection type of a region map chart.

TypeScript

setProjectionType(projectionType: ChartMapProjectionType): void;

Parameters
projectionType ExcelScript.ChartMapProjectionType

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartPivotOptions interface
Reference
Package: ExcelScript

Encapsulates the options for the pivot chart.

Methods
ノ Expand table

getShowAxisField Specifies whether to display the axis field buttons on a PivotChart. The
Buttons() showAxisFieldButtons property corresponds to the "Show Axis Field
Buttons" command on the "Field Buttons" drop-down list of the
"Analyze" tab, which is available when a PivotChart is selected.

getShowLegendField Specifies whether to display the legend field buttons on a PivotChart.


Buttons()

getShowReportFilter Specifies whether to display the report filter field buttons on a


FieldButtons() PivotChart.

getShowValueField Specifies whether to display the show value field buttons on a


Buttons() PivotChart.

setShowAxisField Specifies whether to display the axis field buttons on a PivotChart. The
Buttons(showAxisField showAxisFieldButtons property corresponds to the "Show Axis Field
Buttons) Buttons" command on the "Field Buttons" drop-down list of the
"Analyze" tab, which is available when a PivotChart is selected.

setShowLegendField Specifies whether to display the legend field buttons on a PivotChart.


Buttons(showLegend
FieldButtons)

setShowReportFilter Specifies whether to display the report filter field buttons on a


FieldButtons(show PivotChart.
ReportFilterField
Buttons)

setShowValueField Specifies whether to display the show value field buttons on a


Buttons(showValue PivotChart.
FieldButtons)

Method Details
getShowAxisFieldButtons()
Specifies whether to display the axis field buttons on a PivotChart. The
showAxisFieldButtons property corresponds to the "Show Axis Field Buttons"

command on the "Field Buttons" drop-down list of the "Analyze" tab, which is
available when a PivotChart is selected.

TypeScript

getShowAxisFieldButtons(): boolean;

Returns
boolean

getShowLegendFieldButtons()
Specifies whether to display the legend field buttons on a PivotChart.

TypeScript

getShowLegendFieldButtons(): boolean;

Returns
boolean

getShowReportFilterFieldButtons()
Specifies whether to display the report filter field buttons on a PivotChart.

TypeScript

getShowReportFilterFieldButtons(): boolean;

Returns
boolean

getShowValueFieldButtons()
Specifies whether to display the show value field buttons on a PivotChart.

TypeScript

getShowValueFieldButtons(): boolean;

Returns
boolean

setShowAxisFieldButtons(showAxisFieldButtons)
Specifies whether to display the axis field buttons on a PivotChart. The
showAxisFieldButtons property corresponds to the "Show Axis Field Buttons"

command on the "Field Buttons" drop-down list of the "Analyze" tab, which is
available when a PivotChart is selected.

TypeScript

setShowAxisFieldButtons(showAxisFieldButtons: boolean): void;

Parameters
showAxisFieldButtons boolean

Returns
void

setShowLegendFieldButtons(showLegendFieldButtons)
Specifies whether to display the legend field buttons on a PivotChart.

TypeScript

setShowLegendFieldButtons(showLegendFieldButtons: boolean): void;

Parameters
showLegendFieldButtons boolean
Returns
void

setShowReportFilterFieldButtons(showReportFilterField
Buttons)
Specifies whether to display the report filter field buttons on a PivotChart.

TypeScript

setShowReportFilterFieldButtons(
showReportFilterFieldButtons: boolean
): void;

Parameters
showReportFilterFieldButtons boolean

Returns
void

setShowValueFieldButtons(showValueFieldButtons)
Specifies whether to display the show value field buttons on a PivotChart.

TypeScript

setShowValueFieldButtons(showValueFieldButtons: boolean): void;

Parameters
showValueFieldButtons boolean

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartPlotArea interface
Reference
Package: ExcelScript

This object represents the attributes for a chart plot area.

Methods
ノ Expand table

getFormat() Specifies the formatting of a chart plot area.

getHeight() Specifies the height value of a plot area.

getInsideHeight() Specifies the inside height value of a plot area.

getInsideLeft() Specifies the inside left value of a plot area.

getInsideTop() Specifies the inside top value of a plot area.

getInsideWidth() Specifies the inside width value of a plot area.

getLeft() Specifies the left value of a plot area.

getPosition() Specifies the position of a plot area.

getTop() Specifies the top value of a plot area.

getWidth() Specifies the width value of a plot area.

setHeight(height) Specifies the height value of a plot area.

setInsideHeight(insideHeight) Specifies the inside height value of a plot area.

setInsideLeft(insideLeft) Specifies the inside left value of a plot area.

setInsideTop(insideTop) Specifies the inside top value of a plot area.

setInsideWidth(insideWidth) Specifies the inside width value of a plot area.

setLeft(left) Specifies the left value of a plot area.

setPosition(position) Specifies the position of a plot area.

setTop(top) Specifies the top value of a plot area.

setWidth(width) Specifies the width value of a plot area.


Method Details

getFormat()
Specifies the formatting of a chart plot area.

TypeScript

getFormat(): ChartPlotAreaFormat;

Returns
ExcelScript.ChartPlotAreaFormat

getHeight()
Specifies the height value of a plot area.

TypeScript

getHeight(): number;

Returns
number

getInsideHeight()
Specifies the inside height value of a plot area.

TypeScript

getInsideHeight(): number;

Returns
number

getInsideLeft()
Specifies the inside left value of a plot area.
TypeScript

getInsideLeft(): number;

Returns
number

getInsideTop()
Specifies the inside top value of a plot area.

TypeScript

getInsideTop(): number;

Returns
number

getInsideWidth()
Specifies the inside width value of a plot area.

TypeScript

getInsideWidth(): number;

Returns
number

getLeft()
Specifies the left value of a plot area.

TypeScript

getLeft(): number;
Returns
number

getPosition()
Specifies the position of a plot area.

TypeScript

getPosition(): ChartPlotAreaPosition;

Returns
ExcelScript.ChartPlotAreaPosition

getTop()
Specifies the top value of a plot area.

TypeScript

getTop(): number;

Returns
number

getWidth()
Specifies the width value of a plot area.

TypeScript

getWidth(): number;

Returns
number

setHeight(height)
Specifies the height value of a plot area.

TypeScript

setHeight(height: number): void;

Parameters
height number

Returns
void

setInsideHeight(insideHeight)
Specifies the inside height value of a plot area.

TypeScript

setInsideHeight(insideHeight: number): void;

Parameters
insideHeight number

Returns
void

setInsideLeft(insideLeft)
Specifies the inside left value of a plot area.

TypeScript

setInsideLeft(insideLeft: number): void;

Parameters
insideLeft number
Returns
void

setInsideTop(insideTop)
Specifies the inside top value of a plot area.

TypeScript

setInsideTop(insideTop: number): void;

Parameters
insideTop number

Returns
void

setInsideWidth(insideWidth)
Specifies the inside width value of a plot area.

TypeScript

setInsideWidth(insideWidth: number): void;

Parameters
insideWidth number

Returns
void

setLeft(left)
Specifies the left value of a plot area.

TypeScript
setLeft(left: number): void;

Parameters
left number

Returns
void

setPosition(position)
Specifies the position of a plot area.

TypeScript

setPosition(position: ChartPlotAreaPosition): void;

Parameters
position ExcelScript.ChartPlotAreaPosition

Returns
void

setTop(top)
Specifies the top value of a plot area.

TypeScript

setTop(top: number): void;

Parameters
top number

Returns
void
setWidth(width)
Specifies the width value of a plot area.

TypeScript

setWidth(width: number): void;

Parameters
width number

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartPlotAreaFormat
interface
Reference
Package: ExcelScript

Represents the format properties for a chart plot area.

Methods
ノ Expand table

get Specifies the border attributes of a chart plot area.


Border()

getFill() Specifies the fill format of an object, which includes background formatting
information.

Method Details

getBorder()
Specifies the border attributes of a chart plot area.

TypeScript

getBorder(): ChartBorder;

Returns
ExcelScript.ChartBorder

getFill()
Specifies the fill format of an object, which includes background formatting
information.

TypeScript
getFill(): ChartFill;

Returns
ExcelScript.ChartFill

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartPoint interface
Reference
Package: ExcelScript

Represents a point of a series in a chart.

Methods
ノ Expand table

getDataLabel() Returns the data label of a chart point.

getFormat() Encapsulates the format properties chart point.

getHasDataLabel() Represents whether a data point has a data label. Not applicable for
surface charts.

getMarkerBackground HTML color code representation of the marker background color of a


Color() data point (e.g., #FF0000 represents Red).

getMarkerForeground HTML color code representation of the marker foreground color of a


Color() data point (e.g., #FF0000 represents Red).

getMarkerSize() Represents marker size of a data point. The supported size range is 2
to 72. This method returns an InvalidArgument error if it's set with a
size outside of the supported range.

getMarkerStyle() Represents marker style of a chart data point. See


ExcelScript.ChartMarkerStyle for details.

getValue() Returns the value of a chart point.

setHasDataLabel(has Represents whether a data point has a data label. Not applicable for
DataLabel) surface charts.

setMarkerBackground HTML color code representation of the marker background color of a


Color(marker data point (e.g., #FF0000 represents Red).
BackgroundColor)

setMarkerForeground HTML color code representation of the marker foreground color of a


Color(marker data point (e.g., #FF0000 represents Red).
ForegroundColor)

setMarkerSize(marker Represents marker size of a data point. The supported size range is 2
Size) to 72. This method returns an InvalidArgument error if it's set with a
size outside of the supported range.
setMarkerStyle(marker Represents marker style of a chart data point. See
Style) ExcelScript.ChartMarkerStyle for details.

Method Details

getDataLabel()
Returns the data label of a chart point.

TypeScript

getDataLabel(): ChartDataLabel;

Returns
ExcelScript.ChartDataLabel

getFormat()
Encapsulates the format properties chart point.

TypeScript

getFormat(): ChartPointFormat;

Returns
ExcelScript.ChartPointFormat

getHasDataLabel()
Represents whether a data point has a data label. Not applicable for surface charts.

TypeScript

getHasDataLabel(): boolean;

Returns
boolean
getMarkerBackgroundColor()
HTML color code representation of the marker background color of a data point
(e.g., #FF0000 represents Red).

TypeScript

getMarkerBackgroundColor(): string;

Returns
string

getMarkerForegroundColor()
HTML color code representation of the marker foreground color of a data point (e.g.,
#FF0000 represents Red).

TypeScript

getMarkerForegroundColor(): string;

Returns
string

getMarkerSize()
Represents marker size of a data point. The supported size range is 2 to 72. This
method returns an InvalidArgument error if it's set with a size outside of the
supported range.

TypeScript

getMarkerSize(): number;

Returns
number

getMarkerStyle()
Represents marker style of a chart data point. See ExcelScript.ChartMarkerStyle for
details.

TypeScript

getMarkerStyle(): ChartMarkerStyle;

Returns
ExcelScript.ChartMarkerStyle

getValue()
Returns the value of a chart point.

TypeScript

getValue(): number;

Returns
number

setHasDataLabel(hasDataLabel)
Represents whether a data point has a data label. Not applicable for surface charts.

TypeScript

setHasDataLabel(hasDataLabel: boolean): void;

Parameters
hasDataLabel boolean

Returns
void

setMarkerBackgroundColor(markerBackgroundColor)
HTML color code representation of the marker background color of a data point
(e.g., #FF0000 represents Red).

TypeScript

setMarkerBackgroundColor(markerBackgroundColor: string): void;

Parameters
markerBackgroundColor string

Returns
void

setMarkerForegroundColor(markerForegroundColor)
HTML color code representation of the marker foreground color of a data point (e.g.,
#FF0000 represents Red).

TypeScript

setMarkerForegroundColor(markerForegroundColor: string): void;

Parameters
markerForegroundColor string

Returns
void

setMarkerSize(markerSize)
Represents marker size of a data point. The supported size range is 2 to 72. This
method returns an InvalidArgument error if it's set with a size outside of the
supported range.

TypeScript

setMarkerSize(markerSize: number): void;


Parameters
markerSize number

Returns
void

setMarkerStyle(markerStyle)
Represents marker style of a chart data point. See ExcelScript.ChartMarkerStyle for
details.

TypeScript

setMarkerStyle(markerStyle: ChartMarkerStyle): void;

Parameters
markerStyle ExcelScript.ChartMarkerStyle

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartPointFormat interface
Reference
Package: ExcelScript

Represents the formatting object for chart points.

Methods
ノ Expand table

get Represents the border format of a chart data point, which includes color, style, and
Border() weight information.

getFill() Represents the fill format of a chart, which includes background formatting
information.

Method Details

getBorder()
Represents the border format of a chart data point, which includes color, style, and
weight information.

TypeScript

getBorder(): ChartBorder;

Returns
ExcelScript.ChartBorder

getFill()
Represents the fill format of a chart, which includes background formatting
information.

TypeScript

getFill(): ChartFill;
Returns
ExcelScript.ChartFill

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartSeries interface
Reference
Package: ExcelScript

Represents a series in a chart.

Remarks

Examples

TypeScript

/**
* This sample produces a line chart with two series.
* The chart assumes data in A1:E5 that looks like this:
* Product Qtr1 Qtr2 Qtr3 Qtr4
* Frames 5000 7000 6544 4377
* Saddles 400 323 276 651
*/
function main(workbook: ExcelScript.Workbook) {
// Establish the ranges to use.
const sheet = workbook.getActiveWorksheet();
const headerRange = sheet.getRange("A1:E1");
const firstSeriesRange = sheet.getRange("A2:E2");
const secondSeriesRange = sheet.getRange("A3:E3");

// Create the chart.


const lineChart = sheet.addChart(ExcelScript.ChartType.line, headerRange);

// Add the first chart series.


const firstSeries = lineChart.addChartSeries();
firstSeries.setXAxisValues(headerRange);
firstSeries.setValues(firstSeriesRange);

// Add the second chart series.


const secondSeries = lineChart.addChartSeries();
secondSeries.setXAxisValues(headerRange);
secondSeries.setValues(secondSeriesRange);
}

Methods
ノ Expand table
addChartTrendline(type) Adds a new trendline to trendline collection.

delete() Deletes the chart series.

getAxisGroup() Specifies the group for the specified series.

getBinOptions() Encapsulates the bin options for histogram charts and pareto
charts.

getBoxwhiskerOptions() Encapsulates the options for the box and whisker charts.

getBubbleScale() This can be an integer value from 0 (zero) to 300, representing the
percentage of the default size. This property only applies to bubble
charts.

getChartTrendline(index) Gets a trendline object by index, which is the insertion order in the
items array.

getChartType() Represents the chart type of a series. See ExcelScript.ChartType


for details.

getDataLabels() Represents a collection of all data labels in the series.

getDimensionDataSource Gets the string representation of the data source of the chart series.
String(dimension) The string representation could be information such as a cell
address.

getDimensionDataSource Gets the data source type of the chart series.


Type(dimension)

getDimension Gets the values from a single dimension of the chart series. These
Values(dimension) could be either category values or data values, depending on the
dimension specified and how the data is mapped for the chart
series.

getDoughnutHoleSize() Represents the doughnut hole size of a chart series. Only valid on
doughnut and doughnut exploded charts. Throws an
InvalidArgument error on invalid charts.

getExplosion() Specifies the explosion value for a pie-chart or doughnut-chart


slice. Returns 0 (zero) if there's no explosion (the tip of the slice is in
the center of the pie).

getFiltered() Specifies if the series is filtered. Not applicable for surface charts.

getFirstSliceAngle() Specifies the angle of the first pie-chart or doughnut-chart slice, in


degrees (clockwise from vertical). Applies only to pie, 3-D pie, and
doughnut charts. Can be a value from 0 through 360.

getFormat() Represents the formatting of a chart series, which includes fill and
line formatting.
getGapWidth() Represents the gap width of a chart series. Only valid on bar and
column charts, as well as specific classes of line and pie charts.
Throws an invalid argument exception on invalid charts.

getGradientMaximum Specifies the color for maximum value of a region map chart series.
Color()

getGradientMaximum Specifies the type for maximum value of a region map chart series.
Type()

getGradientMaximum Specifies the maximum value of a region map chart series.


Value()

getGradientMidpoint Specifies the color for the midpoint value of a region map chart
Color() series.

getGradientMidpointType() Specifies the type for the midpoint value of a region map chart
series.

getGradientMidpoint Specifies the midpoint value of a region map chart series.


Value()

getGradientMinimum Specifies the color for the minimum value of a region map chart
Color() series.

getGradientMinimumType() Specifies the type for the minimum value of a region map chart
series.

getGradientMinimum Specifies the minimum value of a region map chart series.


Value()

getGradientStyle() Specifies the series gradient style of a region map chart.

getHasDataLabels() Specifies if the series has data labels.

getInvertColor() Specifies the fill color for negative data points in a series.

getInvertIfNegative() True if Excel inverts the pattern in the item when it corresponds to a
negative number.

getMapOptions() Encapsulates the options for a region map chart.

getMarkerBackground Specifies the marker background color of a chart series.


Color()

getMarkerForeground Specifies the marker foreground color of a chart series.


Color()

getMarkerSize() Specifies the marker size of a chart series. The supported size range
is 2 to 72. This method returns an InvalidArgument error if it's set
with a size outside of the supported range.
getMarkerStyle() Specifies the marker style of a chart series. See
ExcelScript.ChartMarkerStyle for details.

getName() Specifies the name of a series in a chart. The name's length should
not be greater than 255 characters.

getOverlap() Specifies how bars and columns are positioned. Can be a value
between -100 and 100. Applies only to 2-D bar and 2-D column
charts.

getParentLabelStrategy() Specifies the series parent label strategy area for a treemap chart.

getPlotOrder() Specifies the plot order of a chart series within the chart group.

getPoints() Returns a collection of all points in the series.

getSecondPlotSize() Specifies the size of the secondary section of either a pie-of-pie


chart or a bar-of-pie chart, as a percentage of the size of the
primary pie. Can be a value from 5 to 200.

getShowConnectorLines() Specifies whether connector lines are shown in waterfall charts.

getShowLeaderLines() Specifies whether leader lines are displayed for each data label in
the series.

getShowShadow() Specifies if the series has a shadow.

getSmooth() Specifies if the series is smooth. Only applicable to line and scatter
charts.

getSplitType() Specifies the way the two sections of either a pie-of-pie chart or a
bar-of-pie chart are split.

getSplitValue() Specifies the threshold value that separates two sections of either a
pie-of-pie chart or a bar-of-pie chart.

getTrendlines() The collection of trendlines in the series.

getVaryByCategories() True if Excel assigns a different color or pattern to each data


marker. The chart must contain only one series.

getXErrorBars() Represents the error bar object of a chart series.

getYErrorBars() Represents the error bar object of a chart series.

setAxisGroup(axisGroup) Specifies the group for the specified series.

setBubbleScale(bubble This can be an integer value from 0 (zero) to 300, representing the
Scale) percentage of the default size. This property only applies to bubble
charts.

setBubbleSizes(sourceData) Sets the bubble sizes for a chart series. Only works for bubble
charts.

setChartType(chartType) Represents the chart type of a series. See ExcelScript.ChartType


for details.

setDoughnutHole Represents the doughnut hole size of a chart series. Only valid on
Size(doughnutHoleSize) doughnut and doughnut exploded charts. Throws an
InvalidArgument error on invalid charts.

setExplosion(explosion) Specifies the explosion value for a pie-chart or doughnut-chart


slice. Returns 0 (zero) if there's no explosion (the tip of the slice is in
the center of the pie).

setFiltered(filtered) Specifies if the series is filtered. Not applicable for surface charts.

setFirstSliceAngle(firstSlice Specifies the angle of the first pie-chart or doughnut-chart slice, in


Angle) degrees (clockwise from vertical). Applies only to pie, 3-D pie, and
doughnut charts. Can be a value from 0 through 360.

setGapWidth(gapWidth) Represents the gap width of a chart series. Only valid on bar and
column charts, as well as specific classes of line and pie charts.
Throws an invalid argument exception on invalid charts.

setGradientMaximum Specifies the color for maximum value of a region map chart series.
Color(gradientMaximum
Color)

setGradientMaximum Specifies the type for maximum value of a region map chart series.
Type(gradientMaximum
Type)

setGradientMaximum Specifies the maximum value of a region map chart series.


Value(gradientMaximum
Value)

setGradientMidpoint Specifies the color for the midpoint value of a region map chart
Color(gradientMidpoint series.
Color)

setGradientMidpoint Specifies the type for the midpoint value of a region map chart
Type(gradientMidpoint series.
Type)

setGradientMidpoint Specifies the midpoint value of a region map chart series.


Value(gradientMidpoint
Value)

setGradientMinimum Specifies the color for the minimum value of a region map chart
Color(gradientMinimum series.
Color)
setGradientMinimum Specifies the type for the minimum value of a region map chart
Type(gradientMinimum series.
Type)

setGradientMinimum Specifies the minimum value of a region map chart series.


Value(gradientMinimum
Value)

setGradientStyle(gradient Specifies the series gradient style of a region map chart.


Style)

setHasDataLabels(hasData Specifies if the series has data labels.


Labels)

setInvertColor(invertColor) Specifies the fill color for negative data points in a series.

setInvertIfNegative(invert True if Excel inverts the pattern in the item when it corresponds to a
IfNegative) negative number.

setMarkerBackground Specifies the marker background color of a chart series.


Color(markerBackground
Color)

setMarkerForeground Specifies the marker foreground color of a chart series.


Color(markerForeground
Color)

setMarkerSize(markerSize) Specifies the marker size of a chart series. The supported size range
is 2 to 72. This method returns an InvalidArgument error if it's set
with a size outside of the supported range.

setMarkerStyle(marker Specifies the marker style of a chart series. See


Style) ExcelScript.ChartMarkerStyle for details.

setName(name) Specifies the name of a series in a chart. The name's length should
not be greater than 255 characters.

setOverlap(overlap) Specifies how bars and columns are positioned. Can be a value
between -100 and 100. Applies only to 2-D bar and 2-D column
charts.

setParentLabel Specifies the series parent label strategy area for a treemap chart.
Strategy(parentLabel
Strategy)

setPlotOrder(plotOrder) Specifies the plot order of a chart series within the chart group.

setSecondPlotSize(second Specifies the size of the secondary section of either a pie-of-pie


PlotSize) chart or a bar-of-pie chart, as a percentage of the size of the
primary pie. Can be a value from 5 to 200.
setShowConnector Specifies whether connector lines are shown in waterfall charts.
Lines(showConnectorLines)

setShowLeaderLines(show Specifies whether leader lines are displayed for each data label in
LeaderLines) the series.

setShowShadow(show Specifies if the series has a shadow.


Shadow)

setSmooth(smooth) Specifies if the series is smooth. Only applicable to line and scatter
charts.

setSplitType(splitType) Specifies the way the two sections of either a pie-of-pie chart or a
bar-of-pie chart are split.

setSplitValue(splitValue) Specifies the threshold value that separates two sections of either a
pie-of-pie chart or a bar-of-pie chart.

setValues(sourceData) Sets the values for a chart series. For scatter charts, it refers to y-
axis values.

setVaryByCategories(vary True if Excel assigns a different color or pattern to each data


ByCategories) marker. The chart must contain only one series.

setXAxisValues(sourceData) Sets the values of the x-axis for a chart series.

Method Details

addChartTrendline(type)
Adds a new trendline to trendline collection.

TypeScript

addChartTrendline(type?: ChartTrendlineType): ChartTrendline;

Parameters
type ExcelScript.ChartTrendlineType
Specifies the trendline type. The default value is "Linear". See
ExcelScript.ChartTrendline for details.

Returns
ExcelScript.ChartTrendline
delete()
Deletes the chart series.

TypeScript

delete(): void;

Returns
void

getAxisGroup()
Specifies the group for the specified series.

TypeScript

getAxisGroup(): ChartAxisGroup;

Returns
ExcelScript.ChartAxisGroup

getBinOptions()
Encapsulates the bin options for histogram charts and pareto charts.

TypeScript

getBinOptions(): ChartBinOptions;

Returns
ExcelScript.ChartBinOptions

getBoxwhiskerOptions()
Encapsulates the options for the box and whisker charts.

TypeScript
getBoxwhiskerOptions(): ChartBoxwhiskerOptions;

Returns
ExcelScript.ChartBoxwhiskerOptions

getBubbleScale()
This can be an integer value from 0 (zero) to 300, representing the percentage of the
default size. This property only applies to bubble charts.

TypeScript

getBubbleScale(): number;

Returns
number

getChartTrendline(index)
Gets a trendline object by index, which is the insertion order in the items array.

TypeScript

getChartTrendline(index: number): ChartTrendline;

Parameters
index number
Represents the insertion order in the items array.

Returns
ExcelScript.ChartTrendline

getChartType()
Represents the chart type of a series. See ExcelScript.ChartType for details.
TypeScript

getChartType(): ChartType;

Returns
ExcelScript.ChartType

getDataLabels()
Represents a collection of all data labels in the series.

TypeScript

getDataLabels(): ChartDataLabels;

Returns
ExcelScript.ChartDataLabels

getDimensionDataSourceString(dimension)
Gets the string representation of the data source of the chart series. The string
representation could be information such as a cell address.

TypeScript

getDimensionDataSourceString(dimension: ChartSeriesDimension): string;

Parameters
dimension ExcelScript.ChartSeriesDimension
The dimension of the axis where the data is from.

Returns
string

getDimensionDataSourceType(dimension)
Gets the data source type of the chart series.
TypeScript

getDimensionDataSourceType(
dimension: ChartSeriesDimension
): ChartDataSourceType;

Parameters
dimension ExcelScript.ChartSeriesDimension
The dimension of the axis where the data is from.

Returns
ExcelScript.ChartDataSourceType

getDimensionValues(dimension)
Gets the values from a single dimension of the chart series. These could be either
category values or data values, depending on the dimension specified and how the
data is mapped for the chart series.

TypeScript

getDimensionValues(dimension: ChartSeriesDimension): string[];

Parameters
dimension ExcelScript.ChartSeriesDimension
The dimension of the axis where the data is from.

Returns
string[]

getDoughnutHoleSize()
Represents the doughnut hole size of a chart series. Only valid on doughnut and
doughnut exploded charts. Throws an InvalidArgument error on invalid charts.

TypeScript
getDoughnutHoleSize(): number;

Returns
number

getExplosion()
Specifies the explosion value for a pie-chart or doughnut-chart slice. Returns 0 (zero)
if there's no explosion (the tip of the slice is in the center of the pie).

TypeScript

getExplosion(): number;

Returns
number

getFiltered()
Specifies if the series is filtered. Not applicable for surface charts.

TypeScript

getFiltered(): boolean;

Returns
boolean

getFirstSliceAngle()
Specifies the angle of the first pie-chart or doughnut-chart slice, in degrees
(clockwise from vertical). Applies only to pie, 3-D pie, and doughnut charts. Can be a
value from 0 through 360.

TypeScript

getFirstSliceAngle(): number;
Returns
number

getFormat()
Represents the formatting of a chart series, which includes fill and line formatting.

TypeScript

getFormat(): ChartSeriesFormat;

Returns
ExcelScript.ChartSeriesFormat

getGapWidth()
Represents the gap width of a chart series. Only valid on bar and column charts, as
well as specific classes of line and pie charts. Throws an invalid argument exception
on invalid charts.

TypeScript

getGapWidth(): number;

Returns
number

getGradientMaximumColor()
Specifies the color for maximum value of a region map chart series.

TypeScript

getGradientMaximumColor(): string;

Returns
string
getGradientMaximumType()
Specifies the type for maximum value of a region map chart series.

TypeScript

getGradientMaximumType(): ChartGradientStyleType;

Returns
ExcelScript.ChartGradientStyleType

getGradientMaximumValue()
Specifies the maximum value of a region map chart series.

TypeScript

getGradientMaximumValue(): number;

Returns
number

getGradientMidpointColor()
Specifies the color for the midpoint value of a region map chart series.

TypeScript

getGradientMidpointColor(): string;

Returns
string

getGradientMidpointType()
Specifies the type for the midpoint value of a region map chart series.

TypeScript
getGradientMidpointType(): ChartGradientStyleType;

Returns
ExcelScript.ChartGradientStyleType

getGradientMidpointValue()
Specifies the midpoint value of a region map chart series.

TypeScript

getGradientMidpointValue(): number;

Returns
number

getGradientMinimumColor()
Specifies the color for the minimum value of a region map chart series.

TypeScript

getGradientMinimumColor(): string;

Returns
string

getGradientMinimumType()
Specifies the type for the minimum value of a region map chart series.

TypeScript

getGradientMinimumType(): ChartGradientStyleType;

Returns
ExcelScript.ChartGradientStyleType

getGradientMinimumValue()
Specifies the minimum value of a region map chart series.

TypeScript

getGradientMinimumValue(): number;

Returns
number

getGradientStyle()
Specifies the series gradient style of a region map chart.

TypeScript

getGradientStyle(): ChartGradientStyle;

Returns
ExcelScript.ChartGradientStyle

getHasDataLabels()
Specifies if the series has data labels.

TypeScript

getHasDataLabels(): boolean;

Returns
boolean

getInvertColor()
Specifies the fill color for negative data points in a series.
TypeScript

getInvertColor(): string;

Returns
string

getInvertIfNegative()
True if Excel inverts the pattern in the item when it corresponds to a negative
number.

TypeScript

getInvertIfNegative(): boolean;

Returns
boolean

getMapOptions()
Encapsulates the options for a region map chart.

TypeScript

getMapOptions(): ChartMapOptions;

Returns
ExcelScript.ChartMapOptions

getMarkerBackgroundColor()
Specifies the marker background color of a chart series.

TypeScript

getMarkerBackgroundColor(): string;
Returns
string

getMarkerForegroundColor()
Specifies the marker foreground color of a chart series.

TypeScript

getMarkerForegroundColor(): string;

Returns
string

getMarkerSize()
Specifies the marker size of a chart series. The supported size range is 2 to 72. This
method returns an InvalidArgument error if it's set with a size outside of the
supported range.

TypeScript

getMarkerSize(): number;

Returns
number

getMarkerStyle()
Specifies the marker style of a chart series. See ExcelScript.ChartMarkerStyle for
details.

TypeScript

getMarkerStyle(): ChartMarkerStyle;

Returns
ExcelScript.ChartMarkerStyle
getName()
Specifies the name of a series in a chart. The name's length should not be greater
than 255 characters.

TypeScript

getName(): string;

Returns
string

Examples

TypeScript

/**
* This sample logs the names of each of the chart series in a chart
named "ColumnClusteredChart".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get an existing chart named "ColumnClusteredChart".


let chart = selectedSheet.getChart("ColumnClusteredChart");

// Log the name of each chart series in the chart.


let seriesList = chart.getSeries();
seriesList.forEach((series) => {
console.log(series.getName());
});
}

getOverlap()
Specifies how bars and columns are positioned. Can be a value between -100 and
100. Applies only to 2-D bar and 2-D column charts.

TypeScript

getOverlap(): number;
Returns
number

getParentLabelStrategy()
Specifies the series parent label strategy area for a treemap chart.

TypeScript

getParentLabelStrategy(): ChartParentLabelStrategy;

Returns
ExcelScript.ChartParentLabelStrategy

getPlotOrder()
Specifies the plot order of a chart series within the chart group.

TypeScript

getPlotOrder(): number;

Returns
number

getPoints()
Returns a collection of all points in the series.

TypeScript

getPoints(): ChartPoint[];

Returns
ExcelScript.ChartPoint[]

getSecondPlotSize()
Specifies the size of the secondary section of either a pie-of-pie chart or a bar-of-pie
chart, as a percentage of the size of the primary pie. Can be a value from 5 to 200.

TypeScript

getSecondPlotSize(): number;

Returns
number

getShowConnectorLines()
Specifies whether connector lines are shown in waterfall charts.

TypeScript

getShowConnectorLines(): boolean;

Returns
boolean

getShowLeaderLines()
Specifies whether leader lines are displayed for each data label in the series.

TypeScript

getShowLeaderLines(): boolean;

Returns
boolean

getShowShadow()
Specifies if the series has a shadow.

TypeScript
getShowShadow(): boolean;

Returns
boolean

getSmooth()
Specifies if the series is smooth. Only applicable to line and scatter charts.

TypeScript

getSmooth(): boolean;

Returns
boolean

getSplitType()
Specifies the way the two sections of either a pie-of-pie chart or a bar-of-pie chart
are split.

TypeScript

getSplitType(): ChartSplitType;

Returns
ExcelScript.ChartSplitType

getSplitValue()
Specifies the threshold value that separates two sections of either a pie-of-pie chart
or a bar-of-pie chart.

TypeScript

getSplitValue(): number;
Returns
number

getTrendlines()
The collection of trendlines in the series.

TypeScript

getTrendlines(): ChartTrendline[];

Returns
ExcelScript.ChartTrendline[]

getVaryByCategories()
True if Excel assigns a different color or pattern to each data marker. The chart must
contain only one series.

TypeScript

getVaryByCategories(): boolean;

Returns
boolean

getXErrorBars()
Represents the error bar object of a chart series.

TypeScript

getXErrorBars(): ChartErrorBars;

Returns
ExcelScript.ChartErrorBars
getYErrorBars()
Represents the error bar object of a chart series.

TypeScript

getYErrorBars(): ChartErrorBars;

Returns
ExcelScript.ChartErrorBars

Examples

TypeScript

/**
* This script adds error bars for the standard error of each chart
series point.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range for the chart.
const worksheet = workbook.getWorksheet("Sample");
const dataRange = worksheet.getRange("A1:B15");

// Create a line chart.


const chart = worksheet.addChart(ExcelScript.ChartType.line,
dataRange);

// For each series, add error bars for the standard error on each point
const allSeries = chart.getSeries();
allSeries.forEach((series) => {

series.getYErrorBars().setType(ExcelScript.ChartErrorBarsType.stError);
series.getYErrorBars().setVisible(true);
});
}

setAxisGroup(axisGroup)
Specifies the group for the specified series.

TypeScript

setAxisGroup(axisGroup: ChartAxisGroup): void;


Parameters
axisGroup ExcelScript.ChartAxisGroup

Returns
void

setBubbleScale(bubbleScale)
This can be an integer value from 0 (zero) to 300, representing the percentage of the
default size. This property only applies to bubble charts.

TypeScript

setBubbleScale(bubbleScale: number): void;

Parameters
bubbleScale number

Returns
void

setBubbleSizes(sourceData)
Sets the bubble sizes for a chart series. Only works for bubble charts.

TypeScript

setBubbleSizes(sourceData: Range): void;

Parameters
sourceData ExcelScript.Range
The Range object corresponding to the source data.

Returns
void
setChartType(chartType)
Represents the chart type of a series. See ExcelScript.ChartType for details.

TypeScript

setChartType(chartType: ChartType): void;

Parameters
chartType ExcelScript.ChartType

Returns
void

setDoughnutHoleSize(doughnutHoleSize)
Represents the doughnut hole size of a chart series. Only valid on doughnut and
doughnut exploded charts. Throws an InvalidArgument error on invalid charts.

TypeScript

setDoughnutHoleSize(doughnutHoleSize: number): void;

Parameters
doughnutHoleSize number

Returns
void

setExplosion(explosion)
Specifies the explosion value for a pie-chart or doughnut-chart slice. Returns 0 (zero)
if there's no explosion (the tip of the slice is in the center of the pie).

TypeScript

setExplosion(explosion: number): void;


Parameters
explosion number

Returns
void

setFiltered(filtered)
Specifies if the series is filtered. Not applicable for surface charts.

TypeScript

setFiltered(filtered: boolean): void;

Parameters
filtered boolean

Returns
void

setFirstSliceAngle(firstSliceAngle)
Specifies the angle of the first pie-chart or doughnut-chart slice, in degrees
(clockwise from vertical). Applies only to pie, 3-D pie, and doughnut charts. Can be a
value from 0 through 360.

TypeScript

setFirstSliceAngle(firstSliceAngle: number): void;

Parameters
firstSliceAngle number

Returns
void
setGapWidth(gapWidth)
Represents the gap width of a chart series. Only valid on bar and column charts, as
well as specific classes of line and pie charts. Throws an invalid argument exception
on invalid charts.

TypeScript

setGapWidth(gapWidth: number): void;

Parameters
gapWidth number

Returns
void

setGradientMaximumColor(gradientMaximumColor)
Specifies the color for maximum value of a region map chart series.

TypeScript

setGradientMaximumColor(gradientMaximumColor: string): void;

Parameters
gradientMaximumColor string

Returns
void

setGradientMaximumType(gradientMaximumType)
Specifies the type for maximum value of a region map chart series.

TypeScript

setGradientMaximumType(
gradientMaximumType: ChartGradientStyleType
): void;

Parameters
gradientMaximumType ExcelScript.ChartGradientStyleType

Returns
void

setGradientMaximumValue(gradientMaximumValue)
Specifies the maximum value of a region map chart series.

TypeScript

setGradientMaximumValue(gradientMaximumValue: number): void;

Parameters
gradientMaximumValue number

Returns
void

setGradientMidpointColor(gradientMidpointColor)
Specifies the color for the midpoint value of a region map chart series.

TypeScript

setGradientMidpointColor(gradientMidpointColor: string): void;

Parameters
gradientMidpointColor string

Returns
void
setGradientMidpointType(gradientMidpointType)
Specifies the type for the midpoint value of a region map chart series.

TypeScript

setGradientMidpointType(
gradientMidpointType: ChartGradientStyleType
): void;

Parameters
gradientMidpointType ExcelScript.ChartGradientStyleType

Returns
void

setGradientMidpointValue(gradientMidpointValue)
Specifies the midpoint value of a region map chart series.

TypeScript

setGradientMidpointValue(gradientMidpointValue: number): void;

Parameters
gradientMidpointValue number

Returns
void

setGradientMinimumColor(gradientMinimumColor)
Specifies the color for the minimum value of a region map chart series.

TypeScript

setGradientMinimumColor(gradientMinimumColor: string): void;


Parameters
gradientMinimumColor string

Returns
void

setGradientMinimumType(gradientMinimumType)
Specifies the type for the minimum value of a region map chart series.

TypeScript

setGradientMinimumType(
gradientMinimumType: ChartGradientStyleType
): void;

Parameters
gradientMinimumType ExcelScript.ChartGradientStyleType

Returns
void

setGradientMinimumValue(gradientMinimumValue)
Specifies the minimum value of a region map chart series.

TypeScript

setGradientMinimumValue(gradientMinimumValue: number): void;

Parameters
gradientMinimumValue number

Returns
void
setGradientStyle(gradientStyle)
Specifies the series gradient style of a region map chart.

TypeScript

setGradientStyle(gradientStyle: ChartGradientStyle): void;

Parameters
gradientStyle ExcelScript.ChartGradientStyle

Returns
void

setHasDataLabels(hasDataLabels)
Specifies if the series has data labels.

TypeScript

setHasDataLabels(hasDataLabels: boolean): void;

Parameters
hasDataLabels boolean

Returns
void

setInvertColor(invertColor)
Specifies the fill color for negative data points in a series.

TypeScript

setInvertColor(invertColor: string): void;

Parameters
invertColor string

Returns
void

setInvertIfNegative(invertIfNegative)
True if Excel inverts the pattern in the item when it corresponds to a negative
number.

TypeScript

setInvertIfNegative(invertIfNegative: boolean): void;

Parameters
invertIfNegative boolean

Returns
void

setMarkerBackgroundColor(markerBackgroundColor)
Specifies the marker background color of a chart series.

TypeScript

setMarkerBackgroundColor(markerBackgroundColor: string): void;

Parameters
markerBackgroundColor string

Returns
void

setMarkerForegroundColor(markerForegroundColor)
Specifies the marker foreground color of a chart series.

TypeScript

setMarkerForegroundColor(markerForegroundColor: string): void;

Parameters
markerForegroundColor string

Returns
void

setMarkerSize(markerSize)
Specifies the marker size of a chart series. The supported size range is 2 to 72. This
method returns an InvalidArgument error if it's set with a size outside of the
supported range.

TypeScript

setMarkerSize(markerSize: number): void;

Parameters
markerSize number

Returns
void

setMarkerStyle(markerStyle)
Specifies the marker style of a chart series. See ExcelScript.ChartMarkerStyle for
details.

TypeScript

setMarkerStyle(markerStyle: ChartMarkerStyle): void;


Parameters
markerStyle ExcelScript.ChartMarkerStyle

Returns
void

setName(name)
Specifies the name of a series in a chart. The name's length should not be greater
than 255 characters.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

setOverlap(overlap)
Specifies how bars and columns are positioned. Can be a value between -100 and
100. Applies only to 2-D bar and 2-D column charts.

TypeScript

setOverlap(overlap: number): void;

Parameters
overlap number

Returns
void
Examples

TypeScript

/**
* This sample sets the overlap of the columns in a chart named
"ColumnClusteredChart".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get an existing chart named "ColumnClusteredChart".


let chart = selectedSheet.getChart("ColumnClusteredChart");

// Set the overlap of every column of each series within a category.


let seriesList = chart.getSeries();
seriesList.forEach((series) => {
// An overlap of 25 means the columns have 25% of their length
overlapping with the adjacent columns in the same category.
series.setOverlap(25);
});
}

setParentLabelStrategy(parentLabelStrategy)
Specifies the series parent label strategy area for a treemap chart.

TypeScript

setParentLabelStrategy(
parentLabelStrategy: ChartParentLabelStrategy
): void;

Parameters
parentLabelStrategy ExcelScript.ChartParentLabelStrategy

Returns
void

setPlotOrder(plotOrder)
Specifies the plot order of a chart series within the chart group.
TypeScript

setPlotOrder(plotOrder: number): void;

Parameters
plotOrder number

Returns
void

setSecondPlotSize(secondPlotSize)
Specifies the size of the secondary section of either a pie-of-pie chart or a bar-of-pie
chart, as a percentage of the size of the primary pie. Can be a value from 5 to 200.

TypeScript

setSecondPlotSize(secondPlotSize: number): void;

Parameters
secondPlotSize number

Returns
void

setShowConnectorLines(showConnectorLines)
Specifies whether connector lines are shown in waterfall charts.

TypeScript

setShowConnectorLines(showConnectorLines: boolean): void;

Parameters
showConnectorLines boolean
Returns
void

setShowLeaderLines(showLeaderLines)
Specifies whether leader lines are displayed for each data label in the series.

TypeScript

setShowLeaderLines(showLeaderLines: boolean): void;

Parameters
showLeaderLines boolean

Returns
void

setShowShadow(showShadow)
Specifies if the series has a shadow.

TypeScript

setShowShadow(showShadow: boolean): void;

Parameters
showShadow boolean

Returns
void

setSmooth(smooth)
Specifies if the series is smooth. Only applicable to line and scatter charts.

TypeScript
setSmooth(smooth: boolean): void;

Parameters
smooth boolean

Returns
void

setSplitType(splitType)
Specifies the way the two sections of either a pie-of-pie chart or a bar-of-pie chart
are split.

TypeScript

setSplitType(splitType: ChartSplitType): void;

Parameters
splitType ExcelScript.ChartSplitType

Returns
void

setSplitValue(splitValue)
Specifies the threshold value that separates two sections of either a pie-of-pie chart
or a bar-of-pie chart.

TypeScript

setSplitValue(splitValue: number): void;

Parameters
splitValue number
Returns
void

setValues(sourceData)
Sets the values for a chart series. For scatter charts, it refers to y-axis values.

TypeScript

setValues(sourceData: Range): void;

Parameters
sourceData ExcelScript.Range
The Range object corresponding to the source data.

Returns
void

setVaryByCategories(varyByCategories)
True if Excel assigns a different color or pattern to each data marker. The chart must
contain only one series.

TypeScript

setVaryByCategories(varyByCategories: boolean): void;

Parameters
varyByCategories boolean

Returns
void

setXAxisValues(sourceData)
Sets the values of the x-axis for a chart series.
TypeScript

setXAxisValues(sourceData: Range): void;

Parameters
sourceData ExcelScript.Range
The Range object corresponding to the source data.

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartSeriesFormat interface
Reference
Package: ExcelScript

Encapsulates the format properties for the chart series

Methods
ノ Expand table

getFill() Represents the fill format of a chart series, which includes background formatting
information.

get Represents line formatting.


Line()

Method Details

getFill()
Represents the fill format of a chart series, which includes background formatting
information.

TypeScript

getFill(): ChartFill;

Returns
ExcelScript.ChartFill

getLine()
Represents line formatting.

TypeScript

getLine(): ChartLineFormat;
Returns
ExcelScript.ChartLineFormat

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTitle interface
Reference
Package: ExcelScript

Represents a chart title object of a chart.

Methods
ノ Expand table

getFormat() Represents the formatting of a chart title, which includes fill and font
formatting.

getHeight() Returns the height, in points, of the chart title. Value is null if the
chart title is not visible.

getHorizontalAlignment() Specifies the horizontal alignment for chart title.

getLeft() Specifies the distance, in points, from the left edge of chart title to
the left edge of chart area. Value is null if the chart title is not
visible.

getOverlay() Specifies if the chart title will overlay the chart.

getPosition() Represents the position of chart title. See


ExcelScript.ChartTitlePosition for details.

getShowShadow() Represents a boolean value that determines if the chart title has a
shadow.

getSubstring(start, length) Get the substring of a chart title. Line break '\n' counts one
character.

getText() Specifies the chart's title text.

getTextOrientation() Specifies the angle to which the text is oriented for the chart title.
The value should either be an integer from -90 to 90 or the integer
180 for vertically-oriented text.

getTop() Specifies the distance, in points, from the top edge of chart title to
the top of chart area. Value is null if the chart title is not visible.

getVerticalAlignment() Specifies the vertical alignment of chart title. See


ExcelScript.ChartTextVerticalAlignment for details.

getVisible() Specifies if the chart title is visible.


getWidth() Specifies the width, in points, of the chart title. Value is null if the
chart title is not visible.

setFormula(formula) Sets a string value that represents the formula of chart title using
A1-style notation.

setHorizontal Specifies the horizontal alignment for chart title.


Alignment(horizontal
Alignment)

setLeft(left) Specifies the distance, in points, from the left edge of chart title to
the left edge of chart area. Value is null if the chart title is not
visible.

setOverlay(overlay) Specifies if the chart title will overlay the chart.

setPosition(position) Represents the position of chart title. See


ExcelScript.ChartTitlePosition for details.

setShowShadow(show Represents a boolean value that determines if the chart title has a
Shadow) shadow.

setText(text) Specifies the chart's title text.

setTextOrientation(text Specifies the angle to which the text is oriented for the chart title.
Orientation) The value should either be an integer from -90 to 90 or the integer
180 for vertically-oriented text.

setTop(top) Specifies the distance, in points, from the top edge of chart title to
the top of chart area. Value is null if the chart title is not visible.

setVertical Specifies the vertical alignment of chart title. See


Alignment(vertical ExcelScript.ChartTextVerticalAlignment for details.
Alignment)

setVisible(visible) Specifies if the chart title is visible.

Method Details

getFormat()
Represents the formatting of a chart title, which includes fill and font formatting.

TypeScript

getFormat(): ChartTitleFormat;
Returns
ExcelScript.ChartTitleFormat

getHeight()
Returns the height, in points, of the chart title. Value is null if the chart title is not
visible.

TypeScript

getHeight(): number;

Returns
number

getHorizontalAlignment()
Specifies the horizontal alignment for chart title.

TypeScript

getHorizontalAlignment(): ChartTextHorizontalAlignment;

Returns
ExcelScript.ChartTextHorizontalAlignment

getLeft()
Specifies the distance, in points, from the left edge of chart title to the left edge of
chart area. Value is null if the chart title is not visible.

TypeScript

getLeft(): number;

Returns
number
getOverlay()
Specifies if the chart title will overlay the chart.

TypeScript

getOverlay(): boolean;

Returns
boolean

getPosition()
Represents the position of chart title. See ExcelScript.ChartTitlePosition for
details.

TypeScript

getPosition(): ChartTitlePosition;

Returns
ExcelScript.ChartTitlePosition

getShowShadow()
Represents a boolean value that determines if the chart title has a shadow.

TypeScript

getShowShadow(): boolean;

Returns
boolean

getSubstring(start, length)
Get the substring of a chart title. Line break '\n' counts one character.
TypeScript

getSubstring(start: number, length: number): ChartFormatString;

Parameters
start number
Start position of substring to be retrieved. Zero-indexed.

length number
Length of the substring to be retrieved.

Returns
ExcelScript.ChartFormatString

getText()
Specifies the chart's title text.

TypeScript

getText(): string;

Returns
string

getTextOrientation()
Specifies the angle to which the text is oriented for the chart title. The value should
either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.

TypeScript

getTextOrientation(): number;

Returns
number
getTop()
Specifies the distance, in points, from the top edge of chart title to the top of chart
area. Value is null if the chart title is not visible.

TypeScript

getTop(): number;

Returns
number

getVerticalAlignment()
Specifies the vertical alignment of chart title. See
ExcelScript.ChartTextVerticalAlignment for details.

TypeScript

getVerticalAlignment(): ChartTextVerticalAlignment;

Returns
ExcelScript.ChartTextVerticalAlignment

getVisible()
Specifies if the chart title is visible.

TypeScript

getVisible(): boolean;

Returns
boolean

getWidth()
Specifies the width, in points, of the chart title. Value is null if the chart title is not
visible.

TypeScript

getWidth(): number;

Returns
number

setFormula(formula)
Sets a string value that represents the formula of chart title using A1-style notation.

TypeScript

setFormula(formula: string): void;

Parameters
formula string
A string that represents the formula to set.

Returns
void

setHorizontalAlignment(horizontalAlignment)
Specifies the horizontal alignment for chart title.

TypeScript

setHorizontalAlignment(
horizontalAlignment: ChartTextHorizontalAlignment
): void;

Parameters
horizontalAlignment ExcelScript.ChartTextHorizontalAlignment
Returns
void

setLeft(left)
Specifies the distance, in points, from the left edge of chart title to the left edge of
chart area. Value is null if the chart title is not visible.

TypeScript

setLeft(left: number): void;

Parameters
left number

Returns
void

setOverlay(overlay)
Specifies if the chart title will overlay the chart.

TypeScript

setOverlay(overlay: boolean): void;

Parameters
overlay boolean

Returns
void

setPosition(position)
Represents the position of chart title. See ExcelScript.ChartTitlePosition for
details.
TypeScript

setPosition(position: ChartTitlePosition): void;

Parameters
position ExcelScript.ChartTitlePosition

Returns
void

setShowShadow(showShadow)
Represents a boolean value that determines if the chart title has a shadow.

TypeScript

setShowShadow(showShadow: boolean): void;

Parameters
showShadow boolean

Returns
void

setText(text)
Specifies the chart's title text.

TypeScript

setText(text: string): void;

Parameters
text string

Returns
void

setTextOrientation(textOrientation)
Specifies the angle to which the text is oriented for the chart title. The value should
either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.

TypeScript

setTextOrientation(textOrientation: number): void;

Parameters
textOrientation number

Returns
void

setTop(top)
Specifies the distance, in points, from the top edge of chart title to the top of chart
area. Value is null if the chart title is not visible.

TypeScript

setTop(top: number): void;

Parameters
top number

Returns
void

setVerticalAlignment(verticalAlignment)
Specifies the vertical alignment of chart title. See
ExcelScript.ChartTextVerticalAlignment for details.
TypeScript

setVerticalAlignment(
verticalAlignment: ChartTextVerticalAlignment
): void;

Parameters
verticalAlignment ExcelScript.ChartTextVerticalAlignment

Returns
void

setVisible(visible)
Specifies if the chart title is visible.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTitleFormat interface
Reference
Package: ExcelScript

Provides access to the formatting options for a chart title.

Methods
ノ Expand table

get Represents the border format of chart title, which includes color, linestyle, and
Border() weight.

getFill() Represents the fill format of an object, which includes background formatting
information.

getFont() Represents the font attributes (such as font name, font size, and color) for an object.

Method Details

getBorder()
Represents the border format of chart title, which includes color, linestyle, and
weight.

TypeScript

getBorder(): ChartBorder;

Returns
ExcelScript.ChartBorder

getFill()
Represents the fill format of an object, which includes background formatting
information.

TypeScript
getFill(): ChartFill;

Returns
ExcelScript.ChartFill

getFont()
Represents the font attributes (such as font name, font size, and color) for an object.

TypeScript

getFont(): ChartFont;

Returns
ExcelScript.ChartFont

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTrendline interface
Reference
Package: ExcelScript

This object represents the attributes for a chart trendline object.

Methods
ノ Expand table

delete() Delete the trendline object.

getBackwardPeriod() Represents the number of periods that the trendline extends


backward.

getFormat() Represents the formatting of a chart trendline.

getForwardPeriod() Represents the number of periods that the trendline extends


forward.

getIntercept() Specifies the intercept value of the trendline.

getLabel() Represents the label of a chart trendline.

getMovingAveragePeriod() Represents the period of a chart trendline. Only applicable to


trendlines with the type MovingAverage .

getName() Represents the name of the trendline. Can be set to a string


value, a null value represents automatic values. The returned
value is always a string

getPolynomialOrder() Represents the order of a chart trendline. Only applicable to


trendlines with the type Polynomial .

getShowEquation() True if the equation for the trendline is displayed on the chart.

getShowRSquared() True if the r-squared value for the trendline is displayed on the
chart.

getType() Represents the type of a chart trendline.

setBackwardPeriod(backward Represents the number of periods that the trendline extends


Period) backward.

setForwardPeriod(forward Represents the number of periods that the trendline extends


Period) forward.
setIntercept(intercept) Specifies the intercept value of the trendline.

setMovingAverage Represents the period of a chart trendline. Only applicable to


Period(movingAveragePeriod) trendlines with the type MovingAverage .

setName(name) Represents the name of the trendline. Can be set to a string


value, a null value represents automatic values. The returned
value is always a string

setPolynomial Represents the order of a chart trendline. Only applicable to


Order(polynomialOrder) trendlines with the type Polynomial .

setShowEquation(show True if the equation for the trendline is displayed on the chart.
Equation)

setShowRSquared(show True if the r-squared value for the trendline is displayed on the
RSquared) chart.

setType(type) Represents the type of a chart trendline.

Method Details

delete()
Delete the trendline object.

TypeScript

delete(): void;

Returns
void

getBackwardPeriod()
Represents the number of periods that the trendline extends backward.

TypeScript

getBackwardPeriod(): number;

Returns
number

getFormat()
Represents the formatting of a chart trendline.

TypeScript

getFormat(): ChartTrendlineFormat;

Returns
ExcelScript.ChartTrendlineFormat

getForwardPeriod()
Represents the number of periods that the trendline extends forward.

TypeScript

getForwardPeriod(): number;

Returns
number

getIntercept()
Specifies the intercept value of the trendline.

TypeScript

getIntercept(): number;

Returns
number

getLabel()
Represents the label of a chart trendline.
TypeScript

getLabel(): ChartTrendlineLabel;

Returns
ExcelScript.ChartTrendlineLabel

getMovingAveragePeriod()
Represents the period of a chart trendline. Only applicable to trendlines with the
type MovingAverage .

TypeScript

getMovingAveragePeriod(): number;

Returns
number

getName()
Represents the name of the trendline. Can be set to a string value, a null value
represents automatic values. The returned value is always a string

TypeScript

getName(): string;

Returns
string

getPolynomialOrder()
Represents the order of a chart trendline. Only applicable to trendlines with the type
Polynomial .

TypeScript
getPolynomialOrder(): number;

Returns
number

getShowEquation()
True if the equation for the trendline is displayed on the chart.

TypeScript

getShowEquation(): boolean;

Returns
boolean

getShowRSquared()
True if the r-squared value for the trendline is displayed on the chart.

TypeScript

getShowRSquared(): boolean;

Returns
boolean

getType()
Represents the type of a chart trendline.

TypeScript

getType(): ChartTrendlineType;

Returns
ExcelScript.ChartTrendlineType

setBackwardPeriod(backwardPeriod)
Represents the number of periods that the trendline extends backward.

TypeScript

setBackwardPeriod(backwardPeriod: number): void;

Parameters
backwardPeriod number

Returns
void

setForwardPeriod(forwardPeriod)
Represents the number of periods that the trendline extends forward.

TypeScript

setForwardPeriod(forwardPeriod: number): void;

Parameters
forwardPeriod number

Returns
void

setIntercept(intercept)
Specifies the intercept value of the trendline.

TypeScript

setIntercept(intercept: number): void;


Parameters
intercept number

Returns
void

setMovingAveragePeriod(movingAveragePeriod)
Represents the period of a chart trendline. Only applicable to trendlines with the
type MovingAverage .

TypeScript

setMovingAveragePeriod(movingAveragePeriod: number): void;

Parameters
movingAveragePeriod number

Returns
void

setName(name)
Represents the name of the trendline. Can be set to a string value, a null value
represents automatic values. The returned value is always a string

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void
setPolynomialOrder(polynomialOrder)
Represents the order of a chart trendline. Only applicable to trendlines with the type
Polynomial .

TypeScript

setPolynomialOrder(polynomialOrder: number): void;

Parameters
polynomialOrder number

Returns
void

setShowEquation(showEquation)
True if the equation for the trendline is displayed on the chart.

TypeScript

setShowEquation(showEquation: boolean): void;

Parameters
showEquation boolean

Returns
void

setShowRSquared(showRSquared)
True if the r-squared value for the trendline is displayed on the chart.

TypeScript

setShowRSquared(showRSquared: boolean): void;


Parameters
showRSquared boolean

Returns
void

setType(type)
Represents the type of a chart trendline.

TypeScript

setType(type: ChartTrendlineType): void;

Parameters
type ExcelScript.ChartTrendlineType

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTrendlineFormat
interface
Reference
Package: ExcelScript

Represents the format properties for the chart trendline.

Methods
ノ Expand table

getLine() Represents chart line formatting.

Method Details

getLine()
Represents chart line formatting.

TypeScript

getLine(): ChartLineFormat;

Returns
ExcelScript.ChartLineFormat

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTrendlineLabel
interface
Reference
Package: ExcelScript

This object represents the attributes for a chart trendline label object.

Methods
ノ Expand table

getAutoText() Specifies if the trendline label automatically generates appropriate


text based on context.

getFormat() The format of the chart trendline label.

getFormula() String value that represents the formula of the chart trendline label
using A1-style notation.

getHeight() Returns the height, in points, of the chart trendline label. Value is null
if the chart trendline label is not visible.

getHorizontal Represents the horizontal alignment of the chart trendline label. See
Alignment() ExcelScript.ChartTextHorizontalAlignment for details. This property is
valid only when TextOrientation of a trendline label is -90, 90, or 180.

getLeft() Represents the distance, in points, from the left edge of the chart
trendline label to the left edge of the chart area. Value is null if the
chart trendline label is not visible.

getLinkNumberFormat() Specifies if the number format is linked to the cells (so that the
number format changes in the labels when it changes in the cells).

getNumberFormat() String value that represents the format code for the trendline label.

getText() String representing the text of the trendline label on a chart.

getTextOrientation() Represents the angle to which the text is oriented for the chart
trendline label. The value should either be an integer from -90 to 90
or the integer 180 for vertically-oriented text.

getTop() Represents the distance, in points, from the top edge of the chart
trendline label to the top of the chart area. Value is null if the chart
trendline label is not visible.
getVerticalAlignment() Represents the vertical alignment of the chart trendline label. See
ExcelScript.ChartTextVerticalAlignment for details. This property is
valid only when TextOrientation of a trendline label is 0.

getWidth() Returns the width, in points, of the chart trendline label. Value is null
if the chart trendline label is not visible.

setAutoText(autoText) Specifies if the trendline label automatically generates appropriate


text based on context.

setFormula(formula) String value that represents the formula of the chart trendline label
using A1-style notation.

setHorizontal Represents the horizontal alignment of the chart trendline label. See
Alignment(horizontal ExcelScript.ChartTextHorizontalAlignment for details. This property is
Alignment) valid only when TextOrientation of a trendline label is -90, 90, or 180.

setLeft(left) Represents the distance, in points, from the left edge of the chart
trendline label to the left edge of the chart area. Value is null if the
chart trendline label is not visible.

setLinkNumber Specifies if the number format is linked to the cells (so that the
Format(linkNumber number format changes in the labels when it changes in the cells).
Format)

setNumber String value that represents the format code for the trendline label.
Format(numberFormat)

setText(text) String representing the text of the trendline label on a chart.

setTextOrientation(text Represents the angle to which the text is oriented for the chart
Orientation) trendline label. The value should either be an integer from -90 to 90
or the integer 180 for vertically-oriented text.

setTop(top) Represents the distance, in points, from the top edge of the chart
trendline label to the top of the chart area. Value is null if the chart
trendline label is not visible.

setVertical Represents the vertical alignment of the chart trendline label. See
Alignment(vertical ExcelScript.ChartTextVerticalAlignment for details. This property is
Alignment) valid only when TextOrientation of a trendline label is 0.

Method Details

getAutoText()
Specifies if the trendline label automatically generates appropriate text based on
context.
TypeScript

getAutoText(): boolean;

Returns
boolean

getFormat()
The format of the chart trendline label.

TypeScript

getFormat(): ChartTrendlineLabelFormat;

Returns
ExcelScript.ChartTrendlineLabelFormat

getFormula()
String value that represents the formula of the chart trendline label using A1-style
notation.

TypeScript

getFormula(): string;

Returns
string

getHeight()
Returns the height, in points, of the chart trendline label. Value is null if the chart
trendline label is not visible.

TypeScript

getHeight(): number;
Returns
number

getHorizontalAlignment()
Represents the horizontal alignment of the chart trendline label. See
ExcelScript.ChartTextHorizontalAlignment for details. This property is valid only

when TextOrientation of a trendline label is -90, 90, or 180.

TypeScript

getHorizontalAlignment(): ChartTextHorizontalAlignment;

Returns
ExcelScript.ChartTextHorizontalAlignment

getLeft()
Represents the distance, in points, from the left edge of the chart trendline label to
the left edge of the chart area. Value is null if the chart trendline label is not visible.

TypeScript

getLeft(): number;

Returns
number

getLinkNumberFormat()
Specifies if the number format is linked to the cells (so that the number format
changes in the labels when it changes in the cells).

TypeScript

getLinkNumberFormat(): boolean;

Returns
boolean

getNumberFormat()
String value that represents the format code for the trendline label.

TypeScript

getNumberFormat(): string;

Returns
string

getText()
String representing the text of the trendline label on a chart.

TypeScript

getText(): string;

Returns
string

getTextOrientation()
Represents the angle to which the text is oriented for the chart trendline label. The
value should either be an integer from -90 to 90 or the integer 180 for vertically-
oriented text.

TypeScript

getTextOrientation(): number;

Returns
number

getTop()
Represents the distance, in points, from the top edge of the chart trendline label to
the top of the chart area. Value is null if the chart trendline label is not visible.

TypeScript

getTop(): number;

Returns
number

getVerticalAlignment()
Represents the vertical alignment of the chart trendline label. See
ExcelScript.ChartTextVerticalAlignment for details. This property is valid only when

TextOrientation of a trendline label is 0.

TypeScript

getVerticalAlignment(): ChartTextVerticalAlignment;

Returns
ExcelScript.ChartTextVerticalAlignment

getWidth()
Returns the width, in points, of the chart trendline label. Value is null if the chart
trendline label is not visible.

TypeScript

getWidth(): number;

Returns
number

setAutoText(autoText)
Specifies if the trendline label automatically generates appropriate text based on
context.

TypeScript

setAutoText(autoText: boolean): void;

Parameters
autoText boolean

Returns
void

setFormula(formula)
String value that represents the formula of the chart trendline label using A1-style
notation.

TypeScript

setFormula(formula: string): void;

Parameters
formula string

Returns
void

setHorizontalAlignment(horizontalAlignment)
Represents the horizontal alignment of the chart trendline label. See
ExcelScript.ChartTextHorizontalAlignment for details. This property is valid only

when TextOrientation of a trendline label is -90, 90, or 180.

TypeScript

setHorizontalAlignment(
horizontalAlignment: ChartTextHorizontalAlignment
): void;

Parameters
horizontalAlignment ExcelScript.ChartTextHorizontalAlignment

Returns
void

setLeft(left)
Represents the distance, in points, from the left edge of the chart trendline label to
the left edge of the chart area. Value is null if the chart trendline label is not visible.

TypeScript

setLeft(left: number): void;

Parameters
left number

Returns
void

setLinkNumberFormat(linkNumberFormat)
Specifies if the number format is linked to the cells (so that the number format
changes in the labels when it changes in the cells).

TypeScript

setLinkNumberFormat(linkNumberFormat: boolean): void;

Parameters
linkNumberFormat boolean

Returns
void

setNumberFormat(numberFormat)
String value that represents the format code for the trendline label.

TypeScript

setNumberFormat(numberFormat: string): void;

Parameters
numberFormat string

Returns
void

setText(text)
String representing the text of the trendline label on a chart.

TypeScript

setText(text: string): void;

Parameters
text string

Returns
void

setTextOrientation(textOrientation)
Represents the angle to which the text is oriented for the chart trendline label. The
value should either be an integer from -90 to 90 or the integer 180 for vertically-
oriented text.

TypeScript
setTextOrientation(textOrientation: number): void;

Parameters
textOrientation number

Returns
void

setTop(top)
Represents the distance, in points, from the top edge of the chart trendline label to
the top of the chart area. Value is null if the chart trendline label is not visible.

TypeScript

setTop(top: number): void;

Parameters
top number

Returns
void

setVerticalAlignment(verticalAlignment)
Represents the vertical alignment of the chart trendline label. See
ExcelScript.ChartTextVerticalAlignment for details. This property is valid only when

TextOrientation of a trendline label is 0.

TypeScript

setVerticalAlignment(
verticalAlignment: ChartTextVerticalAlignment
): void;

Parameters
verticalAlignment ExcelScript.ChartTextVerticalAlignment

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ChartTrendlineLabelFormat
interface
Reference
Package: ExcelScript

Encapsulates the format properties for the chart trendline label.

Methods
ノ Expand table

get Specifies the border format, which includes color, linestyle, and weight.
Border()

getFill() Specifies the fill format of the current chart trendline label.

getFont() Specifies the font attributes (such as font name, font size, and color) for a chart
trendline label.

Method Details

getBorder()
Specifies the border format, which includes color, linestyle, and weight.

TypeScript

getBorder(): ChartBorder;

Returns
ExcelScript.ChartBorder

getFill()
Specifies the fill format of the current chart trendline label.

TypeScript
getFill(): ChartFill;

Returns
ExcelScript.ChartFill

getFont()
Specifies the font attributes (such as font name, font size, and color) for a chart
trendline label.

TypeScript

getFont(): ChartFont;

Returns
ExcelScript.ChartFont

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ColorScaleConditional
Format interface
Reference
Package: ExcelScript

Represents the color scale criteria for conditional formatting.

Methods
ノ Expand table

getCriteria() The criteria of the color scale. Midpoint is optional when using a two point
color scale.

getThreeColor If true , the color scale will have three points (minimum, midpoint,
Scale() maximum), otherwise it will have two (minimum, maximum).

setCriteria(criteria) The criteria of the color scale. Midpoint is optional when using a two point
color scale.

Method Details

getCriteria()
The criteria of the color scale. Midpoint is optional when using a two point color
scale.

TypeScript

getCriteria(): ConditionalColorScaleCriteria;

Returns
ExcelScript.ConditionalColorScaleCriteria

getThreeColorScale()
If true , the color scale will have three points (minimum, midpoint, maximum),
otherwise it will have two (minimum, maximum).
TypeScript

getThreeColorScale(): boolean;

Returns
boolean

setCriteria(criteria)
The criteria of the color scale. Midpoint is optional when using a two point color
scale.

TypeScript

setCriteria(criteria: ConditionalColorScaleCriteria): void;

Parameters
criteria ExcelScript.ConditionalColorScaleCriteria

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Comment interface
Reference
Package: ExcelScript

Represents a comment in the workbook.

Methods
ノ Expand table

addComment Creates a comment reply for a comment.


Reply(content, content
Type)

delete() Deletes the comment and all the connected replies.

getAuthorEmail() Gets the email of the comment's author.

getAuthorName() Gets the name of the comment's author.

getComment Returns a comment reply identified by its ID. If the comment reply
Reply(commentReplyId) object does not exist, then this method returns undefined .

getContent() The comment's content. The string is plain text.

getContentType() Gets the content type of the comment.

getCreationDate() Gets the creation time of the comment. Returns null if the comment
was converted from a note, since the comment does not have a
creation date.

getId() Specifies the comment identifier.

getLocation() Gets the cell where this comment is located.

getMentions() Gets the entities (e.g., people) that are mentioned in comments.

getReplies() Represents a collection of reply objects associated with the


comment.

getResolved() The comment thread status. A value of true means that the
comment thread is resolved.

getRichContent() Gets the rich comment content (e.g., mentions in comments). This
string is not meant to be displayed to end-users. Your add-in should
only use this to parse rich comment content.
setContent(content) The comment's content. The string is plain text.

setResolved(resolved) The comment thread status. A value of true means that the
comment thread is resolved.

updateMentions(content Updates the comment content with a specially formatted string and
WithMentions) a list of mentions.

Method Details

addCommentReply(content, contentType)
Creates a comment reply for a comment.

TypeScript

addCommentReply(
content: CommentRichContent | string,
contentType?: ContentType
): CommentReply;

Parameters
content ExcelScript.CommentRichContent | string
The comment's content. This can be either a string or a CommentRichContent object
(e.g., for comments with mentions).

contentType ExcelScript.ContentType
Optional. The type of content contained within the comment. The default value is
enum ContentType.Plain .

Returns
ExcelScript.CommentReply

delete()
Deletes the comment and all the connected replies.

TypeScript

delete(): void;
Returns
void

getAuthorEmail()
Gets the email of the comment's author.

TypeScript

getAuthorEmail(): string;

Returns
string

getAuthorName()
Gets the name of the comment's author.

TypeScript

getAuthorName(): string;

Returns
string

getCommentReply(commentReplyId)
Returns a comment reply identified by its ID. If the comment reply object does not
exist, then this method returns undefined .

TypeScript

getCommentReply(commentReplyId: string): CommentReply | undefined;

Parameters
commentReplyId string
The identifier for the comment reply.
Returns
ExcelScript.CommentReply | undefined

getContent()
The comment's content. The string is plain text.

TypeScript

getContent(): string;

Returns
string

getContentType()
Gets the content type of the comment.

TypeScript

getContentType(): ContentType;

Returns
ExcelScript.ContentType

getCreationDate()
Gets the creation time of the comment. Returns null if the comment was converted
from a note, since the comment does not have a creation date.

TypeScript

getCreationDate(): Date;

Returns
Date
getId()
Specifies the comment identifier.

TypeScript

getId(): string;

Returns
string

getLocation()
Gets the cell where this comment is located.

TypeScript

getLocation(): Range;

Returns
ExcelScript.Range

getMentions()
Gets the entities (e.g., people) that are mentioned in comments.

TypeScript

getMentions(): CommentMention[];

Returns
ExcelScript.CommentMention[]

getReplies()
Represents a collection of reply objects associated with the comment.

TypeScript
getReplies(): CommentReply[];

Returns
ExcelScript.CommentReply[]

getResolved()
The comment thread status. A value of true means that the comment thread is
resolved.

TypeScript

getResolved(): boolean;

Returns
boolean

getRichContent()
Gets the rich comment content (e.g., mentions in comments). This string is not meant
to be displayed to end-users. Your add-in should only use this to parse rich comment
content.

TypeScript

getRichContent(): string;

Returns
string

setContent(content)
The comment's content. The string is plain text.

TypeScript

setContent(content: string): void;


Parameters
content string

Returns
void

setResolved(resolved)
The comment thread status. A value of true means that the comment thread is
resolved.

TypeScript

setResolved(resolved: boolean): void;

Parameters
resolved boolean

Returns
void

updateMentions(contentWithMentions)
Updates the comment content with a specially formatted string and a list of
mentions.

TypeScript

updateMentions(contentWithMentions: CommentRichContent): void;

Parameters
contentWithMentions ExcelScript.CommentRichContent
The content for the comment. This contains a specially formatted string and a list of
mentions that will be parsed into the string when displayed by Excel.

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CommentMention interface
Reference
Package: ExcelScript

Represents the entity that is mentioned in comments.

Remarks

Examples

TypeScript

/**
* This sample creates a comment that mentions a specific person.
* That person will get a notification and link to the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell in the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const cell = currentSheet.getCell(0,0);

/* Create a CommentMention object for the comment.


*
* A CommentMention's properties are:
* `name`: The name of the person being mentioned.
* `id`: The zero-based index of this mention in the comment.
* `email`: The email address of the person being mentioned.
*/
const mention: ExcelScript.CommentMention = {
name: "Alex",
id: 0,
email: "[email protected]"
};

/* Create comment content that uses the mention.


* The `<at id="0">` syntax embeds the mention with ID 0 in the comment
text.
* The name is displayed in the comment,
* while an email is sent to the given address.
*/
const content: ExcelScript.CommentRichContent = {
richContent: '<at id="0">' + mention.name + "</at> - Hello!",
mentions: [mention]
};

// Add the comment.


currentSheet.addComment(cell, content, ExcelScript.ContentType.mention);
}

Properties
ノ Expand table

email The email address of the entity that is mentioned in a comment.

id The ID of the entity. The ID matches one of the IDs in CommentRichContent.richContent .

name The name of the entity that is mentioned in a comment.

Property Details

email
The email address of the entity that is mentioned in a comment.

TypeScript

email: string;

Property Value
string

id
The ID of the entity. The ID matches one of the IDs in
CommentRichContent.richContent .

TypeScript

id: number;

Property Value
number
name
The name of the entity that is mentioned in a comment.

TypeScript

name: string;

Property Value
string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CommentReply interface
Reference
Package: ExcelScript

Represents a comment reply in the workbook.

Methods
ノ Expand table

delete() Deletes the comment reply.

getAuthorEmail() Gets the email of the comment reply's author.

getAuthorName() Gets the name of the comment reply's author.

getContent() The comment reply's content. The string is plain text.

getContentType() The content type of the reply.

getCreationDate() Gets the creation time of the comment reply.

getId() Specifies the comment reply identifier.

getLocation() Gets the cell where this comment reply is located.

getMentions() The entities (e.g., people) that are mentioned in comments.

getParentComment() Gets the parent comment of this reply.

getResolved() The comment reply status. A value of true means the reply is in the
resolved state.

getRichContent() The rich comment content (e.g., mentions in comments). This string is
not meant to be displayed to end-users. Your add-in should only use
this to parse rich comment content.

setContent(content) The comment reply's content. The string is plain text.

updateMentions(content Updates the comment content with a specially formatted string and a
WithMentions) list of mentions.

Method Details

delete()
Deletes the comment reply.

TypeScript

delete(): void;

Returns
void

getAuthorEmail()
Gets the email of the comment reply's author.

TypeScript

getAuthorEmail(): string;

Returns
string

getAuthorName()
Gets the name of the comment reply's author.

TypeScript

getAuthorName(): string;

Returns
string

getContent()
The comment reply's content. The string is plain text.

TypeScript

getContent(): string;
Returns
string

getContentType()
The content type of the reply.

TypeScript

getContentType(): ContentType;

Returns
ExcelScript.ContentType

getCreationDate()
Gets the creation time of the comment reply.

TypeScript

getCreationDate(): Date;

Returns
Date

getId()
Specifies the comment reply identifier.

TypeScript

getId(): string;

Returns
string

getLocation()
Gets the cell where this comment reply is located.

TypeScript

getLocation(): Range;

Returns
ExcelScript.Range

getMentions()
The entities (e.g., people) that are mentioned in comments.

TypeScript

getMentions(): CommentMention[];

Returns
ExcelScript.CommentMention[]

getParentComment()
Gets the parent comment of this reply.

TypeScript

getParentComment(): Comment;

Returns
ExcelScript.Comment

getResolved()
The comment reply status. A value of true means the reply is in the resolved state.

TypeScript

getResolved(): boolean;
Returns
boolean

getRichContent()
The rich comment content (e.g., mentions in comments). This string is not meant to
be displayed to end-users. Your add-in should only use this to parse rich comment
content.

TypeScript

getRichContent(): string;

Returns
string

setContent(content)
The comment reply's content. The string is plain text.

TypeScript

setContent(content: string): void;

Parameters
content string

Returns
void

updateMentions(contentWithMentions)
Updates the comment content with a specially formatted string and a list of
mentions.

TypeScript

updateMentions(contentWithMentions: CommentRichContent): void;


Parameters
contentWithMentions ExcelScript.CommentRichContent
The content for the comment. This contains a specially formatted string and a list of
mentions that will be parsed into the string when displayed by Excel.

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CommentRichContent
interface
Reference
Package: ExcelScript

Represents the content contained within a comment or comment reply. Rich content
incudes the text string and any other objects contained within the comment body, such
as mentions.

Properties
ノ Expand table

mentions An array containing all the entities (e.g., people) mentioned within the comment.

rich Specifies the rich content of the comment (e.g., comment content with mentions, the
Content first mentioned entity has an ID attribute of 0, and the second mentioned entity has
an ID attribute of 1).

Property Details

mentions
An array containing all the entities (e.g., people) mentioned within the comment.

TypeScript

mentions?: CommentMention[];

Property Value
ExcelScript.CommentMention[]

richContent
Specifies the rich content of the comment (e.g., comment content with mentions, the
first mentioned entity has an ID attribute of 0, and the second mentioned entity has
an ID attribute of 1).
TypeScript

richContent: string;

Property Value
string

Examples

TypeScript

/**
* This sample finds overdue work items in a table and
* lets their owners know with a comment that uses an @mention.
*
* This assumes the worksheet has a table with the columns:
* "Work Item", "Project", "Owner", "Due Date"
*/
function main(workbook: ExcelScript.Workbook) {
let currentSheet = workbook.getActiveWorksheet();

// Get the "Owner" column range and values.


let table = currentSheet.getTables()[0];
let ownerColumnRange =
table.getColumn("Owner").getRangeBetweenHeaderAndTotal();
let ownerColumnValues = ownerColumnRange.getValues();

// Get the "Due Date" column range and values.


let dueDateColumnRange = table.getColumn("Due
Date").getRangeBetweenHeaderAndTotal();
let dueDateColumnValues = dueDateColumnRange.getValues();

// Look for overdue work items.


for (let row = 0; row < dueDateColumnValues.length; row++) {

/* Convert the Excel date into a JavaScript date.


* This is necessary because Excel and JavaScript store
* their dates as different numerical values.
*/
let dueDate = new Date(Math.round((dueDateColumnValues[row][0] as
number - 25569) * 86400 * 1000));

// Check if the current date is greater than the due date.


if (Date.now() > dueDate.valueOf()) {

/* Create a CommentMention object for the comment,


* based on the work item's owner.
*
* A CommentMention's properties are:
* `name`: The name of the person being mentioned.
* `id`: The index of this mention in the comment.
* `email`: The email address of the person being mentioned.
* In this sample, "Owner: is also the user name for the
email.
*/
let mention = {
name: ownerColumnValues[row][0].toString(),
id: 0,
email: ownerColumnValues[row][0] + "@contoso.com"
};

/* Create the comment.


* The `<at id="0">` syntax embeds the mention in the comment text.
* The name is displayed in the comment,
* while an email is sent to the given address.
*
* The addComment parameters are:
* `cellAddress`: The location of the comment.
* `content`: The text of the comment and any embedded mentions.
* `contentType`: The type of comment ("Mention" or "Plain").
*/
currentSheet.addComment(
dueDateColumnRange.getCell(row, 0),
{
richContent: '<at id="0">' + mention.name + "</at> - Your work
item is overdue.",
mentions: [mention]
},
ExcelScript.ContentType.mention
);
}
}
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalCellValueRule
interface
Reference
Package: ExcelScript

Represents a cell value conditional format rule.

Remarks

Examples

TypeScript

/**
* This script applies conditional formatting to a range.
* That formatting is conditional upon the cell's numerical value.
* Any value between 50 and 75 will have the cell fill color changed and the
font made italic.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range to format.
const sheet = workbook.getActiveWorksheet();
const ratingColumn = sheet.getRange("D2:D20");

// Add cell value conditional formatting.


const cellValueConditionalFormatting =

ratingColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.cellValu
e).getCellValue();

// Create the condition, in this case when the cell value is between 50
and 75.
let rule: ExcelScript.ConditionalCellValueRule = {
formula1: "50",
formula2: "75",
operator: ExcelScript.ConditionalCellValueOperator.between
};
cellValueConditionalFormatting.setRule(rule);

// Set the format to apply when the condition is met.


let format = cellValueConditionalFormatting.getFormat();
format.getFill().setColor("yellow");
format.getFont().setItalic(true);
}
Properties
ノ Expand table

formula1 The formula, if required, on which to evaluate the conditional format rule.

formula2 The formula, if required, on which to evaluate the conditional format rule.

operator The operator of the cell value conditional format.

Property Details

formula1
The formula, if required, on which to evaluate the conditional format rule.

TypeScript

formula1: string;

Property Value
string

formula2
The formula, if required, on which to evaluate the conditional format rule.

TypeScript

formula2?: string;

Property Value
string

operator
The operator of the cell value conditional format.

TypeScript
operator: ConditionalCellValueOperator;

Property Value
ExcelScript.ConditionalCellValueOperator

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalColorScale
Criteria interface
Reference
Package: ExcelScript

Represents the criteria of the color scale.

Properties
ノ Expand table

maximum The maximum point of the color scale criterion.

midpoint The midpoint of the color scale criterion, if the color scale is a 3-color scale.

minimum The minimum point of the color scale criterion.

Property Details

maximum
The maximum point of the color scale criterion.

TypeScript

maximum: ConditionalColorScaleCriterion;

Property Value
ExcelScript.ConditionalColorScaleCriterion

midpoint
The midpoint of the color scale criterion, if the color scale is a 3-color scale.

TypeScript

midpoint?: ConditionalColorScaleCriterion;
Property Value
ExcelScript.ConditionalColorScaleCriterion

minimum
The minimum point of the color scale criterion.

TypeScript

minimum: ConditionalColorScaleCriterion;

Property Value
ExcelScript.ConditionalColorScaleCriterion

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalColorScale
Criterion interface
Reference
Package: ExcelScript

Represents a color scale criterion which contains a type, value, and a color.

Properties
ノ Expand table

color HTML color code representation of the color scale color (e.g., #FF0000 represents Red).

formula A number, a formula, or null (if type is lowestValue ).

type What the criterion conditional formula should be based on.

Property Details

color
HTML color code representation of the color scale color (e.g., #FF0000 represents
Red).

TypeScript

color?: string;

Property Value
string

formula
A number, a formula, or null (if type is lowestValue ).

TypeScript
formula?: string;

Property Value
string

type
What the criterion conditional formula should be based on.

TypeScript

type: ConditionalFormatColorCriterionType;

Property Value
ExcelScript.ConditionalFormatColorCriterionType

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalDataBarNegative
Format interface
Reference
Package: ExcelScript

Represents a conditional format for the negative side of the data bar.

Methods
ノ Expand table

getBorderColor() HTML color code representing the color of the border line, in the
form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g.,
"orange"). Value is "" (an empty string) if no border is present or set.

getFillColor() HTML color code representing the fill color, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange").

getMatchPositiveBorder Specifies if the negative data bar has the same border color as the
Color() positive data bar.

getMatchPositiveFill Specifies if the negative data bar has the same fill color as the
Color() positive data bar.

setBorderColor(border HTML color code representing the color of the border line, in the
Color) form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g.,
"orange"). Value is "" (an empty string) if no border is present or set.

setFillColor(fillColor) HTML color code representing the fill color, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange").

setMatchPositiveBorder Specifies if the negative data bar has the same border color as the
Color(matchPositive positive data bar.
BorderColor)

setMatchPositiveFill Specifies if the negative data bar has the same fill color as the
Color(matchPositiveFill positive data bar.
Color)

Method Details

getBorderColor()
HTML color code representing the color of the border line, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange"). Value is "" (an empty
string) if no border is present or set.

TypeScript

getBorderColor(): string;

Returns
string

getFillColor()
HTML color code representing the fill color, in the form #RRGGBB (e.g., "FFA500") or
as a named HTML color (e.g., "orange").

TypeScript

getFillColor(): string;

Returns
string

getMatchPositiveBorderColor()
Specifies if the negative data bar has the same border color as the positive data bar.

TypeScript

getMatchPositiveBorderColor(): boolean;

Returns
boolean

getMatchPositiveFillColor()
Specifies if the negative data bar has the same fill color as the positive data bar.
TypeScript

getMatchPositiveFillColor(): boolean;

Returns
boolean

setBorderColor(borderColor)
HTML color code representing the color of the border line, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange"). Value is "" (an empty
string) if no border is present or set.

TypeScript

setBorderColor(borderColor: string): void;

Parameters
borderColor string

Returns
void

setFillColor(fillColor)
HTML color code representing the fill color, in the form #RRGGBB (e.g., "FFA500") or
as a named HTML color (e.g., "orange").

TypeScript

setFillColor(fillColor: string): void;

Parameters
fillColor string

Returns
void

setMatchPositiveBorderColor(matchPositiveBorderColor)
Specifies if the negative data bar has the same border color as the positive data bar.

TypeScript

setMatchPositiveBorderColor(matchPositiveBorderColor: boolean): void;

Parameters
matchPositiveBorderColor boolean

Returns
void

setMatchPositiveFillColor(matchPositiveFillColor)
Specifies if the negative data bar has the same fill color as the positive data bar.

TypeScript

setMatchPositiveFillColor(matchPositiveFillColor: boolean): void;

Parameters
matchPositiveFillColor boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our  Provide product feedback
contributor guide.
ExcelScript.ConditionalDataBarPositive
Format interface
Reference
Package: ExcelScript

Represents a conditional format for the positive side of the data bar.

Methods
ノ Expand table

getBorderColor() HTML color code representing the color of the border line, in the form
#RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange"). Value is
"" (an empty string) if no border is present or set.

getFillColor() HTML color code representing the fill color, in the form #RRGGBB (e.g.,
"FFA500") or as a named HTML color (e.g., "orange").

getGradientFill() Specifies if the data bar has a gradient.

setBorder HTML color code representing the color of the border line, in the form
Color(border #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange"). Value is
Color) "" (an empty string) if no border is present or set.

setFillColor(fill HTML color code representing the fill color, in the form #RRGGBB (e.g.,
Color) "FFA500") or as a named HTML color (e.g., "orange").

setGradient Specifies if the data bar has a gradient.


Fill(gradientFill)

Method Details

getBorderColor()
HTML color code representing the color of the border line, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange"). Value is "" (an empty
string) if no border is present or set.

TypeScript

getBorderColor(): string;
Returns
string

getFillColor()
HTML color code representing the fill color, in the form #RRGGBB (e.g., "FFA500") or
as a named HTML color (e.g., "orange").

TypeScript

getFillColor(): string;

Returns
string

getGradientFill()
Specifies if the data bar has a gradient.

TypeScript

getGradientFill(): boolean;

Returns
boolean

setBorderColor(borderColor)
HTML color code representing the color of the border line, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange"). Value is "" (an empty
string) if no border is present or set.

TypeScript

setBorderColor(borderColor: string): void;

Parameters
borderColor string
Returns
void

setFillColor(fillColor)
HTML color code representing the fill color, in the form #RRGGBB (e.g., "FFA500") or
as a named HTML color (e.g., "orange").

TypeScript

setFillColor(fillColor: string): void;

Parameters
fillColor string

Returns
void

setGradientFill(gradientFill)
Specifies if the data bar has a gradient.

TypeScript

setGradientFill(gradientFill: boolean): void;

Parameters
gradientFill boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
Select a link to provide feedback:
The source for this content can
be found on GitHub, where you  Open a documentation issue
can also create and review
issues and pull requests. For  Provide product feedback
more information, see our
contributor guide.
ExcelScript.ConditionalDataBarRule
interface
Reference
Package: ExcelScript

Represents a rule-type for a data bar.

Remarks

Examples

TypeScript

/**
* This script creates data bar conditional formatting on the selected
range.
* The scale of the data bar goes from 0 to 1000.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected range.
const selected = workbook.getSelectedRange();

// Create new conditional formatting on the range.


const format =
selected.addConditionalFormat(ExcelScript.ConditionalFormatType.dataBar);
const dataBarFormat: ExcelScript.DataBarConditionalFormat =
format.getDataBar();

// Set the lower bound of the data bar formatting to be 0.


const lowerBound: ExcelScript.ConditionalDataBarRule = {
type: ExcelScript.ConditionalFormatRuleType.number,
formula: "0"
};
dataBarFormat.setLowerBoundRule(lowerBound);

// Set the upper bound of the data bar formatting to be 1000.


const upperBound: ExcelScript.ConditionalDataBarRule = {
type: ExcelScript.ConditionalFormatRuleType.number,
formula: "1000"
};
dataBarFormat.setUpperBoundRule(upperBound);
}

Properties
ノ Expand table

formula The formula, if required, on which to evaluate the data bar rule.

type The type of rule for the data bar.

Property Details

formula
The formula, if required, on which to evaluate the data bar rule.

TypeScript

formula?: string;

Property Value
string

type
The type of rule for the data bar.

TypeScript

type: ConditionalFormatRuleType;

Property Value
ExcelScript.ConditionalFormatRuleType

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.ConditionalFormat interface
Reference
Package: ExcelScript

An object encapsulating a conditional format's range, format, rule, and other properties.

Methods
ノ Expand table

delete() Deletes this conditional format.

getCellValue() Returns the cell value conditional format properties if the current conditional
format is a CellValue type.

getColorScale() Returns the color scale conditional format properties if the current conditional
format is a ColorScale type.

getCustom() Returns the custom conditional format properties if the current conditional
format is a custom type.

getDataBar() Returns the data bar properties if the current conditional format is a data bar.

getIconSet() Returns the icon set conditional format properties if the current conditional
format is an IconSet type.

getId() The priority of the conditional format in the current


ConditionalFormatCollection .

getPreset() Returns the preset criteria conditional format. See


ExcelScript.PresetCriteriaConditionalFormat for more details.

getPriority() The priority (or index) within the conditional format collection that this
conditional format currently exists in. Changing this also changes other
conditional formats' priorities, to allow for a contiguous priority order. Use a
negative priority to begin from the back. Priorities greater than the bounds will
get and set to the maximum (or minimum if negative) priority. Also note that if
you change the priority, you have to re-fetch a new copy of the object at that
new priority location if you want to make further changes to it.

getRange() Returns the range to which the conditional format is applied. If the conditional
format is applied to multiple ranges, then this method returns undefined .

getRanges() Returns the RangeAreas , comprising one or more rectangular ranges, to which
the conditional format is applied.
getStopIfTrue() If the conditions of this conditional format are met, no lower-priority formats
shall take effect on that cell. Value is null on data bars, icon sets, and color
scales as there's no concept of StopIfTrue for these.

getText Returns the specific text conditional format properties if the current conditional
Comparison() format is a text type. For example, to format cells matching the word "Text".

getTopBottom() Returns the top/bottom conditional format properties if the current conditional
format is a TopBottom type. For example, to format the top 10% or bottom 10
items.

getType() A type of conditional format. Only one can be set at a time.

set The priority (or index) within the conditional format collection that this
Priority(priority) conditional format currently exists in. Changing this also changes other
conditional formats' priorities, to allow for a contiguous priority order. Use a
negative priority to begin from the back. Priorities greater than the bounds will
get and set to the maximum (or minimum if negative) priority. Also note that if
you change the priority, you have to re-fetch a new copy of the object at that
new priority location if you want to make further changes to it.

setStop If the conditions of this conditional format are met, no lower-priority formats
IfTrue(stop shall take effect on that cell. Value is null on data bars, icon sets, and color
IfTrue) scales as there's no concept of StopIfTrue for these.

Method Details

delete()
Deletes this conditional format.

TypeScript

delete(): void;

Returns
void

getCellValue()
Returns the cell value conditional format properties if the current conditional format
is a CellValue type.
TypeScript

getCellValue(): CellValueConditionalFormat | undefined;

Returns
ExcelScript.CellValueConditionalFormat | undefined

Examples

TypeScript

/**
* This script applies conditional formatting to a range.
* That formatting is conditional upon the cell's numerical value.
* Any value between 50 and 75 will have the cell fill color changed and
the font made italic.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range to format.
const sheet = workbook.getActiveWorksheet();
const ratingColumn = sheet.getRange("D2:D20");

// Add cell value conditional formatting.


const cellValueConditionalFormatting =

ratingColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.cellV
alue).getCellValue();

// Create the condition, in this case when the cell value is between 50
and 75.
let rule: ExcelScript.ConditionalCellValueRule = {
formula1: "50",
formula2: "75",
operator: ExcelScript.ConditionalCellValueOperator.between
};
cellValueConditionalFormatting.setRule(rule);

// Set the format to apply when the condition is met.


let format = cellValueConditionalFormatting.getFormat();
format.getFill().setColor("yellow");
format.getFont().setItalic(true);

getColorScale()
Returns the color scale conditional format properties if the current conditional
format is a ColorScale type.

TypeScript

getColorScale(): ColorScaleConditionalFormat | undefined;

Returns
ExcelScript.ColorScaleConditionalFormat | undefined

Examples

TypeScript

/**
* This script applies a red, white, and blue color scale to the selected
range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected range.
let selectedRange = workbook.getSelectedRange();

// Create a new conditional formatting object by adding one to the


range.
let conditionalFormatting =
selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.colo
rScale);

// Set the colors for the three parts of the scale: minimum, midpoint,
and maximum.
conditionalFormatting.getColorScale().setCriteria({
minimum: {
color:"#F8696B", /* A pale red. */
type:ExcelScript.ConditionalFormatColorCriterionType.lowestValue
},
midpoint: {
color: "#FCFCFF", /* Slightly off-white. */

formula:'=50',type:ExcelScript.ConditionalFormatColorCriterionType.percen
tile
},
maximum: {
color: "#5A8AC6", /* A pale blue. */
type:ExcelScript.ConditionalFormatColorCriterionType.highestValue
}
});
}
getCustom()
Returns the custom conditional format properties if the current conditional format is
a custom type.

TypeScript

getCustom(): CustomConditionalFormat | undefined;

Returns
ExcelScript.CustomConditionalFormat | undefined

Examples

TypeScript

/**
* This script applies a custom conditional formatting to the selected
range.
* A light-green fill is applied to a cell if the value is larger than
the value in the row's previous column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected cells.
let selectedRange = workbook.getSelectedRange();

// Apply a rule for positive change from the previous column.


let positiveChange =
selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.cust
om);

positiveChange.getCustom().getFormat().getFill().setColor("lightgreen");

positiveChange.getCustom().getRule().setFormula(`=${selectedRange.getCell
(0, 0).getAddress()}>${selectedRange.getOffsetRange(0, -1).getCell(0,
0).getAddress()}`);
}

getDataBar()
Returns the data bar properties if the current conditional format is a data bar.

TypeScript

getDataBar(): DataBarConditionalFormat | undefined;


Returns
ExcelScript.DataBarConditionalFormat | undefined

Examples

TypeScript

/**
* This script creates data bar conditional formatting on the selected
range.
* The scale of the data bar goes from 0 to 1000.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected range.
const selected = workbook.getSelectedRange();

// Create new conditional formatting on the range.


const format =
selected.addConditionalFormat(ExcelScript.ConditionalFormatType.dataBar);
const dataBarFormat = format.getDataBar();

// Set the lower bound of the data bar formatting to be 0.


const lowerBound: ExcelScript.ConditionalDataBarRule = {
type: ExcelScript.ConditionalFormatRuleType.number,
formula: "0"
};
dataBarFormat.setLowerBoundRule(lowerBound);

// Set the upper bound of the data bar formatting to be 1000.


const upperBound: ExcelScript.ConditionalDataBarRule = {
type: ExcelScript.ConditionalFormatRuleType.number,
formula: "1000"
};
dataBarFormat.setUpperBoundRule(upperBound);
}

getIconSet()
Returns the icon set conditional format properties if the current conditional format is
an IconSet type.

TypeScript

getIconSet(): IconSetConditionalFormat | undefined;

Returns
ExcelScript.IconSetConditionalFormat | undefined

Examples

TypeScript

/**
* This script applies icon set conditional formatting to a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range "A1:A5" on the current worksheet.
const sheet = workbook.getActiveWorksheet();
const range = sheet.getRange("A1:A5");

// Create icon set conditional formatting on the range.


const conditionalFormatting =
range.addConditionalFormat(ExcelScript.ConditionalFormatType.iconSet);

// Use the "3 Traffic Lights (Unrimmed)" set.

conditionalFormatting.getIconSet().setStyle(ExcelScript.IconSet.threeTraf
ficLights1);

// Set the criteria to use a different icon for the bottom, middle, and
top thirds of the values in the range.
conditionalFormatting.getIconSet().setCriteria([
{

formula:'=0',operator:ExcelScript.ConditionalIconCriterionOperator.greate
rThanOrEqual,
type:ExcelScript.ConditionalFormatIconRuleType.percent
},
{

formula:'=33',operator:ExcelScript.ConditionalIconCriterionOperator.great
erThanOrEqual,
type:ExcelScript.ConditionalFormatIconRuleType.percent},
{

formula:'=67',operator:ExcelScript.ConditionalIconCriterionOperator.great
erThanOrEqual,
type:ExcelScript.ConditionalFormatIconRuleType.percent
}]);
}

getId()
The priority of the conditional format in the current ConditionalFormatCollection .

TypeScript
getId(): string;

Returns
string

getPreset()
Returns the preset criteria conditional format. See
ExcelScript.PresetCriteriaConditionalFormat for more details.

TypeScript

getPreset(): PresetCriteriaConditionalFormat | undefined;

Returns
ExcelScript.PresetCriteriaConditionalFormat | undefined

Examples

TypeScript

/**
* This script applies a conditional format that uses a preset criterion.
* Any cell in row 1 will have the color fill set to green if it is a
duplicate value
* (of anything else in row 1).
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range for row 1.
const sheet = workbook.getActiveWorksheet();
const formattedRange = sheet.getRange("1:1");

// Add new conditional formatting to that range.


const conditionalFormat = formattedRange.addConditionalFormat(
ExcelScript.ConditionalFormatType.presetCriteria);

// Set the conditional formatting to apply a green fill.


const presetFormat = conditionalFormat.getPreset();
presetFormat.getFormat().getFill().setColor("green");

// Set a rule to apply the conditional format when values are


duplicated in the range.
const duplicateRule: ExcelScript.ConditionalPresetCriteriaRule = {
criterion:
ExcelScript.ConditionalFormatPresetCriterion.duplicateValues
};
presetFormat.setRule(duplicateRule);
}

getPriority()
The priority (or index) within the conditional format collection that this conditional
format currently exists in. Changing this also changes other conditional formats'
priorities, to allow for a contiguous priority order. Use a negative priority to begin
from the back. Priorities greater than the bounds will get and set to the maximum (or
minimum if negative) priority. Also note that if you change the priority, you have to
re-fetch a new copy of the object at that new priority location if you want to make
further changes to it.

TypeScript

getPriority(): number;

Returns
number

getRange()
Returns the range to which the conditional format is applied. If the conditional
format is applied to multiple ranges, then this method returns undefined .

TypeScript

getRange(): Range;

Returns
ExcelScript.Range

getRanges()
Returns the RangeAreas , comprising one or more rectangular ranges, to which the
conditional format is applied.
TypeScript

getRanges(): RangeAreas;

Returns
ExcelScript.RangeAreas

getStopIfTrue()
If the conditions of this conditional format are met, no lower-priority formats shall
take effect on that cell. Value is null on data bars, icon sets, and color scales as
there's no concept of StopIfTrue for these.

TypeScript

getStopIfTrue(): boolean;

Returns
boolean

getTextComparison()
Returns the specific text conditional format properties if the current conditional
format is a text type. For example, to format cells matching the word "Text".

TypeScript

getTextComparison(): TextConditionalFormat | undefined;

Returns
ExcelScript.TextConditionalFormat | undefined

Examples

TypeScript

/**
* This script adds conditional formatting to the first column in the
worksheet.
* This formatting gives the cells a green fill if they have text
starting with "Excel".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first column in the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const firstColumn = currentSheet.getRange("A:A");

// Add conditional formatting based on the text in the cells.


const textConditionFormat =

firstColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.contai
nsText).getTextComparison();

// Set the conditional format to provide a green fill.


textConditionFormat.getFormat().getFill().setColor("green");

// Apply the condition rule that the text begins with "Excel".
const textRule: ExcelScript.ConditionalTextComparisonRule = {
operator: ExcelScript.ConditionalTextOperator.beginsWith,
text: "Excel"
};
textConditionFormat.setRule(textRule);
}

getTopBottom()
Returns the top/bottom conditional format properties if the current conditional
format is a TopBottom type. For example, to format the top 10% or bottom 10 items.

TypeScript

getTopBottom(): TopBottomConditionalFormat | undefined;

Returns
ExcelScript.TopBottomConditionalFormat | undefined

Examples

TypeScript

/**
* This script applies top/bottom conditional formatting to a range.
* The top 2 values in the range will have the cell fill color changed to
green.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range to format.
const sheet = workbook.getWorksheet("TopBottom");
const dataRange = sheet.getRange("B2:D5");

// Set the fill color to green for the top 2 values in the range.
const topBottomFormat = dataRange.addConditionalFormat(
ExcelScript.ConditionalFormatType.topBottom).getTopBottom();
topBottomFormat.getFormat().getFill().setColor("green");
topBottomFormat.setRule({
rank: 2, /* The numeric threshold. */
type: ExcelScript.ConditionalTopBottomCriterionType.topItems /* The
type of the top/bottom condition. */
});
}

getType()
A type of conditional format. Only one can be set at a time.

TypeScript

getType(): ConditionalFormatType;

Returns
ExcelScript.ConditionalFormatType

setPriority(priority)
The priority (or index) within the conditional format collection that this conditional
format currently exists in. Changing this also changes other conditional formats'
priorities, to allow for a contiguous priority order. Use a negative priority to begin
from the back. Priorities greater than the bounds will get and set to the maximum (or
minimum if negative) priority. Also note that if you change the priority, you have to
re-fetch a new copy of the object at that new priority location if you want to make
further changes to it.

TypeScript

setPriority(priority: number): void;

Parameters
priority number
Returns
void

setStopIfTrue(stopIfTrue)
If the conditions of this conditional format are met, no lower-priority formats shall
take effect on that cell. Value is null on data bars, icon sets, and color scales as
there's no concept of StopIfTrue for these.

TypeScript

setStopIfTrue(stopIfTrue: boolean): void;

Parameters
stopIfTrue boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalFormatRule
interface
Reference
Package: ExcelScript

Represents a rule, for all traditional rule/format pairings.

Remarks

Examples

TypeScript

/**
* This script applies a custom conditional formatting to the selected
range.
* A light-green fill is applied to a cell if the value is larger than the
value in the row's previous column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected cells.
let selectedRange = workbook.getSelectedRange();

// Apply a rule for positive change from the previous column.


let positiveChange: ExcelScript.ConditionalFormat =
selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.custom)
;

// Set the conditional format to be a lightgreen fill.


let positiveCustom: ExcelScript.CustomConditionalFormat =
positiveChange.getCustom();
positiveCustom.getFormat().getFill().setColor("lightgreen");

// Set the conditional rule to be if there is positive change across the


row.
let positiveRule: ExcelScript.ConditionalFormatRule =
positiveCustom.getRule();
positiveRule.setFormula(`=${selectedRange.getCell(0,
0).getAddress()}>${selectedRange.getOffsetRange(0, -1).getCell(0,
0).getAddress()}`);
}

Methods
ノ Expand table

getFormula() The formula, if required, on which to evaluate the conditional format


rule.

getFormulaLocal() The formula, if required, on which to evaluate the conditional format


rule in the user's language.

setFormula(formula) The formula, if required, on which to evaluate the conditional format


rule.

setFormulaLocal(formula The formula, if required, on which to evaluate the conditional format


Local) rule in the user's language.

Method Details

getFormula()
The formula, if required, on which to evaluate the conditional format rule.

TypeScript

getFormula(): string;

Returns
string

getFormulaLocal()
The formula, if required, on which to evaluate the conditional format rule in the
user's language.

TypeScript

getFormulaLocal(): string;

Returns
string

setFormula(formula)
The formula, if required, on which to evaluate the conditional format rule.

TypeScript

setFormula(formula: string): void;

Parameters
formula string

Returns
void

setFormulaLocal(formulaLocal)
The formula, if required, on which to evaluate the conditional format rule in the
user's language.

TypeScript

setFormulaLocal(formulaLocal: string): void;

Parameters
formulaLocal string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalIconCriterion
interface
Reference
Package: ExcelScript

Represents an icon criterion which contains a type, value, an operator, and an optional
custom icon, if not using an icon set.

Remarks

Examples

TypeScript

/**
* This script applies icon set conditional formatting to a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range "A1:A5" on the current worksheet.
const sheet = workbook.getActiveWorksheet();
const range = sheet.getRange("A1:A5");

// Create icon set conditional formatting on the range.


const conditionalFormatting =
range.addConditionalFormat(ExcelScript.ConditionalFormatType.iconSet);

// Use the "3 Traffic Lights (Unrimmed)" set.

conditionalFormatting.getIconSet().setStyle(ExcelScript.IconSet.threeTraffic
Lights1);

// Set the criteria to use a different icon for the bottom, middle, and
top thirds of the values in the range.
const criteria: ExcelScript.ConditionalIconCriterion[] = [
{
formula: '=0', operator:
ExcelScript.ConditionalIconCriterionOperator.greaterThanOrEqual,
type: ExcelScript.ConditionalFormatIconRuleType.percent
},
{
formula: '=33', operator:
ExcelScript.ConditionalIconCriterionOperator.greaterThanOrEqual,
type: ExcelScript.ConditionalFormatIconRuleType.percent
},
{
formula: '=67', operator:
ExcelScript.ConditionalIconCriterionOperator.greaterThanOrEqual,
type: ExcelScript.ConditionalFormatIconRuleType.percent
}];
conditionalFormatting.getIconSet().setCriteria(criteria);
}

Properties
ノ Expand table

custom The custom icon for the current criterion, if different from the default icon set, else
Icon null will be returned.

formula A number or a formula depending on the type.

operator greaterThan or greaterThanOrEqual for each of the rule types for the icon
conditional format.

type What the icon conditional formula should be based on.

Property Details

customIcon
The custom icon for the current criterion, if different from the default icon set, else
null will be returned.

TypeScript

customIcon?: Icon;

Property Value
ExcelScript.Icon

formula
A number or a formula depending on the type.

TypeScript

formula: string;
Property Value
string

operator
greaterThan or greaterThanOrEqual for each of the rule types for the icon

conditional format.

TypeScript

operator: ConditionalIconCriterionOperator;

Property Value
ExcelScript.ConditionalIconCriterionOperator

type
What the icon conditional formula should be based on.

TypeScript

type: ConditionalFormatIconRuleType;

Property Value
ExcelScript.ConditionalFormatIconRuleType

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalPresetCriteria
Rule interface
Reference
Package: ExcelScript

Represents the preset criteria conditional format rule.

Remarks

Examples

TypeScript

/**
* This script applies a conditional format that uses a preset criterion.
* Any cell in row 1 will have the color fill set to green if it is a
duplicate value
* (of anything else in row 1).
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range for row 1.
const sheet = workbook.getActiveWorksheet();
const formattedRange = sheet.getRange("1:1");

// Add new conditional formatting to that range.


const conditionalFormat = formattedRange.addConditionalFormat(
ExcelScript.ConditionalFormatType.presetCriteria);

// Set the conditional formatting to apply a green fill.


const presetFormat = conditionalFormat.getPreset();
presetFormat.getFormat().getFill().setColor("green");

// Set a rule to apply the conditional format when values are duplicated
in the range.
const duplicateRule: ExcelScript.ConditionalPresetCriteriaRule = {
criterion: ExcelScript.ConditionalFormatPresetCriterion.duplicateValues
};
presetFormat.setRule(duplicateRule);
}

Properties
ノ Expand table
criterion The criterion of the conditional format.

Property Details

criterion
The criterion of the conditional format.

TypeScript

criterion: ConditionalFormatPresetCriterion;

Property Value
ExcelScript.ConditionalFormatPresetCriterion

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalRangeBorder
interface
Reference
Package: ExcelScript

Represents the border of an object.

Methods
ノ Expand table

getColor() HTML color code representing the color of the border line, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange").

getSide Constant value that indicates the specific side of the border. See
Index() ExcelScript.ConditionalRangeBorderIndex for details.

getStyle() One of the constants of line style specifying the line style for the border. See
ExcelScript.BorderLineStyle for details.

set HTML color code representing the color of the border line, in the form #RRGGBB
Color(color) (e.g., "FFA500") or as a named HTML color (e.g., "orange").

set One of the constants of line style specifying the line style for the border. See
Style(style) ExcelScript.BorderLineStyle for details.

Method Details

getColor()
HTML color code representing the color of the border line, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange").

TypeScript

getColor(): string;

Returns
string
getSideIndex()
Constant value that indicates the specific side of the border. See
ExcelScript.ConditionalRangeBorderIndex for details.

TypeScript

getSideIndex(): ConditionalRangeBorderIndex;

Returns
ExcelScript.ConditionalRangeBorderIndex

getStyle()
One of the constants of line style specifying the line style for the border. See
ExcelScript.BorderLineStyle for details.

TypeScript

getStyle(): ConditionalRangeBorderLineStyle;

Returns
ExcelScript.ConditionalRangeBorderLineStyle

setColor(color)
HTML color code representing the color of the border line, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange").

TypeScript

setColor(color: string): void;

Parameters
color string

Returns
void

setStyle(style)
One of the constants of line style specifying the line style for the border. See
ExcelScript.BorderLineStyle for details.

TypeScript

setStyle(style: ConditionalRangeBorderLineStyle): void;

Parameters
style ExcelScript.ConditionalRangeBorderLineStyle

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalRangeFill
interface
Reference
Package: ExcelScript

Represents the background of a conditional range object.

Remarks

Examples

TypeScript

/**
* This script applies cell value conditional formatting to a range.
* Any value less than 60 will have the cell's fill color changed and the
font made italic.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range to format.
const selectedRange = workbook.getSelectedRange();

// Add cell value conditional formatting.


const cellValueConditionalFormatting =

selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.cellVal
ue).getCellValue();

// Create the condition, in this case when the cell value is less than 60.
const rule: ExcelScript.ConditionalCellValueRule = {
formula1: "60",
operator: ExcelScript.ConditionalCellValueOperator.lessThan
};
cellValueConditionalFormatting.setRule(rule);

// Set the format to apply when the condition is met.


const format: ExcelScript.ConditionalRangeFormat =
cellValueConditionalFormatting.getFormat();
const fill: ExcelScript.ConditionalRangeFill = format.getFill();
const font: ExcelScript.ConditionalRangeFont = format.getFont();
fill.setColor("yellow");
font.setItalic(true);
}
Methods
ノ Expand table

clear() Resets the fill.

getColor() HTML color code representing the color of the fill, in the form #RRGGBB (e.g.,
"FFA500") or as a named HTML color (e.g., "orange").

set HTML color code representing the color of the fill, in the form #RRGGBB (e.g.,
Color(color) "FFA500") or as a named HTML color (e.g., "orange").

Method Details

clear()
Resets the fill.

TypeScript

clear(): void;

Returns
void

getColor()
HTML color code representing the color of the fill, in the form #RRGGBB (e.g.,
"FFA500") or as a named HTML color (e.g., "orange").

TypeScript

getColor(): string;

Returns
string

setColor(color)
HTML color code representing the color of the fill, in the form #RRGGBB (e.g.,
"FFA500") or as a named HTML color (e.g., "orange").

TypeScript

setColor(color: string): void;

Parameters
color string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalRangeFont
interface
Reference
Package: ExcelScript

This object represents the font attributes (font style, color, etc.) for an object.

Remarks

Examples

TypeScript

/**
* This script applies cell value conditional formatting to a range.
* Any value less than 60 will have the cell's fill color changed and the
font made italic.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range to format.
const selectedRange = workbook.getSelectedRange();

// Add cell value conditional formatting.


const cellValueConditionalFormatting =

selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.cellVal
ue).getCellValue();

// Create the condition, in this case when the cell value is less than 60.
const rule: ExcelScript.ConditionalCellValueRule = {
formula1: "60",
operator: ExcelScript.ConditionalCellValueOperator.lessThan
};
cellValueConditionalFormatting.setRule(rule);

// Set the format to apply when the condition is met.


const format: ExcelScript.ConditionalRangeFormat =
cellValueConditionalFormatting.getFormat();
const fill: ExcelScript.ConditionalRangeFill = format.getFill();
const font: ExcelScript.ConditionalRangeFont = format.getFont();
fill.setColor("yellow");
font.setItalic(true);
}
Methods
ノ Expand table

clear() Resets the font formats.

getBold() Specifies if the font is bold.

getColor() HTML color code representation of the text color (e.g., #FF0000
represents Red).

getItalic() Specifies if the font is italic.

getStrikethrough() Specifies the strikethrough status of the font.

getUnderline() The type of underline applied to the font. See


ExcelScript.ConditionalRangeFontUnderlineStyle for details.

setBold(bold) Specifies if the font is bold.

setColor(color) HTML color code representation of the text color (e.g., #FF0000
represents Red).

setItalic(italic) Specifies if the font is italic.

set Specifies the strikethrough status of the font.


Strikethrough(strikethrough)

setUnderline(underline) The type of underline applied to the font. See


ExcelScript.ConditionalRangeFontUnderlineStyle for details.

Method Details

clear()
Resets the font formats.

TypeScript

clear(): void;

Returns
void
getBold()
Specifies if the font is bold.

TypeScript

getBold(): boolean;

Returns
boolean

getColor()
HTML color code representation of the text color (e.g., #FF0000 represents Red).

TypeScript

getColor(): string;

Returns
string

getItalic()
Specifies if the font is italic.

TypeScript

getItalic(): boolean;

Returns
boolean

getStrikethrough()
Specifies the strikethrough status of the font.

TypeScript
getStrikethrough(): boolean;

Returns
boolean

getUnderline()
The type of underline applied to the font. See
ExcelScript.ConditionalRangeFontUnderlineStyle for details.

TypeScript

getUnderline(): ConditionalRangeFontUnderlineStyle;

Returns
ExcelScript.ConditionalRangeFontUnderlineStyle

setBold(bold)
Specifies if the font is bold.

TypeScript

setBold(bold: boolean): void;

Parameters
bold boolean

Returns
void

setColor(color)
HTML color code representation of the text color (e.g., #FF0000 represents Red).

TypeScript
setColor(color: string): void;

Parameters
color string

Returns
void

setItalic(italic)
Specifies if the font is italic.

TypeScript

setItalic(italic: boolean): void;

Parameters
italic boolean

Returns
void

setStrikethrough(strikethrough)
Specifies the strikethrough status of the font.

TypeScript

setStrikethrough(strikethrough: boolean): void;

Parameters
strikethrough boolean

Returns
void
setUnderline(underline)
The type of underline applied to the font. See
ExcelScript.ConditionalRangeFontUnderlineStyle for details.

TypeScript

setUnderline(underline: ConditionalRangeFontUnderlineStyle): void;

Parameters
underline ExcelScript.ConditionalRangeFontUnderlineStyle

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalRangeFormat
interface
Reference
Package: ExcelScript

A format object encapsulating the conditional formats range's font, fill, borders, and
other properties.

Remarks

Examples

TypeScript

/**
* This script applies cell value conditional formatting to a range.
* Any value less than 60 will have the cell's fill color changed and the
font made italic.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range to format.
const selectedRange = workbook.getSelectedRange();

// Add cell value conditional formatting.


const cellValueConditionalFormatting =

selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.cellVal
ue).getCellValue();

// Create the condition, in this case when the cell value is less than 60.
const rule: ExcelScript.ConditionalCellValueRule = {
formula1: "60",
operator: ExcelScript.ConditionalCellValueOperator.lessThan
};
cellValueConditionalFormatting.setRule(rule);

// Set the format to apply when the condition is met.


const format: ExcelScript.ConditionalRangeFormat =
cellValueConditionalFormatting.getFormat();
format.getFill().setColor("yellow");
format.getFont().setItalic(true);
}

Methods
ノ Expand table

getBorders() Collection of border objects that apply to the overall conditional


format range.

getConditionalRange Gets a border object using its name.


Border(index)

getConditionalRangeBorder Gets the bottom border.


Bottom()

getConditionalRangeBorder Gets the left border.


Left()

getConditionalRangeBorder Gets the right border.


Right()

getConditionalRangeBorder Gets the top border.


Top()

getFill() Returns the fill object defined on the overall conditional format
range.

getFont() Returns the font object defined on the overall conditional format
range.

getNumberFormat() Represents Excel's number format code for the given range.
Cleared if null is passed in.

setNumberFormat(number Represents Excel's number format code for the given range.
Format) Cleared if null is passed in.

Method Details

getBorders()
Collection of border objects that apply to the overall conditional format range.

TypeScript

getBorders(): ConditionalRangeBorder[];

Returns
ExcelScript.ConditionalRangeBorder[]
getConditionalRangeBorder(index)
Gets a border object using its name.

TypeScript

getConditionalRangeBorder(
index: ConditionalRangeBorderIndex
): ConditionalRangeBorder;

Parameters
index ExcelScript.ConditionalRangeBorderIndex
Index value of the border object to be retrieved. See
ExcelScript.ConditionalRangeBorderIndex for details.

Returns
ExcelScript.ConditionalRangeBorder

getConditionalRangeBorderBottom()
Gets the bottom border.

TypeScript

getConditionalRangeBorderBottom(): ConditionalRangeBorder;

Returns
ExcelScript.ConditionalRangeBorder

getConditionalRangeBorderLeft()
Gets the left border.

TypeScript

getConditionalRangeBorderLeft(): ConditionalRangeBorder;

Returns
ExcelScript.ConditionalRangeBorder

getConditionalRangeBorderRight()
Gets the right border.

TypeScript

getConditionalRangeBorderRight(): ConditionalRangeBorder;

Returns
ExcelScript.ConditionalRangeBorder

getConditionalRangeBorderTop()
Gets the top border.

TypeScript

getConditionalRangeBorderTop(): ConditionalRangeBorder;

Returns
ExcelScript.ConditionalRangeBorder

getFill()
Returns the fill object defined on the overall conditional format range.

TypeScript

getFill(): ConditionalRangeFill;

Returns
ExcelScript.ConditionalRangeFill

getFont()
Returns the font object defined on the overall conditional format range.
TypeScript

getFont(): ConditionalRangeFont;

Returns
ExcelScript.ConditionalRangeFont

getNumberFormat()
Represents Excel's number format code for the given range. Cleared if null is passed
in.

TypeScript

getNumberFormat(): string;

Returns
string

setNumberFormat(numberFormat)
Represents Excel's number format code for the given range. Cleared if null is passed
in.

TypeScript

setNumberFormat(numberFormat: string): void;

Parameters
numberFormat string

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ConditionalTextComparison
Rule interface
Reference
Package: ExcelScript

Represents a cell value conditional format rule.

Remarks

Examples

TypeScript

/**
* This script adds conditional formatting to the first column in the
worksheet.
* This formatting gives the cells a green fill if they have text starting
with "Excel".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first column in the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const firstColumn = currentSheet.getRange("A:A");

// Add conditional formatting based on the text in the cells.


const textConditionFormat =

firstColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.containsT
ext).getTextComparison();

// Set the conditional format to provide a green fill.


textConditionFormat.getFormat().getFill().setColor("green");

// Apply the condition rule that the text begins with "Excel".
const textRule: ExcelScript.ConditionalTextComparisonRule = {
operator: ExcelScript.ConditionalTextOperator.beginsWith,
text: "Excel"
};
textConditionFormat.setRule(textRule);
}

Properties
ノ Expand table

operator The operator of the text conditional format.

text The text value of the conditional format.

Property Details

operator
The operator of the text conditional format.

TypeScript

operator: ConditionalTextOperator;

Property Value
ExcelScript.ConditionalTextOperator

text
The text value of the conditional format.

TypeScript

text: string;

Property Value
string

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.ConditionalTopBottomRule
interface
Reference
Package: ExcelScript

Represents the rule of the top/bottom conditional format.

Remarks

Examples

TypeScript

/**
* This sample applies conditional formatting to the currently used range in
the worksheet.
* The conditional formatting is a pink fill for the 5 lowest values.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get the used range in the worksheet.


let range = selectedSheet.getUsedRange();

// Set the fill color to pink for the lowest 5 values in the range.
let conditionalFormat =
range.addConditionalFormat(ExcelScript.ConditionalFormatType.topBottom)
conditionalFormat.getTopBottom().getFormat().getFill().setColor("pink");
conditionalFormat.getTopBottom().setRule({
rank: 5, /* The numerical threshold. */
type: ExcelScript.ConditionalTopBottomCriterionType.bottomItems /* The
type of the top/bottom condition. */
});
}

Properties
ノ Expand table

rank The rank between 1 and 1000 for numeric ranks or 1 and 100 for percent ranks.

type Format values based on the top or bottom rank.


Property Details

rank
The rank between 1 and 1000 for numeric ranks or 1 and 100 for percent ranks.

TypeScript

rank: number;

Property Value
number

type
Format values based on the top or bottom rank.

TypeScript

type: ConditionalTopBottomCriterionType;

Property Value
ExcelScript.ConditionalTopBottomCriterionType

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CultureInfo interface
Reference
Package: ExcelScript

Provides information based on current system culture settings. This includes the culture
names, number formatting, and other culturally dependent settings.

Remarks

Examples

TypeScript

/**
* This script sets the value of a cell to a date string for January 2,
2023.
* It writes the day or month first in the string based on system settings.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell in the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0,0);

// Get the date format.


const cultureInfo : ExcelScript.CultureInfo =
workbook.getApplication().getCultureInfo();
const systemDateTimeFormat : ExcelScript.DatetimeFormatInfo =
cultureInfo.getDatetimeFormat();
const shortDatePattern : string =
systemDateTimeFormat.getShortDatePattern();

// Determine if the date should start with the month or day.


if (shortDatePattern.startsWith("m")) {
cell.setValue("1/2/2023");
} else {
cell.setValue("2/1/2023");
}
}

Methods
ノ Expand table

getDatetime Defines the culturally appropriate format of displaying date and time. This is
Format() based on current system culture settings.
getName() Gets the culture name in the format languagecode2-country/regioncode2 (e.g.,
"zh-cn" or "en-us"). This is based on current system settings.

getNumber Defines the culturally appropriate format of displaying numbers. This is based
Format() on current system culture settings.

Method Details

getDatetimeFormat()
Defines the culturally appropriate format of displaying date and time. This is based
on current system culture settings.

TypeScript

getDatetimeFormat(): DatetimeFormatInfo;

Returns
ExcelScript.DatetimeFormatInfo

getName()
Gets the culture name in the format languagecode2-country/regioncode2 (e.g., "zh-
cn" or "en-us"). This is based on current system settings.

TypeScript

getName(): string;

Returns
string

getNumberFormat()
Defines the culturally appropriate format of displaying numbers. This is based on
current system culture settings.

TypeScript
getNumberFormat(): NumberFormatInfo;

Returns
ExcelScript.NumberFormatInfo

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CustomConditionalFormat
interface
Reference
Package: ExcelScript

Represents a custom conditional format type.

Remarks

Examples

TypeScript

/**
* This script applies a custom three-color conditional formatting to the
selected range.
* The three colors represent positive, negative, or no changes from the
values in the previous column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected cells.
let selectedRange = workbook.getSelectedRange();

// Apply a rule for positive change from the previous column.


let positiveChange: ExcelScript.ConditionalFormat =
selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.custom)
;
let positiveCustom: ExcelScript.CustomConditionalFormat =
positiveChange.getCustom();
positiveCustom.getFormat().getFill().setColor("lightgreen");
positiveCustom.getRule().setFormula(`=${selectedRange.getCell(0,
0).getAddress()}>${selectedRange.getOffsetRange(0, -1).getCell(0,
0).getAddress()}`);

// Apply a rule for negative change from the previous column.


let negativeChange: ExcelScript.ConditionalFormat =
selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.custom)
;
let negativeCustom: ExcelScript.CustomConditionalFormat =
negativeChange.getCustom();
negativeCustom.getFormat().getFill().setColor("pink");
negativeCustom.getRule().setFormula(`=${selectedRange.getCell(0,
0).getAddress()}<${selectedRange.getOffsetRange(0, -1).getCell(0,
0).getAddress()}`);

// Apply a rule for no change from the previous column.


let sameChange: ExcelScript.ConditionalFormat =
selectedRange.addConditionalFormat(ExcelScript.ConditionalFormatType.custom)
;
let sameCustom: ExcelScript.CustomConditionalFormat =
sameChange.getCustom();
sameCustom.getFormat().getFill().setColor("lightyellow");
sameCustom.getRule().setFormula(`=${selectedRange.getCell(0,
0).getAddress()}=${selectedRange.getOffsetRange(0, -1).getCell(0,
0).getAddress()}`);
}

Methods
ノ Expand table

get Returns a format object, encapsulating the conditional formats font, fill, borders, and
Format() other properties.

getRule() Specifies the Rule object on this conditional format.

Method Details

getFormat()
Returns a format object, encapsulating the conditional formats font, fill, borders, and
other properties.

TypeScript

getFormat(): ConditionalRangeFormat;

Returns
ExcelScript.ConditionalRangeFormat

getRule()
Specifies the Rule object on this conditional format.

TypeScript

getRule(): ConditionalFormatRule;
Returns
ExcelScript.ConditionalFormatRule

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CustomDataValidation
interface
Reference
Package: ExcelScript

Represents the custom data validation criteria.

Remarks

Examples

TypeScript

/**
* This script adds data validation to a range.
* The validation prevents duplicate entries within that range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range "B2:B20".
const sheet = workbook.getActiveWorksheet();
const range = sheet.getRange("B2:B20");

// Set data validation on the range to prevent duplicate, non-blank


entries.
const dataValidation = range.getDataValidation();
dataValidation.setIgnoreBlanks(true);
const duplicateRule : ExcelScript.CustomDataValidation = {
formula: "=COUNTIF($B$2:$B$20, B2)=1"
};
dataValidation.setRule({
custom: duplicateRule
});
}

Properties
ノ Expand table

formula A custom data validation formula. This creates special input rules, such as preventing
duplicates, or limiting the total in a range of cells.
Property Details

formula
A custom data validation formula. This creates special input rules, such as preventing
duplicates, or limiting the total in a range of cells.

TypeScript

formula: string;

Property Value
string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CustomProperty interface
Reference
Package: ExcelScript

Represents a custom property.

Methods
ノ Expand table

delete() Deletes the custom property.

getKey() The key of the custom property. The key is limited to 255 characters outside of
Excel on the web (larger keys are automatically trimmed to 255 characters on
other platforms).

getType() The type of the value used for the custom property.

getValue() The value of the custom property. The value is limited to 255 characters outside of
Excel on the web (larger values are automatically trimmed to 255 characters on
other platforms).

set The value of the custom property. The value is limited to 255 characters outside of
Value(value) Excel on the web (larger values are automatically trimmed to 255 characters on
other platforms).

Method Details

delete()
Deletes the custom property.

TypeScript

delete(): void;

Returns
void

getKey()
The key of the custom property. The key is limited to 255 characters outside of Excel
on the web (larger keys are automatically trimmed to 255 characters on other
platforms).

TypeScript

getKey(): string;

Returns
string

getType()
The type of the value used for the custom property.

TypeScript

getType(): DocumentPropertyType;

Returns
ExcelScript.DocumentPropertyType

getValue()
The value of the custom property. The value is limited to 255 characters outside of
Excel on the web (larger values are automatically trimmed to 255 characters on other
platforms).

TypeScript

getValue(): any;

Returns
any

setValue(value)
The value of the custom property. The value is limited to 255 characters outside of
Excel on the web (larger values are automatically trimmed to 255 characters on other
platforms).

TypeScript

setValue(value: any): void;

Parameters
value any

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.CustomXmlPart interface
Reference
Package: ExcelScript

Represents a custom XML part object in a workbook.

Methods
ノ Expand table

delete() Deletes the custom XML part.

getId() The custom XML part's ID.

getNamespaceUri() The custom XML part's namespace URI.

getXml() Gets the custom XML part's full XML content.

setXml(xml) Sets the custom XML part's full XML content.

Method Details

delete()
Deletes the custom XML part.

TypeScript

delete(): void;

Returns
void

getId()
The custom XML part's ID.

TypeScript
getId(): string;

Returns
string

getNamespaceUri()
The custom XML part's namespace URI.

TypeScript

getNamespaceUri(): string;

Returns
string

getXml()
Gets the custom XML part's full XML content.

TypeScript

getXml(): string;

Returns
string

setXml(xml)
Sets the custom XML part's full XML content.

TypeScript

setXml(xml: string): void;

Parameters
xml string
XML content for the part.

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DataBarConditionalFormat
interface
Reference
Package: ExcelScript

Represents an Excel conditional data bar type.

Remarks

Examples

TypeScript

/**
* This script creates data bar conditional formatting on the selected
range.
* The scale of the data bar goes from 0 to 1000.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected range.
const selected = workbook.getSelectedRange();

// Create new conditional formatting on the range.


const format =
selected.addConditionalFormat(ExcelScript.ConditionalFormatType.dataBar);
const dataBarFormat: ExcelScript.DataBarConditionalFormat =
format.getDataBar();

// Set the lower bound of the data bar formatting to be 0.


const lowerBound: ExcelScript.ConditionalDataBarRule = {
type: ExcelScript.ConditionalFormatRuleType.number,
formula: "0"
};
dataBarFormat.setLowerBoundRule(lowerBound);

// Set the upper bound of the data bar formatting to be 1000.


const upperBound: ExcelScript.ConditionalDataBarRule = {
type: ExcelScript.ConditionalFormatRuleType.number,
formula: "1000"
};
dataBarFormat.setUpperBoundRule(upperBound);
}

Methods
ノ Expand table

getAxisColor() HTML color code representing the color of the Axis line, in the form
#RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange"). Value
is "" (an empty string) if no axis is present or set.

getAxisFormat() Representation of how the axis is determined for an Excel data bar.

getBarDirection() Specifies the direction that the data bar graphic should be based on.

getLowerBound The rule for what constitutes the lower bound (and how to calculate it, if
Rule() applicable) for a data bar. The ConditionalDataBarRule object must be set
as a JSON object (use x.lowerBoundRule = {...} instead of
x.lowerBoundRule.formula = ... ).

getNegative Representation of all values to the left of the axis in an Excel data bar.
Format()

getPositiveFormat() Representation of all values to the right of the axis in an Excel data bar.

getShowDataBar If true , hides the values from the cells where the data bar is applied.
Only()

getUpperBound The rule for what constitutes the upper bound (and how to calculate it, if
Rule() applicable) for a data bar. The ConditionalDataBarRule object must be set
as a JSON object (use x.upperBoundRule = {...} instead of
x.upperBoundRule.formula = ... ).

setAxisColor(axis HTML color code representing the color of the Axis line, in the form
Color) #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange"). Value
is "" (an empty string) if no axis is present or set.

setAxisFormat(axis Representation of how the axis is determined for an Excel data bar.
Format)

setBarDirection(bar Specifies the direction that the data bar graphic should be based on.
Direction)

setLowerBound The rule for what constitutes the lower bound (and how to calculate it, if
Rule(lowerBound applicable) for a data bar. The ConditionalDataBarRule object must be set
Rule) as a JSON object (use x.lowerBoundRule = {...} instead of
x.lowerBoundRule.formula = ... ).

setShowDataBar If true , hides the values from the cells where the data bar is applied.
Only(showDataBar
Only)

setUpperBound The rule for what constitutes the upper bound (and how to calculate it, if
Rule(upperBound applicable) for a data bar. The ConditionalDataBarRule object must be set
Rule) as a JSON object (use x.upperBoundRule = {...} instead of
x.upperBoundRule.formula = ... ).
Method Details

getAxisColor()
HTML color code representing the color of the Axis line, in the form #RRGGBB (e.g.,
"FFA500") or as a named HTML color (e.g., "orange"). Value is "" (an empty string) if
no axis is present or set.

TypeScript

getAxisColor(): string;

Returns
string

getAxisFormat()
Representation of how the axis is determined for an Excel data bar.

TypeScript

getAxisFormat(): ConditionalDataBarAxisFormat;

Returns
ExcelScript.ConditionalDataBarAxisFormat

getBarDirection()
Specifies the direction that the data bar graphic should be based on.

TypeScript

getBarDirection(): ConditionalDataBarDirection;

Returns
ExcelScript.ConditionalDataBarDirection
getLowerBoundRule()
The rule for what constitutes the lower bound (and how to calculate it, if applicable)
for a data bar. The ConditionalDataBarRule object must be set as a JSON object (use
x.lowerBoundRule = {...} instead of x.lowerBoundRule.formula = ... ).

TypeScript

getLowerBoundRule(): ConditionalDataBarRule;

Returns
ExcelScript.ConditionalDataBarRule

getNegativeFormat()
Representation of all values to the left of the axis in an Excel data bar.

TypeScript

getNegativeFormat(): ConditionalDataBarNegativeFormat;

Returns
ExcelScript.ConditionalDataBarNegativeFormat

getPositiveFormat()
Representation of all values to the right of the axis in an Excel data bar.

TypeScript

getPositiveFormat(): ConditionalDataBarPositiveFormat;

Returns
ExcelScript.ConditionalDataBarPositiveFormat

getShowDataBarOnly()
If true , hides the values from the cells where the data bar is applied.
TypeScript

getShowDataBarOnly(): boolean;

Returns
boolean

getUpperBoundRule()
The rule for what constitutes the upper bound (and how to calculate it, if applicable)
for a data bar. The ConditionalDataBarRule object must be set as a JSON object (use
x.upperBoundRule = {...} instead of x.upperBoundRule.formula = ... ).

TypeScript

getUpperBoundRule(): ConditionalDataBarRule;

Returns
ExcelScript.ConditionalDataBarRule

setAxisColor(axisColor)
HTML color code representing the color of the Axis line, in the form #RRGGBB (e.g.,
"FFA500") or as a named HTML color (e.g., "orange"). Value is "" (an empty string) if
no axis is present or set.

TypeScript

setAxisColor(axisColor: string): void;

Parameters
axisColor string

Returns
void

setAxisFormat(axisFormat)
Representation of how the axis is determined for an Excel data bar.

TypeScript

setAxisFormat(axisFormat: ConditionalDataBarAxisFormat): void;

Parameters
axisFormat ExcelScript.ConditionalDataBarAxisFormat

Returns
void

setBarDirection(barDirection)
Specifies the direction that the data bar graphic should be based on.

TypeScript

setBarDirection(barDirection: ConditionalDataBarDirection): void;

Parameters
barDirection ExcelScript.ConditionalDataBarDirection

Returns
void

setLowerBoundRule(lowerBoundRule)
The rule for what constitutes the lower bound (and how to calculate it, if applicable)
for a data bar. The ConditionalDataBarRule object must be set as a JSON object (use
x.lowerBoundRule = {...} instead of x.lowerBoundRule.formula = ... ).

TypeScript

setLowerBoundRule(lowerBoundRule: ConditionalDataBarRule): void;

Parameters
lowerBoundRule ExcelScript.ConditionalDataBarRule

Returns
void

setShowDataBarOnly(showDataBarOnly)
If true , hides the values from the cells where the data bar is applied.

TypeScript

setShowDataBarOnly(showDataBarOnly: boolean): void;

Parameters
showDataBarOnly boolean

Returns
void

setUpperBoundRule(upperBoundRule)
The rule for what constitutes the upper bound (and how to calculate it, if applicable)
for a data bar. The ConditionalDataBarRule object must be set as a JSON object (use
x.upperBoundRule = {...} instead of x.upperBoundRule.formula = ... ).

TypeScript

setUpperBoundRule(upperBoundRule: ConditionalDataBarRule): void;

Parameters
upperBoundRule ExcelScript.ConditionalDataBarRule

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DataPivotHierarchy interface
Reference
Package: ExcelScript

Represents the Excel DataPivotHierarchy.

Remarks

Examples

TypeScript

/**
* This sample sorts the rows of a PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get an existing PivotTable.
const pivotTable = workbook.getPivotTable("Farm Sales");

// Get the data hierarchy to use as the basis of the sort.


const valueFieldToSortOn: ExcelScript.DataPivotHierarchy =
pivotTable.getDataHierarchy("Sum of Crates Sold Wholesale");

// Get the row to sort.


const rowToSort: ExcelScript.RowColumnPivotHierarchy =
pivotTable.getRowHierarchy("Farm");

// Sort the "Farm" row's only field by the values in "Sum of Crates Sold
Wholesale".
rowToSort.getFields()[0].sortByValues(ExcelScript.SortBy.descending,
valueFieldToSortOn);
}

Methods
ノ Expand table

getField() Returns the PivotFields associated with the DataPivotHierarchy.

getId() ID of the DataPivotHierarchy.

getName() Name of the DataPivotHierarchy.

getNumberFormat() Number format of the DataPivotHierarchy.


getPosition() Position of the DataPivotHierarchy.

getShowAs() Specifies if the data should be shown as a specific summary


calculation.

getSummarizeBy() Specifies if all items of the DataPivotHierarchy are shown.

setName(name) Name of the DataPivotHierarchy.

setNumberFormat(number Number format of the DataPivotHierarchy.


Format)

setPosition(position) Position of the DataPivotHierarchy.

setShowAs(showAs) Specifies if the data should be shown as a specific summary


calculation.

setSummarizeBy(summarizeBy) Specifies if all items of the DataPivotHierarchy are shown.

setToDefault() Reset the DataPivotHierarchy back to its default values.

Method Details

getField()
Returns the PivotFields associated with the DataPivotHierarchy.

TypeScript

getField(): PivotField;

Returns
ExcelScript.PivotField

getId()
ID of the DataPivotHierarchy.

TypeScript

getId(): string;

Returns
string

getName()
Name of the DataPivotHierarchy.

TypeScript

getName(): string;

Returns
string

getNumberFormat()
Number format of the DataPivotHierarchy.

TypeScript

getNumberFormat(): string;

Returns
string

getPosition()
Position of the DataPivotHierarchy.

TypeScript

getPosition(): number;

Returns
number

getShowAs()
Specifies if the data should be shown as a specific summary calculation.
TypeScript

getShowAs(): ShowAsRule;

Returns
ExcelScript.ShowAsRule

getSummarizeBy()
Specifies if all items of the DataPivotHierarchy are shown.

TypeScript

getSummarizeBy(): AggregationFunction;

Returns
ExcelScript.AggregationFunction

setName(name)
Name of the DataPivotHierarchy.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

setNumberFormat(numberFormat)
Number format of the DataPivotHierarchy.

TypeScript
setNumberFormat(numberFormat: string): void;

Parameters
numberFormat string

Returns
void

setPosition(position)
Position of the DataPivotHierarchy.

TypeScript

setPosition(position: number): void;

Parameters
position number

Returns
void

setShowAs(showAs)
Specifies if the data should be shown as a specific summary calculation.

TypeScript

setShowAs(showAs: ShowAsRule): void;

Parameters
showAs ExcelScript.ShowAsRule

Returns
void
Examples

TypeScript

/**
* The script changes the display for "Crates Sold at Farm".
* It shows the percentage of the grand total,
* instead of the default sum.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Pivot".
const farmPivot = workbook.getPivotTable("Farm Pivot");

// Get the data hierarchy "Sum of Crates Sold at Farm".


const farmSales = farmPivot.getDataHierarchy("Sum of Crates Sold at
Farm");

// Show the data as a percentage of the grand total.


farmSales.setShowAs({
calculation: ExcelScript.ShowAsCalculation.percentOfGrandTotal
});
}

setSummarizeBy(summarizeBy)
Specifies if all items of the DataPivotHierarchy are shown.

TypeScript

setSummarizeBy(summarizeBy: AggregationFunction): void;

Parameters
summarizeBy ExcelScript.AggregationFunction

Returns
void

Examples

TypeScript

/**
* This script changes how the data in a PivotTable is aggregated.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first PivotTable in the workbook.
const pivotTable = workbook.getPivotTables()[0];

// Set the first data hierarchy to summarize with an average value,


instead of a sum.
const dataHierarchy = pivotTable.getDataHierarchies()[0];
dataHierarchy.setSummarizeBy(ExcelScript.AggregationFunction.average);
}

setToDefault()
Reset the DataPivotHierarchy back to its default values.

TypeScript

setToDefault(): void;

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DataValidation interface
Reference
Package: ExcelScript

Represents the data validation applied to the current range.

Methods
ノ Expand table

clear() Clears the data validation from the current range.

getErrorAlert() Error alert when user enters invalid data.

getIgnoreBlanks() Specifies if data validation will be performed on blank cells. Default is true .

getInvalidCells() Returns a RangeAreas object, comprising one or more rectangular ranges,


with invalid cell values. If all cell values are valid, this function will return
null .

getPrompt() Prompt when users select a cell.

getRule() Data validation rule that contains different type of data validation criteria.

getType() Type of the data validation, see ExcelScript.DataValidationType for details.

getValid() Represents if all cell values are valid according to the data validation rules.
Returns true if all cell values are valid, or false if all cell values are invalid.
Returns null if there are both valid and invalid cell values within the range.

setErrorAlert(error Error alert when user enters invalid data.


Alert)

setIgnore Specifies if data validation will be performed on blank cells. Default is true .
Blanks(ignore
Blanks)

setPrompt(prompt) Prompt when users select a cell.

setRule(rule) Data validation rule that contains different type of data validation criteria.

Method Details

clear()
Clears the data validation from the current range.

TypeScript

clear(): void;

Returns
void

getErrorAlert()
Error alert when user enters invalid data.

TypeScript

getErrorAlert(): DataValidationErrorAlert;

Returns
ExcelScript.DataValidationErrorAlert

getIgnoreBlanks()
Specifies if data validation will be performed on blank cells. Default is true .

TypeScript

getIgnoreBlanks(): boolean;

Returns
boolean

getInvalidCells()
Returns a RangeAreas object, comprising one or more rectangular ranges, with
invalid cell values. If all cell values are valid, this function will return null .

TypeScript
getInvalidCells(): RangeAreas;

Returns
ExcelScript.RangeAreas

getPrompt()
Prompt when users select a cell.

TypeScript

getPrompt(): DataValidationPrompt;

Returns
ExcelScript.DataValidationPrompt

getRule()
Data validation rule that contains different type of data validation criteria.

TypeScript

getRule(): DataValidationRule;

Returns
ExcelScript.DataValidationRule

getType()
Type of the data validation, see ExcelScript.DataValidationType for details.

TypeScript

getType(): DataValidationType;

Returns
ExcelScript.DataValidationType

Examples

TypeScript

/**
* This sample reads and logs the data validation type of the currently
selected range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the currently selected range.
let range = workbook.getSelectedRange();

// Get the type (`DataValidationType`) of data validation applied to


the range.
let validationType = range.getDataValidation().getType();

/*
* Log the data validation type.
* If the range has a single value, it logs that type.
* If the range doesn't have data validation applied, it logs "None".
* If the range has multiple different types of data validation, it
logs "Inconsistent" or "MixedCriteria".
*/
console.log(validationType.toString());
}

getValid()
Represents if all cell values are valid according to the data validation rules. Returns
true if all cell values are valid, or false if all cell values are invalid. Returns null if

there are both valid and invalid cell values within the range.

TypeScript

getValid(): boolean;

Returns
boolean

setErrorAlert(errorAlert)
Error alert when user enters invalid data.
TypeScript

setErrorAlert(errorAlert: DataValidationErrorAlert): void;

Parameters
errorAlert ExcelScript.DataValidationErrorAlert

Returns
void

setIgnoreBlanks(ignoreBlanks)
Specifies if data validation will be performed on blank cells. Default is true .

TypeScript

setIgnoreBlanks(ignoreBlanks: boolean): void;

Parameters
ignoreBlanks boolean

Returns
void

setPrompt(prompt)
Prompt when users select a cell.

TypeScript

setPrompt(prompt: DataValidationPrompt): void;

Parameters
prompt ExcelScript.DataValidationPrompt

Returns
void

Examples

TypeScript

/**
* 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.
let selectedSheet = workbook.getActiveWorksheet();
let 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.
dataValidation.setPrompt({
showPrompt: true,
title: "First names only",
message: "Only enter the first name of the employee, not the full
name."
});
}

setRule(rule)
Data validation rule that contains different type of data validation criteria.

TypeScript

setRule(rule: DataValidationRule): void;

Parameters
rule ExcelScript.DataValidationRule

Returns
void
Examples

TypeScript

/**
* This script creates a data validation rule for the range B1: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 B1:B5 in the active worksheet.
const currentSheet = workbook.getActiveWorksheet();
const positiveNumberOnlyCells = currentSheet.getRange("B1: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);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.DataValidationErrorAlert
interface
Reference
Package: ExcelScript

Represents the error alert properties for the data validation.

Remarks

Examples

TypeScript

/**
* This script creates a data validation rule for the range B1: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 B1:B5 in the active worksheet.
const currentSheet = workbook.getActiveWorksheet();
const positiveNumberOnlyCells = currentSheet.getRange("B1: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);
}
Properties
ノ Expand table

message Represents the error alert message.

show Specifies whether to show an error alert dialog when a user enters invalid data. The
Alert default is true .

style The data validation alert type, please see ExcelScript.DataValidationAlertStyle for
details.

title Represents the error alert dialog title.

Property Details

message
Represents the error alert message.

TypeScript

message: string;

Property Value
string

showAlert
Specifies whether to show an error alert dialog when a user enters invalid data. The
default is true .

TypeScript

showAlert: boolean;

Property Value
boolean
style
The data validation alert type, please see ExcelScript.DataValidationAlertStyle for
details.

TypeScript

style: DataValidationAlertStyle;

Property Value
ExcelScript.DataValidationAlertStyle

title
Represents the error alert dialog title.

TypeScript

title: string;

Property Value
string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DataValidationPrompt
interface
Reference
Package: ExcelScript

Represents the user prompt properties for the data validation.

Remarks

Examples

TypeScript

/**
* 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.
let selectedSheet = workbook.getActiveWorksheet();
let 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);
}

Properties
ノ Expand table

message Specifies the message of the prompt.


showPrompt Specifies if a prompt is shown when a user selects a cell with data validation.

title Specifies the title for the prompt.

Property Details

message
Specifies the message of the prompt.

TypeScript

message: string;

Property Value
string

showPrompt
Specifies if a prompt is shown when a user selects a cell with data validation.

TypeScript

showPrompt: boolean;

Property Value
boolean

title
Specifies the title for the prompt.

TypeScript

title: string;

Property Value
string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DataValidationRule interface
Reference
Package: ExcelScript

A data validation rule contains different types of data validation. You can only use one of
them at a time according the ExcelScript.DataValidationType .

Properties
ノ Expand table

custom Custom data validation criteria.

date Date data validation criteria.

decimal Decimal data validation criteria.

list List data validation criteria.

textLength Text length data validation criteria.

time Time data validation criteria.

wholeNumber Whole number data validation criteria.

Property Details

custom
Custom data validation criteria.

TypeScript

custom?: CustomDataValidation;

Property Value
ExcelScript.CustomDataValidation

Examples
TypeScript

/**
* This script adds data validation to a range.
* The validation prevents duplicate entries within that range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range "B2:B20".
const sheet = workbook.getActiveWorksheet();
const range = sheet.getRange("B2:B20");

// Set data validation on the range to prevent duplicate, non-blank


entries.
const dataValidation = range.getDataValidation();
dataValidation.setIgnoreBlanks(true);
const duplicateRule : ExcelScript.CustomDataValidation = {
formula: "=COUNTIF($B$2:$B$20, B2)=1"
};
dataValidation.setRule({
custom: duplicateRule
});
}

date
Date data validation criteria.

TypeScript

date?: DateTimeDataValidation;

Property Value
ExcelScript.DateTimeDataValidation

decimal
Decimal data validation criteria.

TypeScript

decimal?: BasicDataValidation;

Property Value
ExcelScript.BasicDataValidation
list
List data validation criteria.

TypeScript

list?: ListDataValidation;

Property Value
ExcelScript.ListDataValidation

Examples

TypeScript

/**
* This script creates a dropdown selection list for a cell.
* It uses the existing values of the selected range as the choices for
the list.
*/
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.


let validationCriteria : ExcelScript.ListDataValidation = {
inCellDropDown: true,
source: dataValidationListString
};
let validationRule: ExcelScript.DataValidationRule = {
list: validationCriteria
};
dataValidation.setRule(validationRule);
}

textLength
Text length data validation criteria.

TypeScript

textLength?: BasicDataValidation;

Property Value
ExcelScript.BasicDataValidation

time
Time data validation criteria.

TypeScript

time?: DateTimeDataValidation;

Property Value
ExcelScript.DateTimeDataValidation

wholeNumber
Whole number data validation criteria.

TypeScript

wholeNumber?: BasicDataValidation;

Property Value
ExcelScript.BasicDataValidation

Examples
TypeScript

/**
* This script creates a data validation rule for the range B1: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 B1:B5 in the active worksheet.
const currentSheet = workbook.getActiveWorksheet();
const positiveNumberOnlyCells = currentSheet.getRange("B1: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);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DateTimeDataValidation
interface
Reference
Package: ExcelScript

Represents the date data validation criteria.

Remarks

Examples

TypeScript

/**
* This script sets a validation rule that only allows for certain dates to
be entered.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range D2:D6 in the current worksheet.
const selectedSheet = workbook.getActiveWorksheet();
const range = selectedSheet.getRange("D2:D6");

// Set a validation rule to only allow values that are dates in the year
2023.
let dataValidation = range.getDataValidation();
const dateValidationRule: ExcelScript.DateTimeDataValidation = {
formula1: "1/1/2023",
formula2: "12/31/2023",
operator: ExcelScript.DataValidationOperator.between
};
dataValidation.setRule({ date: dateValidationRule});

// Set an appropriate error message.


dataValidation.setErrorAlert({
showAlert: true,
title: "2023 date required",
message: "Please enter a date in the year 2023.",
style: ExcelScript.DataValidationAlertStyle.stop
});
}

Properties
ノ Expand table

formula1 Specifies the right-hand operand when the operator property is set to a binary
operator such as GreaterThan (the left-hand operand is the value the user tries to
enter in the cell). With the ternary operators Between and NotBetween, specifies the
lower bound operand. When setting the value, it can be passed in as a Date, a Range
object, or a string formula (where the string is either a stringified date/time in ISO8601
format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). When retrieving
the value, it will always be returned as a string formula, for example: "=10", "=A1",
"=SUM(A1:B5)", etc.

formula2 With the ternary operators Between and NotBetween, specifies the upper bound
operand. Is not used with the binary operators, such as GreaterThan. When setting the
value, it can be passed in as a Date, a Range object, or a string (where the string is
either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a
formula like "=MIN(A1, B1)"). When retrieving the value, it will always be returned as a
string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.

operator The operator to use for validating the data.

Property Details

formula1
Specifies the right-hand operand when the operator property is set to a binary
operator such as GreaterThan (the left-hand operand is the value the user tries to
enter in the cell). With the ternary operators Between and NotBetween, specifies the
lower bound operand. When setting the value, it can be passed in as a Date, a Range
object, or a string formula (where the string is either a stringified date/time in
ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). When
retrieving the value, it will always be returned as a string formula, for example: "=10",
"=A1", "=SUM(A1:B5)", etc.

TypeScript

formula1: string | Date | Range;

Property Value
string | Date | ExcelScript.Range

formula2
With the ternary operators Between and NotBetween, specifies the upper bound
operand. Is not used with the binary operators, such as GreaterThan. When setting
the value, it can be passed in as a Date, a Range object, or a string (where the string
is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a
formula like "=MIN(A1, B1)"). When retrieving the value, it will always be returned as
a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.

TypeScript

formula2?: string | Date | Range;

Property Value
string | Date | ExcelScript.Range

operator
The operator to use for validating the data.

TypeScript

operator: DataValidationOperator;

Property Value
ExcelScript.DataValidationOperator

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DatetimeFormatInfo
interface
Reference
Package: ExcelScript

Defines the culturally appropriate format of displaying numbers. This is based on current
system culture settings.

Remarks

Examples

TypeScript

/**
* This script sets the value of a cell to a date string for January 2,
2023.
* It writes the day or month first in the string based on system settings.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell in the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0,0);

// Get the date format.


const cultureInfo : ExcelScript.CultureInfo =
workbook.getApplication().getCultureInfo();
const systemDateTimeFormat : ExcelScript.DatetimeFormatInfo =
cultureInfo.getDatetimeFormat();
const shortDatePattern : string =
systemDateTimeFormat.getShortDatePattern();

// Determine if the date should start with the month or day.


if (shortDatePattern.startsWith("m")) {
cell.setValue("1/2/2023");
} else {
cell.setValue("2/1/2023");
}
}

Methods
ノ Expand table
getDateSeparator() Gets the string used as the date separator. This is based on current system
settings.

getLongDate Gets the format string for a long date value. This is based on current
Pattern() system settings.

getLongTime Gets the format string for a long time value. This is based on current
Pattern() system settings.

getShortDate Gets the format string for a short date value. This is based on current
Pattern() system settings.

getTimeSeparator() Gets the string used as the time separator. This is based on current system
settings.

Method Details

getDateSeparator()
Gets the string used as the date separator. This is based on current system settings.

TypeScript

getDateSeparator(): string;

Returns
string

Examples

TypeScript

/**
* This script writes the current date, month, and year.
* It uses the system's date separator character.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell in the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0,0);

// Get the date separation string.


const cultureInfo = workbook.getApplication().getCultureInfo();
const systemDateTimeFormat = cultureInfo.getDatetimeFormat();
const separator = systemDateTimeFormat.getDateSeparator();
// Get the current date.
const currentDate = new Date(Date.now());

// Write the date using the system's separator character.

cell.setValue(`${currentDate.getMonth()}${separator}${currentDate.getDate
()}${separator}${currentDate.getFullYear()}`);
}

getLongDatePattern()
Gets the format string for a long date value. This is based on current system settings.

TypeScript

getLongDatePattern(): string;

Returns
string

Examples

TypeScript

/**
* This script returns the system's long date pattern.
* This could be used in a Power Automate flow to keep date formatting
consistent.
*/
function main(workbook: ExcelScript.Workbook) : string {
const cultureInfo = workbook.getApplication().getCultureInfo();
const dateTimeInfo = cultureInfo.getDatetimeFormat();

return dateTimeInfo.getLongDatePattern();
}

getLongTimePattern()
Gets the format string for a long time value. This is based on current system settings.

TypeScript

getLongTimePattern(): string;
Returns
string

getShortDatePattern()
Gets the format string for a short date value. This is based on current system
settings.

TypeScript

getShortDatePattern(): string;

Returns
string

getTimeSeparator()
Gets the string used as the time separator. This is based on current system settings.

TypeScript

getTimeSeparator(): string;

Returns
string

Examples

TypeScript

/**
* This script writes the current hour, minute, and second.
* It uses the system's time separator character.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell in the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0, 0);

// Get the date separation string.


const cultureInfo = workbook.getApplication().getCultureInfo();
const systemDateTimeFormat = cultureInfo.getDatetimeFormat();
const separator = systemDateTimeFormat.getTimeSeparator();
// Get the current time.
const currentTime = new Date(Date.now());

// Write the date using the system's separator character.

cell.setValue(`${currentTime.getHours()}${separator}${currentTime.getMinu
tes()}${separator}${currentTime.getSeconds()}`);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.DocumentProperties
interface
Reference
Package: ExcelScript

Represents workbook properties.

Remarks

Examples

TypeScript

/**
* This script creates a new worksheet that displays some of the document
properties.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the document properties.
const properties: ExcelScript.DocumentProperties =
workbook.getProperties();

// Create a new worksheet called "Metadata".


const newWorksheet = workbook.addWorksheet("Metadata");

// Create an array to store the string values of properties to save.


let values: string[][] = [];
values.push(["Creation Date", properties.getCreationDate().toString()]);
values.push(["Author", properties.getAuthor()]);
values.push(["Last Edited By", properties.getLastAuthor()]);

// Set the property values to a range on the new worksheet.


newWorksheet.getRange("A1:B3").setValues(values);
}

Methods
ノ Expand table

addCustomProperty(key, Creates a new or sets an existing custom property.


value)

deleteAllCustomProperties() Deletes all custom properties in this collection.


getAuthor() The author of the workbook.

getCategory() The category of the workbook.

getComments() The comments of the workbook.

getCompany() The company of the workbook.

getCreationDate() Gets the creation date of the workbook.

getCustom() Gets the collection of custom properties of the workbook.

getCustomProperty(key) Gets a custom property object by its key, which is case-insensitive.


If the custom property doesn't exist, then this method returns
undefined .

getKeywords() The keywords of the workbook.

getLastAuthor() Gets the last author of the workbook.

getManager() The manager of the workbook.

getRevisionNumber() Gets the revision number of the workbook.

getSubject() The subject of the workbook.

getTitle() The title of the workbook.

setAuthor(author) The author of the workbook.

setCategory(category) The category of the workbook.

setComments(comments) The comments of the workbook.

setCompany(company) The company of the workbook.

setKeywords(keywords) The keywords of the workbook.

setManager(manager) The manager of the workbook.

setRevisionNumber(revision Gets the revision number of the workbook.


Number)

setSubject(subject) The subject of the workbook.

setTitle(title) The title of the workbook.

Method Details

addCustomProperty(key, value)
Creates a new or sets an existing custom property.

TypeScript

addCustomProperty(key: string, value: any): CustomProperty;

Parameters
key string
Required. The custom property's key, which is case-insensitive. The key is limited to
255 characters outside of Excel on the web (larger keys are automatically trimmed to
255 characters on other platforms).

value any
Required. The custom property's value. The value is limited to 255 characters outside
of Excel on the web (larger values are automatically trimmed to 255 characters on
other platforms).

Returns
ExcelScript.CustomProperty

Examples

TypeScript

/**
* This script adds a workbook-level custom property.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the property collection.
const properties = workbook.getProperties();

// Add a new property called "Project" with the value "FA".


properties.addCustomProperty("Project", "FA");
}

deleteAllCustomProperties()
Deletes all custom properties in this collection.

TypeScript
deleteAllCustomProperties(): void;

Returns
void

getAuthor()
The author of the workbook.

TypeScript

getAuthor(): string;

Returns
string

getCategory()
The category of the workbook.

TypeScript

getCategory(): string;

Returns
string

getComments()
The comments of the workbook.

TypeScript

getComments(): string;

Returns
string

getCompany()
The company of the workbook.

TypeScript

getCompany(): string;

Returns
string

getCreationDate()
Gets the creation date of the workbook.

TypeScript

getCreationDate(): Date;

Returns
Date

getCustom()
Gets the collection of custom properties of the workbook.

TypeScript

getCustom(): CustomProperty[];

Returns
ExcelScript.CustomProperty[]

getCustomProperty(key)
Gets a custom property object by its key, which is case-insensitive. If the custom
property doesn't exist, then this method returns undefined .

TypeScript

getCustomProperty(key: string): CustomProperty | undefined;

Parameters
key string
Required. The key that identifies the custom property object.

Returns
ExcelScript.CustomProperty | undefined

Examples

TypeScript

/**
* This script gets a workbook-level custom property called "Project".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the property collection.
const properties = workbook.getProperties();

// Get the "Project" property.


const project = properties.getCustomProperty("Project");

// Show the property value in the console.


console.log(project.getValue());
}

getKeywords()
The keywords of the workbook.

TypeScript

getKeywords(): string;

Returns
string

getLastAuthor()
Gets the last author of the workbook.

TypeScript

getLastAuthor(): string;

Returns
string

getManager()
The manager of the workbook.

TypeScript

getManager(): string;

Returns
string

getRevisionNumber()
Gets the revision number of the workbook.

TypeScript

getRevisionNumber(): number;

Returns
number

getSubject()
The subject of the workbook.
TypeScript

getSubject(): string;

Returns
string

getTitle()
The title of the workbook.

TypeScript

getTitle(): string;

Returns
string

setAuthor(author)
The author of the workbook.

TypeScript

setAuthor(author: string): void;

Parameters
author string

Returns
void

setCategory(category)
The category of the workbook.

TypeScript
setCategory(category: string): void;

Parameters
category string

Returns
void

setComments(comments)
The comments of the workbook.

TypeScript

setComments(comments: string): void;

Parameters
comments string

Returns
void

setCompany(company)
The company of the workbook.

TypeScript

setCompany(company: string): void;

Parameters
company string

Returns
void
setKeywords(keywords)
The keywords of the workbook.

TypeScript

setKeywords(keywords: string): void;

Parameters
keywords string

Returns
void

setManager(manager)
The manager of the workbook.

TypeScript

setManager(manager: string): void;

Parameters
manager string

Returns
void

setRevisionNumber(revisionNumber)
Gets the revision number of the workbook.

TypeScript

setRevisionNumber(revisionNumber: number): void;

Parameters
revisionNumber number

Returns
void

setSubject(subject)
The subject of the workbook.

TypeScript

setSubject(subject: string): void;

Parameters
subject string

Returns
void

setTitle(title)
The title of the workbook.

TypeScript

setTitle(title: string): void;

Parameters
title string

Returns
void

6 Collaborate with us on
Office Scripts feedback
GitHub Office Scripts is an open source project.
Select a link to provide feedback:
The source for this content can
be found on GitHub, where you  Open a documentation issue
can also create and review
issues and pull requests. For  Provide product feedback
more information, see our
contributor guide.
ExcelScript.Filter interface
Reference
Package: ExcelScript

Manages the filtering of a table's column.

Remarks

Examples

TypeScript

/**
* This script adds a table filter to only show the top 10% of values
* belonging to a particular column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
const table = workbook.getActiveWorksheet().getTables()[0];

// Get the filter for the "PageViews" table column.


const pageViewFilter : ExcelScript.Filter =
table.getColumnByName("PageViews").getFilter();

// Apply a filter to only show the rows with the top 10% of values in
this column.
pageViewFilter.applyTopPercentFilter(10);
}

Methods
ノ Expand table

apply(criteria) Apply the given filter criteria on the given column.

applyBottomItemsFilter(count) Apply a "Bottom Item" filter to the column for the given
number of elements.

applyBottomPercent Apply a "Bottom Percent" filter to the column for the given
Filter(percent) percentage of elements.

applyCellColorFilter(color) Apply a "Cell Color" filter to the column for the given color.
applyCustomFilter(criteria1, Apply an "Icon" filter to the column for the given criteria
criteria2, oper) strings.

applyDynamicFilter(criteria) Apply a "Dynamic" filter to the column.

applyFontColorFilter(color) Apply a "Font Color" filter to the column for the given color.

applyIconFilter(icon) Apply an "Icon" filter to the column for the given icon.

applyTopItemsFilter(count) Apply a "Top Item" filter to the column for the given number
of elements.

applyTopPercentFilter(percent) Apply a "Top Percent" filter to the column for the given
percentage of elements.

applyValuesFilter(values) Apply a "Values" filter to the column for the given values.

clear() Clear the filter on the given column.

getCriteria() The currently applied filter on the given column.

Method Details

apply(criteria)
Apply the given filter criteria on the given column.

TypeScript

apply(criteria: FilterCriteria): void;

Parameters
criteria ExcelScript.FilterCriteria
The criteria to apply.

Returns
void

applyBottomItemsFilter(count)
Apply a "Bottom Item" filter to the column for the given number of elements.
TypeScript

applyBottomItemsFilter(count: number): void;

Parameters
count number
The number of elements from the bottom to show.

Returns
void

applyBottomPercentFilter(percent)
Apply a "Bottom Percent" filter to the column for the given percentage of elements.

TypeScript

applyBottomPercentFilter(percent: number): void;

Parameters
percent number
The percentage of elements from the bottom to show.

Returns
void

applyCellColorFilter(color)
Apply a "Cell Color" filter to the column for the given color.

TypeScript

applyCellColorFilter(color: string): void;

Parameters
color string
The background color of the cells to show.

Returns
void

applyCustomFilter(criteria1, criteria2, oper)


Apply an "Icon" filter to the column for the given criteria strings.

TypeScript

applyCustomFilter(
criteria1: string,
criteria2?: string,
oper?: FilterOperator
): void;

Parameters
criteria1 string
The first criteria string.

criteria2 string
Optional. The second criteria string.

oper ExcelScript.FilterOperator
Optional. The operator that describes how the two criteria are joined.

Returns
void

Examples

TypeScript

/**
* The script filters rows from a table based on numerical values.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const table = currentSheet.getTables()[0];
// Filter to only show rows with values in the "Sales" column that are
// greater than or equal to 2000.
table.getColumnByName("Sales").getFilter().applyCustomFilter(">=2000");
}

applyDynamicFilter(criteria)
Apply a "Dynamic" filter to the column.

TypeScript

applyDynamicFilter(criteria: DynamicFilterCriteria): void;

Parameters
criteria ExcelScript.DynamicFilterCriteria
The dynamic criteria to apply.

Returns
void

Examples

TypeScript

/**
* This script applies a filter to a table that filters it
* to only show rows with dates from the previous month.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the table named "ReportTable".
const table = workbook.getTable("ReportTable");

// Get the column with the header "Date".


const dateColumn = table.getColumnByName("Date");

// Apply a dynamic filter to the column.


// `lastMonth` will only show rows with a date from the previous month.

dateColumn.getFilter().applyDynamicFilter(ExcelScript.DynamicFilterCriter
ia.lastMonth);
}
applyFontColorFilter(color)
Apply a "Font Color" filter to the column for the given color.

TypeScript

applyFontColorFilter(color: string): void;

Parameters
color string
The font color of the cells to show.

Returns
void

applyIconFilter(icon)
Apply an "Icon" filter to the column for the given icon.

TypeScript

applyIconFilter(icon: Icon): void;

Parameters
icon ExcelScript.Icon
The icons of the cells to show.

Returns
void

applyTopItemsFilter(count)
Apply a "Top Item" filter to the column for the given number of elements.

TypeScript

applyTopItemsFilter(count: number): void;


Parameters
count number
The number of elements from the top to show.

Returns
void

applyTopPercentFilter(percent)
Apply a "Top Percent" filter to the column for the given percentage of elements.

TypeScript

applyTopPercentFilter(percent: number): void;

Parameters
percent number
The percentage of elements from the top to show.

Returns
void

applyValuesFilter(values)
Apply a "Values" filter to the column for the given values.

TypeScript

applyValuesFilter(values: Array<string | FilterDatetime>): void;

Parameters
values Array<string | ExcelScript.FilterDatetime>
The list of values to show. This must be an array of strings or an array of
ExcelScript.FilterDateTime objects.

Returns
void

Examples

TypeScript

/**
* This script applies a filter to a table so that it only shows rows
with "Needs Review" in the "Type" column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the workbook.
const table = workbook.getTables()[0];

// Apply the filter to the "Type" column.


const typeColumn = table.getColumnByName("Type");
typeColumn.getFilter().applyValuesFilter(["Needs Review"]);
}

clear()
Clear the filter on the given column.

TypeScript

clear(): void;

Returns
void

Examples

TypeScript

/**
* This script shows how to clear a filter from a table column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the workbook.
const table = workbook.getTables()[0];

// Clear the filter for the table column named "Status".


const statusColumnFilter = table.getColumn("Status").getFilter();
statusColumnFilter.clear();
}

getCriteria()
The currently applied filter on the given column.

TypeScript

getCriteria(): FilterCriteria;

Returns
ExcelScript.FilterCriteria

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.FilterCriteria interface
Reference
Package: ExcelScript

Represents the filtering criteria applied to a column.

Properties
ノ Expand table

color The HTML color string used to filter cells. Used with cellColor and fontColor
filtering.

criterion1 The first criterion used to filter data. Used as an operator in the case of custom
filtering. For example ">50" for numbers greater than 50, or "=*s" for values ending
in "s".

Used as a number in the case of top/bottom items/percents (e.g., "5" for the top 5
items if filterOn is set to topItems ).

criterion2 The second criterion used to filter data. Only used as an operator in the case of
custom filtering.

dynamic The dynamic criteria from the ExcelScript.DynamicFilterCriteria set to apply on


Criteria this column. Used with dynamic filtering.

filterOn The property used by the filter to determine whether the values should stay visible.

icon The icon used to filter cells. Used with icon filtering.

operator The operator used to combine criterion 1 and 2 when using custom filtering.

subField The property used by the filter to do a rich filter on rich values.

values The set of values to be used as part of values filtering.

Property Details

color
The HTML color string used to filter cells. Used with cellColor and fontColor
filtering.
TypeScript

color?: string;

Property Value
string

criterion1
The first criterion used to filter data. Used as an operator in the case of custom
filtering. For example ">50" for numbers greater than 50, or "=*s" for values ending
in "s".

Used as a number in the case of top/bottom items/percents (e.g., "5" for the top 5
items if filterOn is set to topItems ).

TypeScript

criterion1?: string;

Property Value
string

Examples

TypeScript

/**
* This script creates an autoFilter on the worksheet that filters out
rows based on column values.
* The autoFilter filters to only include rows that have a value in
column C in the lowest 10 values
* (of column C values).
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const dataRange = currentSheet.getUsedRange();

// Add a filter that will only show the rows with the lowest 10 values
in column C
// (index 2, assuming the used range spans from at least A:C).
const filterCriteria: ExcelScript.FilterCriteria = {
criterion1: "10",
filterOn: ExcelScript.FilterOn.bottomItems
};
currentSheet.getAutoFilter().apply(dataRange, 2, filterCriteria);
}

criterion2
The second criterion used to filter data. Only used as an operator in the case of
custom filtering.

TypeScript

criterion2?: string;

Property Value
string

dynamicCriteria
The dynamic criteria from the ExcelScript.DynamicFilterCriteria set to apply on
this column. Used with dynamic filtering.

TypeScript

dynamicCriteria?: DynamicFilterCriteria;

Property Value
ExcelScript.DynamicFilterCriteria

filterOn
The property used by the filter to determine whether the values should stay visible.

TypeScript

filterOn: FilterOn;

Property Value
ExcelScript.FilterOn

icon
The icon used to filter cells. Used with icon filtering.

TypeScript

icon?: Icon;

Property Value
ExcelScript.Icon

operator
The operator used to combine criterion 1 and 2 when using custom filtering.

TypeScript

operator?: FilterOperator;

Property Value
ExcelScript.FilterOperator

subField
The property used by the filter to do a rich filter on rich values.

TypeScript

subField?: string;

Property Value
string

values
The set of values to be used as part of values filtering.
TypeScript

values?: Array<string | FilterDatetime>;

Property Value
Array<string | ExcelScript.FilterDatetime>

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.FilterDatetime interface
Reference
Package: ExcelScript

Represents how to filter a date when filtering on values.

Remarks

Examples

TypeScript

/**
* This script applies a filter to a PivotTable that filters it
* to only show rows from between June 20th, 2022 and July 10th, 2022.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the "Date Recorded" field to filter.
// The data in this field must be dates in order for the filter to work.
const pivot = workbook.getPivotTables()[0];
const rowHierarchy = pivot.getRowHierarchy("Date Recorded");
const rowField = rowHierarchy.getFields()[0];

// Create the filter's date boundaries.


let earliestDate: ExcelScript.FilterDatetime = {
date: "2022-06-20",
specificity: ExcelScript.FilterDatetimeSpecificity.day
};
let latestDate: ExcelScript.FilterDatetime = {
date: "2022-07-10",
specificity: ExcelScript.FilterDatetimeSpecificity.day
};

// Apply the date filter.


rowField.applyFilter({
dateFilter: {
condition: ExcelScript.DateFilterCondition.between,
lowerBound: earliestDate,
upperBound: latestDate
}
});
}

Properties
ノ Expand table

date The date in ISO8601 format used to filter data.

specificity How specific the date should be used to keep data. For example, if the date is 2005-
04-02 and the specificity is set to "month", the filter operation will keep all rows with
a date in the month of April 2005.

Property Details

date
The date in ISO8601 format used to filter data.

TypeScript

date: string;

Property Value
string

specificity
How specific the date should be used to keep data. For example, if the date is 2005-
04-02 and the specificity is set to "month", the filter operation will keep all rows with
a date in the month of April 2005.

TypeScript

specificity: FilterDatetimeSpecificity;

Property Value
ExcelScript.FilterDatetimeSpecificity

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
Select a link to provide feedback:
The source for this content can
be found on GitHub, where you  Open a documentation issue
can also create and review
issues and pull requests. For  Provide product feedback
more information, see our
contributor guide.
ExcelScript.FilterPivotHierarchy interface
Reference
Package: ExcelScript

Represents the Excel FilterPivotHierarchy.

Remarks

Examples

TypeScript

/**
* This script creates a PivotTable with a filter.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the two worksheets to use in PivotTable creation.
const dataSheet = workbook.getWorksheet("Data");
const pivotSheet = workbook.getWorksheet("Pivot");

// Create a new PivotTable.


const newPivot = pivotSheet.addPivotTable(
"My PivotTable",
dataSheet.getUsedRange(),
pivotSheet.getRange("A1"));

// Add a filter with the Quarter field.


const filter: ExcelScript.FilterPivotHierarchy =
newPivot.addFilterHierarchy(newPivot.getHierarchy("Quarter"));

// Add other hierarchies...


}

Methods
ノ Expand table

getEnableMultipleFilterItems() Determines whether to allow multiple filter items.

getFields() Returns the PivotFields associated with the


FilterPivotHierarchy.

getId() ID of the FilterPivotHierarchy.


getName() Name of the FilterPivotHierarchy.

getPivotField(name) Gets a PivotField by name. If the PivotField does not exist,


then this method returns undefined .

getPosition() Position of the FilterPivotHierarchy.

setEnableMultipleFilterItems(enable Determines whether to allow multiple filter items.


MultipleFilterItems)

setName(name) Name of the FilterPivotHierarchy.

setPosition(position) Position of the FilterPivotHierarchy.

setToDefault() Reset the FilterPivotHierarchy back to its default values.

Method Details

getEnableMultipleFilterItems()
Determines whether to allow multiple filter items.

TypeScript

getEnableMultipleFilterItems(): boolean;

Returns
boolean

getFields()
Returns the PivotFields associated with the FilterPivotHierarchy.

TypeScript

getFields(): PivotField[];

Returns
ExcelScript.PivotField[]

getId()
ID of the FilterPivotHierarchy.

TypeScript

getId(): string;

Returns
string

getName()
Name of the FilterPivotHierarchy.

TypeScript

getName(): string;

Returns
string

Examples

TypeScript

/**
* This script logs the names of all the filter hierarchies in a
PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first PivotTable in the workbook.
const pivotTable = workbook.getPivotTables()[0];

// For each pivot filter, log its name.


pivotTable.getFilterHierarchies().forEach((filter:
ExcelScript.FilterPivotHierarchy) => {
console.log(filter.getName());
});
}

getPivotField(name)
Gets a PivotField by name. If the PivotField does not exist, then this method returns
undefined .

TypeScript

getPivotField(name: string): PivotField | undefined;

Parameters
name string
Name of the PivotField to be retrieved.

Returns
ExcelScript.PivotField | undefined

getPosition()
Position of the FilterPivotHierarchy.

TypeScript

getPosition(): number;

Returns
number

setEnableMultipleFilterItems(enableMultipleFilterItems)
Determines whether to allow multiple filter items.

TypeScript

setEnableMultipleFilterItems(enableMultipleFilterItems: boolean): void;

Parameters
enableMultipleFilterItems boolean

Returns
void

setName(name)
Name of the FilterPivotHierarchy.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

setPosition(position)
Position of the FilterPivotHierarchy.

TypeScript

setPosition(position: number): void;

Parameters
position number

Returns
void

setToDefault()
Reset the FilterPivotHierarchy back to its default values.

TypeScript

setToDefault(): void;
Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.FormatProtection interface
Reference
Package: ExcelScript

Represents the format protection of a range object.

Methods
ノ Expand table

getFormulaHidden() Specifies if Excel hides the formula for the cells in the range. A null
value indicates that the entire range doesn't have a uniform formula
hidden setting.

getLocked() Specifies if Excel locks the cells in the object. A null value indicates
that the entire range doesn't have a uniform lock setting.

setFormula Specifies if Excel hides the formula for the cells in the range. A null
Hidden(formulaHidden) value indicates that the entire range doesn't have a uniform formula
hidden setting.

setLocked(locked) Specifies if Excel locks the cells in the object. A null value indicates
that the entire range doesn't have a uniform lock setting.

Method Details

getFormulaHidden()
Specifies if Excel hides the formula for the cells in the range. A null value indicates
that the entire range doesn't have a uniform formula hidden setting.

TypeScript

getFormulaHidden(): boolean;

Returns
boolean

getLocked()
Specifies if Excel locks the cells in the object. A null value indicates that the entire
range doesn't have a uniform lock setting.

TypeScript

getLocked(): boolean;

Returns
boolean

setFormulaHidden(formulaHidden)
Specifies if Excel hides the formula for the cells in the range. A null value indicates
that the entire range doesn't have a uniform formula hidden setting.

TypeScript

setFormulaHidden(formulaHidden: boolean): void;

Parameters
formulaHidden boolean

Returns
void

setLocked(locked)
Specifies if Excel locks the cells in the object. A null value indicates that the entire
range doesn't have a uniform lock setting.

TypeScript

setLocked(locked: boolean): void;

Parameters
locked boolean
Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.GeometricShape interface
Reference
Package: ExcelScript

Represents a geometric shape inside a worksheet. A geometric shape can be a


rectangle, block arrow, equation symbol, flowchart item, star, banner, callout, or any
other basic shape in Excel.

Methods
ノ Expand table

getId() Returns the shape identifier.

Method Details

getId()
Returns the shape identifier.

TypeScript

getId(): string;

Returns
string

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.HeaderFooter interface
Reference
Package: ExcelScript

Methods
ノ Expand table

getCenter The center footer of the worksheet. To apply font formatting or insert a
Footer() variable value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

getCenter The center header of the worksheet. To apply font formatting or insert a
Header() variable value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

getLeftFooter() The left footer of the worksheet. To apply font formatting or insert a variable
value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

getLeftHeader() The left header of the worksheet. To apply font formatting or insert a variable
value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

getRightFooter() The right footer of the worksheet. To apply font formatting or insert a variable
value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

getRightHeader() The right header of the worksheet. To apply font formatting or insert a
variable value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

setCenter The center footer of the worksheet. To apply font formatting or insert a
Footer(center variable value, use format codes specified here:
Footer) https://msdn.microsoft.com/library/bb225426.aspx .

setCenter The center header of the worksheet. To apply font formatting or insert a
Header(center variable value, use format codes specified here:
Header) https://msdn.microsoft.com/library/bb225426.aspx .

setLeftFooter(left The left footer of the worksheet. To apply font formatting or insert a variable
Footer) value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

setLeft The left header of the worksheet. To apply font formatting or insert a variable
Header(left value, use format codes specified here:
Header) https://msdn.microsoft.com/library/bb225426.aspx .
setRight The right footer of the worksheet. To apply font formatting or insert a variable
Footer(right value, use format codes specified here:
Footer) https://msdn.microsoft.com/library/bb225426.aspx .

setRight The right header of the worksheet. To apply font formatting or insert a
Header(right variable value, use format codes specified here:
Header) https://msdn.microsoft.com/library/bb225426.aspx .

Method Details

getCenterFooter()
The center footer of the worksheet. To apply font formatting or insert a variable
value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

getCenterFooter(): string;

Returns
string

getCenterHeader()
The center header of the worksheet. To apply font formatting or insert a variable
value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

getCenterHeader(): string;

Returns
string

getLeftFooter()
The left footer of the worksheet. To apply font formatting or insert a variable value,
use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

getLeftFooter(): string;

Returns
string

getLeftHeader()
The left header of the worksheet. To apply font formatting or insert a variable value,
use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

getLeftHeader(): string;

Returns
string

getRightFooter()
The right footer of the worksheet. To apply font formatting or insert a variable value,
use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

getRightFooter(): string;

Returns
string

getRightHeader()
The right header of the worksheet. To apply font formatting or insert a variable value,
use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

getRightHeader(): string;

Returns
string

setCenterFooter(centerFooter)
The center footer of the worksheet. To apply font formatting or insert a variable
value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

setCenterFooter(centerFooter: string): void;

Parameters
centerFooter string

Returns
void

setCenterHeader(centerHeader)
The center header of the worksheet. To apply font formatting or insert a variable
value, use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

setCenterHeader(centerHeader: string): void;

Parameters
centerHeader string

Returns
void

setLeftFooter(leftFooter)
The left footer of the worksheet. To apply font formatting or insert a variable value,
use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

setLeftFooter(leftFooter: string): void;

Parameters
leftFooter string

Returns
void

setLeftHeader(leftHeader)
The left header of the worksheet. To apply font formatting or insert a variable value,
use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

setLeftHeader(leftHeader: string): void;

Parameters
leftHeader string

Returns
void
setRightFooter(rightFooter)
The right footer of the worksheet. To apply font formatting or insert a variable value,
use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

setRightFooter(rightFooter: string): void;

Parameters
rightFooter string

Returns
void

setRightHeader(rightHeader)
The right header of the worksheet. To apply font formatting or insert a variable value,
use format codes specified here:
https://msdn.microsoft.com/library/bb225426.aspx .

TypeScript

setRightHeader(rightHeader: string): void;

Parameters
rightHeader string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review  Open a documentation issue
issues and pull requests. For
more information, see our  Provide product feedback
contributor guide.
ExcelScript.HeaderFooterGroup
interface
Reference
Package: ExcelScript

Methods
ノ Expand table

getDefaultForAll The general header/footer, used for all pages unless even/odd or first
Pages() page is specified.

getEvenPages() The header/footer to use for even pages, odd header/footer needs to be
specified for odd pages.

getFirstPage() The first page header/footer, for all other pages general or even/odd is
used.

getOddPages() The header/footer to use for odd pages, even header/footer needs to be
specified for even pages.

getState() The state by which headers/footers are set. See


ExcelScript.HeaderFooterState for details.

getUseSheetMargins() Gets or sets a flag indicating if headers/footers are aligned with the page
margins set in the page layout options for the worksheet.

getUseSheetScale() Gets or sets a flag indicating if headers/footers should be scaled by the


page percentage scale set in the page layout options for the worksheet.

setState(state) The state by which headers/footers are set. See


ExcelScript.HeaderFooterState for details.

setUseSheet Gets or sets a flag indicating if headers/footers are aligned with the page
Margins(useSheet margins set in the page layout options for the worksheet.
Margins)

setUseSheetScale(use Gets or sets a flag indicating if headers/footers should be scaled by the


SheetScale) page percentage scale set in the page layout options for the worksheet.

Method Details

getDefaultForAllPages()
The general header/footer, used for all pages unless even/odd or first page is
specified.

TypeScript

getDefaultForAllPages(): HeaderFooter;

Returns
ExcelScript.HeaderFooter

getEvenPages()
The header/footer to use for even pages, odd header/footer needs to be specified
for odd pages.

TypeScript

getEvenPages(): HeaderFooter;

Returns
ExcelScript.HeaderFooter

getFirstPage()
The first page header/footer, for all other pages general or even/odd is used.

TypeScript

getFirstPage(): HeaderFooter;

Returns
ExcelScript.HeaderFooter

getOddPages()
The header/footer to use for odd pages, even header/footer needs to be specified
for even pages.

TypeScript
getOddPages(): HeaderFooter;

Returns
ExcelScript.HeaderFooter

getState()
The state by which headers/footers are set. See ExcelScript.HeaderFooterState for
details.

TypeScript

getState(): HeaderFooterState;

Returns
ExcelScript.HeaderFooterState

getUseSheetMargins()
Gets or sets a flag indicating if headers/footers are aligned with the page margins set
in the page layout options for the worksheet.

TypeScript

getUseSheetMargins(): boolean;

Returns
boolean

getUseSheetScale()
Gets or sets a flag indicating if headers/footers should be scaled by the page
percentage scale set in the page layout options for the worksheet.

TypeScript

getUseSheetScale(): boolean;
Returns
boolean

setState(state)
The state by which headers/footers are set. See ExcelScript.HeaderFooterState for
details.

TypeScript

setState(state: HeaderFooterState): void;

Parameters
state ExcelScript.HeaderFooterState

Returns
void

setUseSheetMargins(useSheetMargins)
Gets or sets a flag indicating if headers/footers are aligned with the page margins set
in the page layout options for the worksheet.

TypeScript

setUseSheetMargins(useSheetMargins: boolean): void;

Parameters
useSheetMargins boolean

Returns
void

setUseSheetScale(useSheetScale)
Gets or sets a flag indicating if headers/footers should be scaled by the page
percentage scale set in the page layout options for the worksheet.
TypeScript

setUseSheetScale(useSheetScale: boolean): void;

Parameters
useSheetScale boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Icon interface
Reference
Package: ExcelScript

Represents a cell icon.

Properties
ノ Expand table

index Specifies the index of the icon in the given set.

set Specifies the set that the icon is part of.

Property Details

index
Specifies the index of the icon in the given set.

TypeScript

index: number;

Property Value
number

set
Specifies the set that the icon is part of.

TypeScript

set: IconSet;

Property Value
ExcelScript.IconSet
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.IconSetConditionalFormat
interface
Reference
Package: ExcelScript

Represents an icon set criteria for conditional formatting.

Remarks

Examples

TypeScript

/**
* This script applies icon set conditional formatting to a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range "A1:A5" on the current worksheet.
const sheet = workbook.getActiveWorksheet();
const range = sheet.getRange("A1:A5");

// Create icon set conditional formatting on the range.


const conditionalFormatting =
range.addConditionalFormat(ExcelScript.ConditionalFormatType.iconSet);
const iconSetFormat: ExcelScript.IconSetConditionalFormat =
conditionalFormatting.getIconSet();
// Use the "3 Traffic Lights (Unrimmed)" set.
iconSetFormat.setStyle(ExcelScript.IconSet.threeTrafficLights1);

// Set the criteria to use a different icon for the bottom, middle, and
top thirds of the values in the range.
iconSetFormat.setCriteria([
{

formula:'=0',operator:ExcelScript.ConditionalIconCriterionOperator.greaterTh
anOrEqual,
type:ExcelScript.ConditionalFormatIconRuleType.percent
},
{

formula:'=33',operator:ExcelScript.ConditionalIconCriterionOperator.greaterT
hanOrEqual,
type:ExcelScript.ConditionalFormatIconRuleType.percent},
{

formula:'=67',operator:ExcelScript.ConditionalIconCriterionOperator.greaterT
hanOrEqual,
type:ExcelScript.ConditionalFormatIconRuleType.percent
}]);
}

Methods
ノ Expand table

getCriteria() An array of criteria and icon sets for the rules and potential custom icons
for conditional icons. Note that for the first criterion only the custom
icon can be modified, while type, formula, and operator will be ignored
when set.

getReverseIcon If true , reverses the icon orders for the icon set. Note that this cannot be
Order() set if custom icons are used.

getShowIconOnly() If true , hides the values and only shows icons.

getStyle() If set, displays the icon set option for the conditional format.

setCriteria(criteria) An array of criteria and icon sets for the rules and potential custom icons
for conditional icons. Note that for the first criterion only the custom
icon can be modified, while type, formula, and operator will be ignored
when set.

setReverseIcon If true , reverses the icon orders for the icon set. Note that this cannot be
Order(reverseIcon set if custom icons are used.
Order)

setShowIcon If true , hides the values and only shows icons.


Only(showIconOnly)

setStyle(style) If set, displays the icon set option for the conditional format.

Method Details

getCriteria()
An array of criteria and icon sets for the rules and potential custom icons for
conditional icons. Note that for the first criterion only the custom icon can be
modified, while type, formula, and operator will be ignored when set.

TypeScript
getCriteria(): ConditionalIconCriterion[];

Returns
ExcelScript.ConditionalIconCriterion[]

getReverseIconOrder()
If true , reverses the icon orders for the icon set. Note that this cannot be set if
custom icons are used.

TypeScript

getReverseIconOrder(): boolean;

Returns
boolean

getShowIconOnly()
If true , hides the values and only shows icons.

TypeScript

getShowIconOnly(): boolean;

Returns
boolean

getStyle()
If set, displays the icon set option for the conditional format.

TypeScript

getStyle(): IconSet;
Returns
ExcelScript.IconSet

setCriteria(criteria)
An array of criteria and icon sets for the rules and potential custom icons for
conditional icons. Note that for the first criterion only the custom icon can be
modified, while type, formula, and operator will be ignored when set.

TypeScript

setCriteria(criteria: ConditionalIconCriterion[]): void;

Parameters
criteria ExcelScript.ConditionalIconCriterion[]

Returns
void

setReverseIconOrder(reverseIconOrder)
If true , reverses the icon orders for the icon set. Note that this cannot be set if
custom icons are used.

TypeScript

setReverseIconOrder(reverseIconOrder: boolean): void;

Parameters
reverseIconOrder boolean

Returns
void

setShowIconOnly(showIconOnly)
If true , hides the values and only shows icons.
TypeScript

setShowIconOnly(showIconOnly: boolean): void;

Parameters
showIconOnly boolean

Returns
void

setStyle(style)
If set, displays the icon set option for the conditional format.

TypeScript

setStyle(style: IconSet): void;

Parameters
style ExcelScript.IconSet

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Image interface
Reference
Package: ExcelScript

Represents an image in the worksheet. To get the corresponding Shape object, use
Image.getShape .

Remarks

Examples

TypeScript

/**
* This script transfers an image from one worksheet to another.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the worksheet with the image on it.
const firstWorksheet = workbook.getWorksheet("FirstSheet");

// Get the first image from the worksheet.


// If a script added the image, you could add a name to make it easier to
find.
let image: ExcelScript.Image;
firstWorksheet.getShapes().forEach((shape, index) => {
if (shape.getType() === ExcelScript.ShapeType.image) {
image = shape.getImage();
return;
}
});

// Copy the image to another worksheet.


image.getShape().copyTo("SecondSheet");
}

Methods
ノ Expand table

getFormat() Returns the format of the image.

getId() Specifies the shape identifier for the image object.


getShape() Returns the Shape object associated with the image.

Method Details

getFormat()
Returns the format of the image.

TypeScript

getFormat(): PictureFormat;

Returns
ExcelScript.PictureFormat

getId()
Specifies the shape identifier for the image object.

TypeScript

getId(): string;

Returns
string

getShape()
Returns the Shape object associated with the image.

TypeScript

getShape(): Shape;

Returns
ExcelScript.Shape
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.IterativeCalculation interface
Reference
Package: ExcelScript

Represents the iterative calculation settings.

Methods
ノ Expand table

getEnabled() True if Excel will use iteration to resolve circular references.

getMaxChange() Specifies the maximum amount of change between each iteration as


Excel resolves circular references.

getMaxIteration() Specifies the maximum number of iterations that Excel can use to
resolve a circular reference.

setEnabled(enabled) True if Excel will use iteration to resolve circular references.

setMaxChange(max Specifies the maximum amount of change between each iteration as


Change) Excel resolves circular references.

setMaxIteration(max Specifies the maximum number of iterations that Excel can use to
Iteration) resolve a circular reference.

Method Details

getEnabled()
True if Excel will use iteration to resolve circular references.

TypeScript

getEnabled(): boolean;

Returns
boolean

getMaxChange()
Specifies the maximum amount of change between each iteration as Excel resolves
circular references.

TypeScript

getMaxChange(): number;

Returns
number

getMaxIteration()
Specifies the maximum number of iterations that Excel can use to resolve a circular
reference.

TypeScript

getMaxIteration(): number;

Returns
number

setEnabled(enabled)
True if Excel will use iteration to resolve circular references.

TypeScript

setEnabled(enabled: boolean): void;

Parameters
enabled boolean

Returns
void

setMaxChange(maxChange)
Specifies the maximum amount of change between each iteration as Excel resolves
circular references.

TypeScript

setMaxChange(maxChange: number): void;

Parameters
maxChange number

Returns
void

setMaxIteration(maxIteration)
Specifies the maximum number of iterations that Excel can use to resolve a circular
reference.

TypeScript

setMaxIteration(maxIteration: number): void;

Parameters
maxIteration number

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.Line interface
Reference
Package: ExcelScript

Represents a line inside a worksheet. To get the corresponding Shape object, use
Line.shape .

Methods
ノ Expand table

connectBeginShape(shape, Attaches the beginning of the specified connector to a specified


connectionSite) shape.

connectEndShape(shape, Attaches the end of the specified connector to a specified shape.


connectionSite)

disconnectBeginShape() Detaches the beginning of the specified connector from a shape.

disconnectEndShape() Detaches the end of the specified connector from a shape.

getBeginArrowheadLength() Represents the length of the arrowhead at the beginning of the


specified line.

getBeginArrowheadStyle() Represents the style of the arrowhead at the beginning of the


specified line.

getBeginArrowheadWidth() Represents the width of the arrowhead at the beginning of the


specified line.

getBeginConnectedShape() Represents the shape to which the beginning of the specified line
is attached.

getBeginConnectedSite() Represents the connection site to which the beginning of a


connector is connected. Returns null when the beginning of the
line is not attached to any shape.

getConnectorType() Represents the connector type for the line.

getEndArrowheadLength() Represents the length of the arrowhead at the end of the specified
line.

getEndArrowheadStyle() Represents the style of the arrowhead at the end of the specified
line.

getEndArrowheadWidth() Represents the width of the arrowhead at the end of the specified
line.
getEndConnectedShape() Represents the shape to which the end of the specified line is
attached.

getEndConnectedSite() Represents the connection site to which the end of a connector is


connected. Returns null when the end of the line is not attached
to any shape.

getId() Specifies the shape identifier.

getIsBeginConnected() Specifies if the beginning of the specified line is connected to a


shape.

getIsEndConnected() Specifies if the end of the specified line is connected to a shape.

getShape() Returns the Shape object associated with the line.

setBeginArrowhead Represents the length of the arrowhead at the beginning of the


Length(beginArrowhead specified line.
Length)

setBeginArrowhead Represents the style of the arrowhead at the beginning of the


Style(beginArrowheadStyle) specified line.

setBeginArrowhead Represents the width of the arrowhead at the beginning of the


Width(beginArrowhead specified line.
Width)

setConnectorType(connector Represents the connector type for the line.


Type)

setEndArrowhead Represents the length of the arrowhead at the end of the specified
Length(endArrowhead line.
Length)

setEndArrowheadStyle(end Represents the style of the arrowhead at the end of the specified
ArrowheadStyle) line.

setEndArrowheadWidth(end Represents the width of the arrowhead at the end of the specified
ArrowheadWidth) line.

Method Details

connectBeginShape(shape, connectionSite)
Attaches the beginning of the specified connector to a specified shape.

TypeScript
connectBeginShape(shape: Shape, connectionSite: number): void;

Parameters
shape ExcelScript.Shape
The shape to connect.

connectionSite number
The connection site on the shape to which the beginning of the connector is
attached. Must be an integer between 0 (inclusive) and the connection-site count of
the specified shape (exclusive).

Returns
void

connectEndShape(shape, connectionSite)
Attaches the end of the specified connector to a specified shape.

TypeScript

connectEndShape(shape: Shape, connectionSite: number): void;

Parameters
shape ExcelScript.Shape
The shape to connect.

connectionSite number
The connection site on the shape to which the end of the connector is attached.
Must be an integer between 0 (inclusive) and the connection-site count of the
specified shape (exclusive).

Returns
void

disconnectBeginShape()
Detaches the beginning of the specified connector from a shape.

TypeScript

disconnectBeginShape(): void;

Returns
void

disconnectEndShape()
Detaches the end of the specified connector from a shape.

TypeScript

disconnectEndShape(): void;

Returns
void

getBeginArrowheadLength()
Represents the length of the arrowhead at the beginning of the specified line.

TypeScript

getBeginArrowheadLength(): ArrowheadLength;

Returns
ExcelScript.ArrowheadLength

getBeginArrowheadStyle()
Represents the style of the arrowhead at the beginning of the specified line.

TypeScript

getBeginArrowheadStyle(): ArrowheadStyle;
Returns
ExcelScript.ArrowheadStyle

getBeginArrowheadWidth()
Represents the width of the arrowhead at the beginning of the specified line.

TypeScript

getBeginArrowheadWidth(): ArrowheadWidth;

Returns
ExcelScript.ArrowheadWidth

getBeginConnectedShape()
Represents the shape to which the beginning of the specified line is attached.

TypeScript

getBeginConnectedShape(): Shape;

Returns
ExcelScript.Shape

getBeginConnectedSite()
Represents the connection site to which the beginning of a connector is connected.
Returns null when the beginning of the line is not attached to any shape.

TypeScript

getBeginConnectedSite(): number;

Returns
number
getConnectorType()
Represents the connector type for the line.

TypeScript

getConnectorType(): ConnectorType;

Returns
ExcelScript.ConnectorType

getEndArrowheadLength()
Represents the length of the arrowhead at the end of the specified line.

TypeScript

getEndArrowheadLength(): ArrowheadLength;

Returns
ExcelScript.ArrowheadLength

getEndArrowheadStyle()
Represents the style of the arrowhead at the end of the specified line.

TypeScript

getEndArrowheadStyle(): ArrowheadStyle;

Returns
ExcelScript.ArrowheadStyle

getEndArrowheadWidth()
Represents the width of the arrowhead at the end of the specified line.

TypeScript
getEndArrowheadWidth(): ArrowheadWidth;

Returns
ExcelScript.ArrowheadWidth

getEndConnectedShape()
Represents the shape to which the end of the specified line is attached.

TypeScript

getEndConnectedShape(): Shape;

Returns
ExcelScript.Shape

getEndConnectedSite()
Represents the connection site to which the end of a connector is connected.
Returns null when the end of the line is not attached to any shape.

TypeScript

getEndConnectedSite(): number;

Returns
number

getId()
Specifies the shape identifier.

TypeScript

getId(): string;

Returns
string

getIsBeginConnected()
Specifies if the beginning of the specified line is connected to a shape.

TypeScript

getIsBeginConnected(): boolean;

Returns
boolean

getIsEndConnected()
Specifies if the end of the specified line is connected to a shape.

TypeScript

getIsEndConnected(): boolean;

Returns
boolean

getShape()
Returns the Shape object associated with the line.

TypeScript

getShape(): Shape;

Returns
ExcelScript.Shape

setBeginArrowheadLength(beginArrowheadLength)
Represents the length of the arrowhead at the beginning of the specified line.
TypeScript

setBeginArrowheadLength(beginArrowheadLength: ArrowheadLength): void;

Parameters
beginArrowheadLength ExcelScript.ArrowheadLength

Returns
void

setBeginArrowheadStyle(beginArrowheadStyle)
Represents the style of the arrowhead at the beginning of the specified line.

TypeScript

setBeginArrowheadStyle(beginArrowheadStyle: ArrowheadStyle): void;

Parameters
beginArrowheadStyle ExcelScript.ArrowheadStyle

Returns
void

setBeginArrowheadWidth(beginArrowheadWidth)
Represents the width of the arrowhead at the beginning of the specified line.

TypeScript

setBeginArrowheadWidth(beginArrowheadWidth: ArrowheadWidth): void;

Parameters
beginArrowheadWidth ExcelScript.ArrowheadWidth

Returns
void

setConnectorType(connectorType)
Represents the connector type for the line.

TypeScript

setConnectorType(connectorType: ConnectorType): void;

Parameters
connectorType ExcelScript.ConnectorType

Returns
void

setEndArrowheadLength(endArrowheadLength)
Represents the length of the arrowhead at the end of the specified line.

TypeScript

setEndArrowheadLength(endArrowheadLength: ArrowheadLength): void;

Parameters
endArrowheadLength ExcelScript.ArrowheadLength

Returns
void

setEndArrowheadStyle(endArrowheadStyle)
Represents the style of the arrowhead at the end of the specified line.

TypeScript

setEndArrowheadStyle(endArrowheadStyle: ArrowheadStyle): void;


Parameters
endArrowheadStyle ExcelScript.ArrowheadStyle

Returns
void

setEndArrowheadWidth(endArrowheadWidth)
Represents the width of the arrowhead at the end of the specified line.

TypeScript

setEndArrowheadWidth(endArrowheadWidth: ArrowheadWidth): void;

Parameters
endArrowheadWidth ExcelScript.ArrowheadWidth

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.LinkedWorkbook interface
Reference
Package: ExcelScript

Contains information about a linked workbook. If a workbook has links pointing to data
in another workbook, the second workbook is linked to the first workbook. In this
scenario, the second workbook is called the "linked workbook".

Methods
ノ Expand table

break Makes a request to break the links pointing to the linked workbook. Links in formulas
Links() are replaced with the latest fetched data. The current LinkedWorkbook object is
invalidated and removed from LinkedWorkbookCollection .

refresh Makes a request to refresh the data retrieved from the linked workbook.
Links()

Method Details

breakLinks()
Makes a request to break the links pointing to the linked workbook. Links in
formulas are replaced with the latest fetched data. The current LinkedWorkbook
object is invalidated and removed from LinkedWorkbookCollection .

TypeScript

breakLinks(): void;

Returns
void

Examples

TypeScript
/**
* This script removes all links to other workbooks.
*/
function main(workbook: ExcelScript.Workbook) {
// Get all the linked workbook references.
const externalWorkbooks: ExcelScript.LinkedWorkbook[] =
workbook.getLinkedWorkbooks();
console.log(`There are ${externalWorkbooks.length} other workbooks
linked to from this workbook.`);

// Remove all the links to those workbooks.


// This changes the value of cells with workbook links to
"#CONNECT!".
externalWorkbooks.forEach((workbookLink) => {
workbookLink.breakLinks();
});
}

refreshLinks()
Makes a request to refresh the data retrieved from the linked workbook.

TypeScript

refreshLinks(): void;

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ListDataValidation interface
Reference
Package: ExcelScript

Represents the List data validation criteria.

Remarks

Examples

TypeScript

/**
* This script creates a dropdown selection list for a cell.
* It uses the existing values of the selected range as the choices for the
list.
*/
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.


let validationCriteria : ExcelScript.ListDataValidation = {
inCellDropDown: true,
source: dataValidationListString
};
let validationRule: ExcelScript.DataValidationRule = {
list: validationCriteria
};
dataValidation.setRule(validationRule);
}
Properties
ノ Expand table

inCellDrop Specifies whether to display the list in a cell drop-down. The default is true .
Down

source Source of the list for data validation When setting the value, it can be passed in as a
Range object, or a string that contains a comma-separated number, boolean, or
date.

Property Details

inCellDropDown
Specifies whether to display the list in a cell drop-down. The default is true .

TypeScript

inCellDropDown: boolean;

Property Value
boolean

source
Source of the list for data validation When setting the value, it can be passed in as a
Range object, or a string that contains a comma-separated number, boolean, or date.

TypeScript

source: string | Range;

Property Value
string | ExcelScript.Range
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.NamedItem interface
Reference
Package: ExcelScript

Represents a defined name for a range of cells or value. Names can be primitive named
objects (as seen in the type below), range object, or a reference to a range. This object
can be used to obtain range object associated with names.

Remarks

Examples

TypeScript

/**
* This script creates a named formula and uses it in another part of the
workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Create a named item for a formula.
// This formula is the sum of the cells F2:F21 on Sheet1.
const namedItem: ExcelScript.NamedItem = workbook.addNamedItem(
"GrandTotal",
"=SUM(Sheet1!$F$2:$F$21)",
"The sum of table sums."
);

// Add this named formula to a new sheet in the workbook.


const otherSheet = workbook.addWorksheet();
otherSheet.getRange("A1").setFormula(namedItem.getFormula());

// Switch to the new worksheet.


otherSheet.activate();
}

Methods
ノ Expand table

delete() Deletes the given name.

getArrayValues() Returns an object containing values and types of the named item.
getComment() Specifies the comment associated with this name.

getFormula() The formula of the named item. Formulas always start with an equal sign
("=").

getName() The name of the object.

getRange() Returns the range object that is associated with the name. If the named
item's type is not a range, then this method returns undefined .

getScope() Specifies if the name is scoped to the workbook or to a specific


worksheet. Possible values are: Worksheet, Workbook.

getType() Specifies the type of the value returned by the name's formula. See
ExcelScript.NamedItemType for details.

getValue() Represents the value computed by the name's formula. For a named
range, it will return the range address. This API returns the #VALUE! error
in the Excel UI if it refers to a user-defined function.

getVisible() Specifies if the object is visible.

getWorksheet() Returns the worksheet to which the named item is scoped. If the item is
scoped to the workbook instead, then this method returns undefined .

set Specifies the comment associated with this name.


Comment(comment)

setFormula(formula) The formula of the named item. Formulas always start with an equal sign
("=").

setVisible(visible) Specifies if the object is visible.

Method Details

delete()
Deletes the given name.

TypeScript

delete(): void;

Returns
void
getArrayValues()
Returns an object containing values and types of the named item.

TypeScript

getArrayValues(): NamedItemArrayValues;

Returns
ExcelScript.NamedItemArrayValues

getComment()
Specifies the comment associated with this name.

TypeScript

getComment(): string;

Returns
string

getFormula()
The formula of the named item. Formulas always start with an equal sign ("=").

TypeScript

getFormula(): string;

Returns
string

getName()
The name of the object.

TypeScript
getName(): string;

Returns
string

getRange()
Returns the range object that is associated with the name. If the named item's type is
not a range, then this method returns undefined .

TypeScript

getRange(): Range;

Returns
ExcelScript.Range

getScope()
Specifies if the name is scoped to the workbook or to a specific worksheet. Possible
values are: Worksheet, Workbook.

TypeScript

getScope(): NamedItemScope;

Returns
ExcelScript.NamedItemScope

getType()
Specifies the type of the value returned by the name's formula. See
ExcelScript.NamedItemType for details.

TypeScript

getType(): NamedItemType;
Returns
ExcelScript.NamedItemType

Examples

TypeScript

/**
* This script looks for every named range with "Review" in the name
* and marks the range with a yellow fill.
*/
function main(workbook: ExcelScript.Workbook) {
// Look at every named item in the workbook.
workbook.getNames().forEach((namedItem) => {
// Find names containing "Review".
if (namedItem.getName().includes("Review")) {
// Only change the fill color if the named item is a range (not a
formula).
let itemType: ExcelScript.NamedItemType = namedItem.getType();
if (itemType === ExcelScript.NamedItemType.range) {
// Set the range's fill color to yellow.
namedItem.getRange().getFormat().getFill().setColor("yellow");
}
}
});
}

getValue()
Represents the value computed by the name's formula. For a named range, it will
return the range address. This API returns the #VALUE! error in the Excel UI if it refers
to a user-defined function.

TypeScript

getValue(): string | number;

Returns
string | number

getVisible()
Specifies if the object is visible.
TypeScript

getVisible(): boolean;

Returns
boolean

getWorksheet()
Returns the worksheet to which the named item is scoped. If the item is scoped to
the workbook instead, then this method returns undefined .

TypeScript

getWorksheet(): Worksheet | undefined;

Returns
ExcelScript.Worksheet | undefined

setComment(comment)
Specifies the comment associated with this name.

TypeScript

setComment(comment: string): void;

Parameters
comment string

Returns
void

setFormula(formula)
The formula of the named item. Formulas always start with an equal sign ("=").
TypeScript

setFormula(formula: string): void;

Parameters
formula string

Returns
void

setVisible(visible)
Specifies if the object is visible.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.NamedItemArrayValues
interface
Reference
Package: ExcelScript

Represents an object containing values and types of a named item.

Methods
ノ Expand table

getTypes() Represents the types for each item in the named item array

getValues() Represents the values of each item in the named item array.

Method Details

getTypes()
Represents the types for each item in the named item array

TypeScript

getTypes(): RangeValueType[][];

Returns
ExcelScript.RangeValueType[][]

getValues()
Represents the values of each item in the named item array.

TypeScript

getValues(): (string | number | boolean)[][];


Returns
(string | number | boolean)[][]

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.NamedSheetView interface
Reference
Package: ExcelScript

Represents a named sheet view of a worksheet. A sheet view stores the sort and filter
rules for a particular worksheet. Every sheet view (even a temporary sheet view) has a
unique, worksheet-scoped name that is used to access the view.

Methods
ノ Expand table

activate() Activates this sheet view. This is equivalent to using "Switch To" in the Excel UI.

delete() Removes the sheet view from the worksheet.

duplicate(name) Creates a copy of this sheet view.

getName() Gets or sets the name of the sheet view. The temporary sheet view name is the
empty string (""). Naming the view by using the name property causes the
sheet view to be saved.

setName(name) Gets or sets the name of the sheet view. The temporary sheet view name is the
empty string (""). Naming the view by using the name property causes the
sheet view to be saved.

Method Details

activate()
Activates this sheet view. This is equivalent to using "Switch To" in the Excel UI.

TypeScript

activate(): void;

Returns
void
delete()
Removes the sheet view from the worksheet.

TypeScript

delete(): void;

Returns
void

duplicate(name)
Creates a copy of this sheet view.

TypeScript

duplicate(name?: string): NamedSheetView;

Parameters
name string
The name of the duplicated sheet view. If no name is provided, one will be
generated.

Returns
ExcelScript.NamedSheetView

getName()
Gets or sets the name of the sheet view. The temporary sheet view name is the
empty string (""). Naming the view by using the name property causes the sheet view
to be saved.

TypeScript

getName(): string;

Returns
string

setName(name)
Gets or sets the name of the sheet view. The temporary sheet view name is the
empty string (""). Naming the view by using the name property causes the sheet view
to be saved.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.NumberFormatInfo interface
Reference
Package: ExcelScript

Defines the culturally appropriate format of displaying numbers. This is based on current
system culture settings.

Methods
ノ Expand table

getNumberDecimal Gets the string used as the decimal separator for numeric values. This is
Separator() based on current system settings.

getNumberGroup Gets the string used to separate groups of digits to the left of the decimal
Separator() for numeric values. This is based on current system settings.

Method Details

getNumberDecimalSeparator()
Gets the string used as the decimal separator for numeric values. This is based on
current system settings.

TypeScript

getNumberDecimalSeparator(): string;

Returns
string

getNumberGroupSeparator()
Gets the string used to separate groups of digits to the left of the decimal for
numeric values. This is based on current system settings.

TypeScript
getNumberGroupSeparator(): string;

Returns
string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PageBreak interface
Reference
Package: ExcelScript

Methods
ノ Expand table

delete() Deletes a page break object.

getCellAfterBreak() Gets the first cell after the page break.

getColumnIndex() Specifies the column index for the page break.

Method Details

delete()
Deletes a page break object.

TypeScript

delete(): void;

Returns
void

getCellAfterBreak()
Gets the first cell after the page break.

TypeScript

getCellAfterBreak(): Range;

Returns
ExcelScript.Range
getColumnIndex()
Specifies the column index for the page break.

TypeScript

getColumnIndex(): number;

Returns
number

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PageLayout interface
Reference
Package: ExcelScript

Represents layout and print settings that are not dependent on any printer-specific
implementation. These settings include margins, orientation, page numbering, title rows,
and print area.

Remarks

Examples

TypeScript

/**
* This script sets some basic page layout settings for printing.
*/
function main(workbook: ExcelScript.Workbook) {
// Go to each worksheet so the print settings are consistent.
workbook.getWorksheets().forEach((sheet) => {
const pageLayout : ExcelScript.PageLayout = sheet.getPageLayout();

// Turn off draft mode so images are printed.


pageLayout.setDraftMode(false);

// Print on 8.5"x11" paper.


pageLayout.setPaperSize(ExcelScript.PaperType.letter);

// Print every page with a landscape orientation.


pageLayout.setOrientation(ExcelScript.PageOrientation.landscape);
});
}

Methods
ノ Expand table

getBlackAndWhite() The worksheet's black and white print option.

getBottomMargin() The worksheet's bottom page margin to use for printing in points.

getCenterHorizontally() The worksheet's center horizontally flag. This flag determines


whether the worksheet will be centered horizontally when it's
printed.

getCenterVertically() The worksheet's center vertically flag. This flag determines whether
the worksheet will be centered vertically when it's printed.

getDraftMode() The worksheet's draft mode option. If true , the sheet will be
printed without graphics.

getFirstPageNumber() The worksheet's first page number to print. A null value


represents "auto" page numbering.

getFooterMargin() The worksheet's footer margin, in points, for use when printing.

getHeaderMargin() The worksheet's header margin, in points, for use when printing.

getHeadersFooters() Header and footer configuration for the worksheet.

getLeftMargin() The worksheet's left margin, in points, for use when printing.

getOrientation() The worksheet's orientation of the page.

getPaperSize() The worksheet's paper size of the page.

getPrintArea() Gets the RangeAreas object, comprising one or more rectangular


ranges, that represents the print area for the worksheet. If there is
no print area, then this method returns undefined .

getPrintComments() Specifies if the worksheet's comments should be displayed when


printing.

getPrintErrors() The worksheet's print errors option.

getPrintGridlines() Specifies if the worksheet's gridlines will be printed.

getPrintHeadings() Specifies if the worksheet's headings will be printed.

getPrintOrder() The worksheet's page print order option. This specifies the order
to use for processing the page number printed.

getPrintTitleColumns() Gets the range object representing the title columns. If not set,
then this method returns undefined .

getPrintTitleRows() Gets the range object representing the title rows. If not set, then
this method returns undefined .

getRightMargin() The worksheet's right margin, in points, for use when printing.

getTopMargin() The worksheet's top margin, in points, for use when printing.

getZoom() The worksheet's print zoom options. The PageLayoutZoomOptions


object must be set as a JSON object (use x.zoom = {...} instead
of x.zoom.scale = ... ).
setBlackAndWhite(blackAnd The worksheet's black and white print option.
White)

setBottomMargin(bottom The worksheet's bottom page margin to use for printing in points.
Margin)

setCenterHorizontally(center The worksheet's center horizontally flag. This flag determines


Horizontally) whether the worksheet will be centered horizontally when it's
printed.

setCenterVertically(center The worksheet's center vertically flag. This flag determines whether
Vertically) the worksheet will be centered vertically when it's printed.

setDraftMode(draftMode) The worksheet's draft mode option. If true , the sheet will be
printed without graphics.

setFirstPageNumber(first The worksheet's first page number to print. A null value


PageNumber) represents "auto" page numbering.

setFooterMargin(footer The worksheet's footer margin, in points, for use when printing.
Margin)

setHeaderMargin(header The worksheet's header margin, in points, for use when printing.
Margin)

setLeftMargin(leftMargin) The worksheet's left margin, in points, for use when printing.

setOrientation(orientation) The worksheet's orientation of the page.

setPaperSize(paperSize) The worksheet's paper size of the page.

setPrintArea(printArea) Sets the worksheet's print area.

setPrintComments(print Specifies if the worksheet's comments should be displayed when


Comments) printing.

setPrintErrors(printErrors) The worksheet's print errors option.

setPrintGridlines(print Specifies if the worksheet's gridlines will be printed.


Gridlines)

setPrintHeadings(print Specifies if the worksheet's headings will be printed.


Headings)

setPrintMargins(unit, margin Sets the worksheet's page margins with units.


Options)

setPrintOrder(printOrder) The worksheet's page print order option. This specifies the order
to use for processing the page number printed.

setPrintTitleColumns(print Sets the columns that contain the cells to be repeated at the left of
TitleColumns) each page of the worksheet for printing.
setPrintTitleRows(printTitle Sets the rows that contain the cells to be repeated at the top of
Rows) each page of the worksheet for printing.

setRightMargin(right The worksheet's right margin, in points, for use when printing.
Margin)

setTopMargin(topMargin) The worksheet's top margin, in points, for use when printing.

setZoom(zoom) The worksheet's print zoom options. The PageLayoutZoomOptions


object must be set as a JSON object (use x.zoom = {...} instead
of x.zoom.scale = ... ).

Method Details

getBlackAndWhite()
The worksheet's black and white print option.

TypeScript

getBlackAndWhite(): boolean;

Returns
boolean

getBottomMargin()
The worksheet's bottom page margin to use for printing in points.

TypeScript

getBottomMargin(): number;

Returns
number

getCenterHorizontally()
The worksheet's center horizontally flag. This flag determines whether the worksheet
will be centered horizontally when it's printed.
TypeScript

getCenterHorizontally(): boolean;

Returns
boolean

getCenterVertically()
The worksheet's center vertically flag. This flag determines whether the worksheet
will be centered vertically when it's printed.

TypeScript

getCenterVertically(): boolean;

Returns
boolean

getDraftMode()
The worksheet's draft mode option. If true , the sheet will be printed without
graphics.

TypeScript

getDraftMode(): boolean;

Returns
boolean

getFirstPageNumber()
The worksheet's first page number to print. A null value represents "auto" page
numbering.

TypeScript
getFirstPageNumber(): number | "";

Returns
number | ""

getFooterMargin()
The worksheet's footer margin, in points, for use when printing.

TypeScript

getFooterMargin(): number;

Returns
number

getHeaderMargin()
The worksheet's header margin, in points, for use when printing.

TypeScript

getHeaderMargin(): number;

Returns
number

getHeadersFooters()
Header and footer configuration for the worksheet.

TypeScript

getHeadersFooters(): HeaderFooterGroup;

Returns
ExcelScript.HeaderFooterGroup

getLeftMargin()
The worksheet's left margin, in points, for use when printing.

TypeScript

getLeftMargin(): number;

Returns
number

getOrientation()
The worksheet's orientation of the page.

TypeScript

getOrientation(): PageOrientation;

Returns
ExcelScript.PageOrientation

getPaperSize()
The worksheet's paper size of the page.

TypeScript

getPaperSize(): PaperType;

Returns
ExcelScript.PaperType

getPrintArea()
Gets the RangeAreas object, comprising one or more rectangular ranges, that
represents the print area for the worksheet. If there is no print area, then this method
returns undefined .

TypeScript

getPrintArea(): RangeAreas;

Returns
ExcelScript.RangeAreas

getPrintComments()
Specifies if the worksheet's comments should be displayed when printing.

TypeScript

getPrintComments(): PrintComments;

Returns
ExcelScript.PrintComments

getPrintErrors()
The worksheet's print errors option.

TypeScript

getPrintErrors(): PrintErrorType;

Returns
ExcelScript.PrintErrorType

getPrintGridlines()
Specifies if the worksheet's gridlines will be printed.

TypeScript
getPrintGridlines(): boolean;

Returns
boolean

getPrintHeadings()
Specifies if the worksheet's headings will be printed.

TypeScript

getPrintHeadings(): boolean;

Returns
boolean

getPrintOrder()
The worksheet's page print order option. This specifies the order to use for
processing the page number printed.

TypeScript

getPrintOrder(): PrintOrder;

Returns
ExcelScript.PrintOrder

getPrintTitleColumns()
Gets the range object representing the title columns. If not set, then this method
returns undefined .

TypeScript

getPrintTitleColumns(): Range;
Returns
ExcelScript.Range

getPrintTitleRows()
Gets the range object representing the title rows. If not set, then this method returns
undefined .

TypeScript

getPrintTitleRows(): Range;

Returns
ExcelScript.Range

getRightMargin()
The worksheet's right margin, in points, for use when printing.

TypeScript

getRightMargin(): number;

Returns
number

getTopMargin()
The worksheet's top margin, in points, for use when printing.

TypeScript

getTopMargin(): number;

Returns
number
getZoom()
The worksheet's print zoom options. The PageLayoutZoomOptions object must be set
as a JSON object (use x.zoom = {...} instead of x.zoom.scale = ... ).

TypeScript

getZoom(): PageLayoutZoomOptions;

Returns
ExcelScript.PageLayoutZoomOptions

setBlackAndWhite(blackAndWhite)
The worksheet's black and white print option.

TypeScript

setBlackAndWhite(blackAndWhite: boolean): void;

Parameters
blackAndWhite boolean

Returns
void

setBottomMargin(bottomMargin)
The worksheet's bottom page margin to use for printing in points.

TypeScript

setBottomMargin(bottomMargin: number): void;

Parameters
bottomMargin number
Returns
void

setCenterHorizontally(centerHorizontally)
The worksheet's center horizontally flag. This flag determines whether the worksheet
will be centered horizontally when it's printed.

TypeScript

setCenterHorizontally(centerHorizontally: boolean): void;

Parameters
centerHorizontally boolean

Returns
void

setCenterVertically(centerVertically)
The worksheet's center vertically flag. This flag determines whether the worksheet
will be centered vertically when it's printed.

TypeScript

setCenterVertically(centerVertically: boolean): void;

Parameters
centerVertically boolean

Returns
void

setDraftMode(draftMode)
The worksheet's draft mode option. If true , the sheet will be printed without
graphics.
TypeScript

setDraftMode(draftMode: boolean): void;

Parameters
draftMode boolean

Returns
void

Examples

TypeScript

/**
* This script turns off the print setting for draft mode.
*/
function main(workbook: ExcelScript.Workbook) {
// Go to each worksheet so the print settings are consistent.
workbook.getWorksheets().forEach((sheet) => {
const pageLayout = sheet.getPageLayout();

// Turn off draft mode so images are printed.


pageLayout.setDraftMode(false);
});
}

setFirstPageNumber(firstPageNumber)
The worksheet's first page number to print. A null value represents "auto" page
numbering.

TypeScript

setFirstPageNumber(firstPageNumber: number | ""): void;

Parameters
firstPageNumber number | ""

Returns
void

setFooterMargin(footerMargin)
The worksheet's footer margin, in points, for use when printing.

TypeScript

setFooterMargin(footerMargin: number): void;

Parameters
footerMargin number

Returns
void

setHeaderMargin(headerMargin)
The worksheet's header margin, in points, for use when printing.

TypeScript

setHeaderMargin(headerMargin: number): void;

Parameters
headerMargin number

Returns
void

setLeftMargin(leftMargin)
The worksheet's left margin, in points, for use when printing.

TypeScript

setLeftMargin(leftMargin: number): void;


Parameters
leftMargin number

Returns
void

setOrientation(orientation)
The worksheet's orientation of the page.

TypeScript

setOrientation(orientation: PageOrientation): void;

Parameters
orientation ExcelScript.PageOrientation

Returns
void

Examples

TypeScript

/**
* This script sets the printing orientation for the entire workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Go to each worksheet so the print settings are consistent.
workbook.getWorksheets().forEach((sheet) => {
const pageLayout = sheet.getPageLayout();

// Print every page with a landscape orientation.


pageLayout.setOrientation(ExcelScript.PageOrientation.landscape);
});
}

setPaperSize(paperSize)
The worksheet's paper size of the page.
TypeScript

setPaperSize(paperSize: PaperType): void;

Parameters
paperSize ExcelScript.PaperType

Returns
void

Examples

TypeScript

/**
* This script sets the page size for printing.
*/
function main(workbook: ExcelScript.Workbook) {
// Go to each worksheet so the print settings are consistent.
workbook.getWorksheets().forEach((sheet) => {
const pageLayout = sheet.getPageLayout();
// Print on 8.5"x11" paper.
pageLayout.setPaperSize(ExcelScript.PaperType.letter);
});
}

setPrintArea(printArea)
Sets the worksheet's print area.

TypeScript

setPrintArea(printArea: Range | RangeAreas | string): void;

Parameters
printArea ExcelScript.Range | ExcelScript.RangeAreas | string
The range or ranges of the content to print.

Returns
void

setPrintComments(printComments)
Specifies if the worksheet's comments should be displayed when printing.

TypeScript

setPrintComments(printComments: PrintComments): void;

Parameters
printComments ExcelScript.PrintComments

Returns
void

Examples

TypeScript

/**
* This script makes the comments print at the end of the worksheet
* when the workbook is printed.
*/
function main(workbook: ExcelScript.Workbook) {
// Access every worksheet in the workbook.
workbook.getWorksheets().forEach(worksheet => {
// Get the page layout for each sheet.
const layout = worksheet.getPageLayout();

// Change the comment printing settings to print them at the end of


the sheet.
layout.setPrintComments(ExcelScript.PrintComments.endSheet);
});
}

setPrintErrors(printErrors)
The worksheet's print errors option.

TypeScript
setPrintErrors(printErrors: PrintErrorType): void;

Parameters
printErrors ExcelScript.PrintErrorType

Returns
void

setPrintGridlines(printGridlines)
Specifies if the worksheet's gridlines will be printed.

TypeScript

setPrintGridlines(printGridlines: boolean): void;

Parameters
printGridlines boolean

Returns
void

setPrintHeadings(printHeadings)
Specifies if the worksheet's headings will be printed.

TypeScript

setPrintHeadings(printHeadings: boolean): void;

Parameters
printHeadings boolean

Returns
void
setPrintMargins(unit, marginOptions)
Sets the worksheet's page margins with units.

TypeScript

setPrintMargins(
unit: PrintMarginUnit,
marginOptions: PageLayoutMarginOptions
): void;

Parameters
unit ExcelScript.PrintMarginUnit
Measurement unit for the margins provided.

marginOptions ExcelScript.PageLayoutMarginOptions
Margin values to set. Margins not provided remain unchanged.

Returns
void

setPrintOrder(printOrder)
The worksheet's page print order option. This specifies the order to use for
processing the page number printed.

TypeScript

setPrintOrder(printOrder: PrintOrder): void;

Parameters
printOrder ExcelScript.PrintOrder

Returns
void

Examples
TypeScript

/**
* This script sets the print order for every worksheet in the workbook.
* The order of printed content will go over (e.g., left-to-right)
* then down (i.e., top-to-bottom).
*/
function main(workbook: ExcelScript.Workbook) {
// Access every worksheet in the workbook.
workbook.getWorksheets().forEach(worksheet => {
// Get the page layout for each sheet.
const layout: ExcelScript.PageLayout = worksheet.getPageLayout();

// Set the print order to over-then-down.


layout.setPrintOrder(ExcelScript.PrintOrder.overThenDown);
});
}

setPrintTitleColumns(printTitleColumns)
Sets the columns that contain the cells to be repeated at the left of each page of the
worksheet for printing.

TypeScript

setPrintTitleColumns(printTitleColumns: Range | string): void;

Parameters
printTitleColumns ExcelScript.Range | string
The columns to be repeated to the left of each page. The range must span the entire
column to be valid.

Returns
void

setPrintTitleRows(printTitleRows)
Sets the rows that contain the cells to be repeated at the top of each page of the
worksheet for printing.

TypeScript
setPrintTitleRows(printTitleRows: Range | string): void;

Parameters
printTitleRows ExcelScript.Range | string
The rows to be repeated at the top of each page. The range must span the entire
row to be valid.

Returns
void

setRightMargin(rightMargin)
The worksheet's right margin, in points, for use when printing.

TypeScript

setRightMargin(rightMargin: number): void;

Parameters
rightMargin number

Returns
void

setTopMargin(topMargin)
The worksheet's top margin, in points, for use when printing.

TypeScript

setTopMargin(topMargin: number): void;

Parameters
topMargin number
Returns
void

setZoom(zoom)
The worksheet's print zoom options. The PageLayoutZoomOptions object must be set
as a JSON object (use x.zoom = {...} instead of x.zoom.scale = ... ).

TypeScript

setZoom(zoom: PageLayoutZoomOptions): void;

Parameters
zoom ExcelScript.PageLayoutZoomOptions

Returns
void

Examples

TypeScript

/**
* This script changes the scale-to-fit of the page layout.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
const sheet = workbook.getActiveWorksheet();

// Scale the layout to half size for printing.


const layout = sheet.getPageLayout();
const zoomOptions: ExcelScript.PageLayoutZoomOptions = {
scale: 50
}
layout.setZoom(zoomOptions)
}

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
be found on GitHub, where you Select a link to provide feedback:
can also create and review
issues and pull requests. For  Open a documentation issue
more information, see our
contributor guide.  Provide product feedback
ExcelScript.PageLayoutMarginOptions
interface
Reference
Package: ExcelScript

Represents the options in page layout margins.

Properties
ノ Expand table

bottom Specifies the page layout bottom margin in the unit specified to use for printing.

footer Specifies the page layout footer margin in the unit specified to use for printing.

header Specifies the page layout header margin in the unit specified to use for printing.

left Specifies the page layout left margin in the unit specified to use for printing.

right Specifies the page layout right margin in the unit specified to use for printing.

top Specifies the page layout top margin in the unit specified to use for printing.

Property Details

bottom
Specifies the page layout bottom margin in the unit specified to use for printing.

TypeScript

bottom?: number;

Property Value
number

footer
Specifies the page layout footer margin in the unit specified to use for printing.
TypeScript

footer?: number;

Property Value
number

header
Specifies the page layout header margin in the unit specified to use for printing.

TypeScript

header?: number;

Property Value
number

left
Specifies the page layout left margin in the unit specified to use for printing.

TypeScript

left?: number;

Property Value
number

right
Specifies the page layout right margin in the unit specified to use for printing.

TypeScript

right?: number;
Property Value
number

top
Specifies the page layout top margin in the unit specified to use for printing.

TypeScript

top?: number;

Property Value
number

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PageLayoutZoomOptions
interface
Reference
Package: ExcelScript

Represents page zoom properties.

Remarks

Examples

TypeScript

/**
* This script changes the scale-to-fit of the page layout.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
const sheet = workbook.getActiveWorksheet();

// Scale the layout to half size for printing.


const layout = sheet.getPageLayout();
const zoomOptions: ExcelScript.PageLayoutZoomOptions = {
scale: 50
}
layout.setZoom(zoomOptions)
}

Properties
ノ Expand table

horizontalFit Number of pages to fit horizontally. This value can be null if percentage scale
ToPages is used.

scale Print page scale value can be between 10 and 400. This value can be null if fit
to page tall or wide is specified.

verticalFit Number of pages to fit vertically. This value can be null if percentage scale is
ToPages used.
Property Details

horizontalFitToPages
Number of pages to fit horizontally. This value can be null if percentage scale is
used.

TypeScript

horizontalFitToPages?: number;

Property Value
number

scale
Print page scale value can be between 10 and 400. This value can be null if fit to
page tall or wide is specified.

TypeScript

scale?: number;

Property Value
number

verticalFitToPages
Number of pages to fit vertically. This value can be null if percentage scale is used.

TypeScript

verticalFitToPages?: number;

Property Value
number
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotDateFilter interface
Reference
Package: ExcelScript

Configurable template for a date filter to apply to a PivotField. The condition defines
what criteria need to be set in order for the filter to operate.

Properties
ノ Expand table

comparator The comparator is the static value to which other values are compared. The type of
comparison is defined by the condition.

condition Specifies the condition for the filter, which defines the necessary filtering criteria.

exclusive If true , filter excludes items that meet criteria. The default is false (filter to include
items that meet criteria).

lowerBound The lower-bound of the range for the between filter condition.

upper The upper-bound of the range for the between filter condition.
Bound

wholeDays For equals , before , after , and between filter conditions, indicates if comparisons
should be made as whole days.

Property Details

comparator
The comparator is the static value to which other values are compared. The type of
comparison is defined by the condition.

TypeScript

comparator?: FilterDatetime;

Property Value
ExcelScript.FilterDatetime
condition
Specifies the condition for the filter, which defines the necessary filtering criteria.

TypeScript

condition: DateFilterCondition;

Property Value
ExcelScript.DateFilterCondition

Examples

TypeScript

/**
* This script applies a filter to a PivotTable that filters out rows
* that aren't from this month.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the "Date Recorded" field to filter.
// The data in this field must be dates in order for the filter to
work.
const pivot = workbook.getPivotTables()[0];
const rowHierarchy = pivot.getRowHierarchy("Date Recorded");
const rowField = rowHierarchy.getFields()[0];

// Apply the date filter.


rowField.applyFilter({
dateFilter: {
// Setting the condition to `thisMonth` means items that are before
or
// after this month will not be displayed.
condition: ExcelScript.DateFilterCondition.thisMonth
}
});
}

exclusive
If true , filter excludes items that meet criteria. The default is false (filter to include
items that meet criteria).

TypeScript
exclusive?: boolean;

Property Value
boolean

lowerBound
The lower-bound of the range for the between filter condition.

TypeScript

lowerBound?: FilterDatetime;

Property Value
ExcelScript.FilterDatetime

Examples

TypeScript

/**
* This script applies a filter to a PivotTable that filters it
* to only show rows from between June 20th, 2022 and July 10th, 2022.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the "Date Recorded" field to filter.
// The data in this field must be dates in order for the filter to
work.
const pivot = workbook.getPivotTables()[0];
const rowHierarchy = pivot.getRowHierarchy("Date Recorded");
const rowField = rowHierarchy.getFields()[0];

// Create the filter's date boundaries.


let earliestDate: ExcelScript.FilterDatetime = {
date: "2022-06-20",
specificity: ExcelScript.FilterDatetimeSpecificity.day
};
let latestDate: ExcelScript.FilterDatetime = {
date: "2022-07-10",
specificity: ExcelScript.FilterDatetimeSpecificity.day
};

// Apply the date filter.


rowField.applyFilter({
dateFilter: {
condition: ExcelScript.DateFilterCondition.between,
lowerBound: earliestDate,
upperBound: latestDate
}
});
}

upperBound
The upper-bound of the range for the between filter condition.

TypeScript

upperBound?: FilterDatetime;

Property Value
ExcelScript.FilterDatetime

wholeDays
For equals , before , after , and between filter conditions, indicates if comparisons
should be made as whole days.

TypeScript

wholeDays?: boolean;

Property Value
boolean

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.PivotField interface
Reference
Package: ExcelScript

Represents the Excel PivotField.

Methods
ノ Expand table

applyFilter(filter) Sets one or more of the field's current PivotFilters and applies
them to the field. If the provided filters are invalid or cannot be
applied, an exception is thrown.

clearAllFilters() Clears all criteria from all of the field's filters. This removes any
active filtering on the field.

clearFilter(filterType) Clears all existing criteria from the field's filter of the given type (if
one is currently applied).

getFilters() Gets all filters currently applied on the field.

getId() ID of the PivotField.

getItems() Returns the PivotItems associated with the PivotField.

getName() Name of the PivotField.

getPivotItem(name) Gets a PivotItem by name. If the PivotItem does not exist, then
this method returns undefined .

getShowAllItems() Determines whether to show all items of the PivotField.

getSubtotals() Subtotals of the PivotField.

isFiltered(filterType) Checks if there are any applied filters on the field.

setName(name) Name of the PivotField.

setShowAllItems(showAll Determines whether to show all items of the PivotField.


Items)

setSubtotals(subtotals) Subtotals of the PivotField.

sortByLabels(sortBy) Sorts the PivotField. If a DataPivotHierarchy is specified, then sort


will be applied based on it, if not sort will be based on the
PivotField itself.
sortByValues(sortBy, values Sorts the PivotField by specified values in a given scope. The
Hierarchy, pivotItemScope) scope defines which specific values will be used to sort when
there are multiple values from the same DataPivotHierarchy.

Method Details

applyFilter(filter)
Sets one or more of the field's current PivotFilters and applies them to the field. If
the provided filters are invalid or cannot be applied, an exception is thrown.

TypeScript

applyFilter(filter: PivotFilters): void;

Parameters
filter ExcelScript.PivotFilters
A configured specific PivotFilter, or a PivotFilters interface containing multiple
configured filters.

Returns
void

Examples

TypeScript

/**
* This script applies a PivotValueFilter to the first row hierarchy in
the PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable on the current worksheet.
let sheet = workbook.getActiveWorksheet();
let pivotTable = sheet.getPivotTables()[0];

// Get the first row hierarchy to use as the field which gets filtered.
let rowHierarchy = pivotTable.getRowHierarchies()[0];

// Get the first data hierarchy to use as the values for filtering the
rows.
let dataHierarchy = pivotTable.getDataHierarchies()[0];
// Create a filter that excludes values greater than 500.
let filter: ExcelScript.PivotValueFilter = {
condition: ExcelScript.ValueFilterCondition.greaterThan,
comparator: 500,
value: dataHierarchy.getName()
};

// Apply the filter.


rowHierarchy.getPivotField(rowHierarchy.getName()).applyFilter({
valueFilter: filter
});
}

clearAllFilters()
Clears all criteria from all of the field's filters. This removes any active filtering on the
field.

TypeScript

clearAllFilters(): void;

Returns
void

clearFilter(filterType)
Clears all existing criteria from the field's filter of the given type (if one is currently
applied).

TypeScript

clearFilter(filterType: PivotFilterType): void;

Parameters
filterType ExcelScript.PivotFilterType
The type of filter on the field of which to clear all criteria.

Returns
void
Examples

TypeScript

/**
* This script gets the "Type" field from the "Farms Sales" PivotTable
* and clears the value filter from it.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Sales".
const pivot = workbook.getPivotTable("Farm Sales");

// Get the "Type" field.


const typeField = pivot.getHierarchy("Type").getPivotField("Type");

// Clear the value filter (if there is one) from the field.
typeField.clearFilter(ExcelScript.PivotFilterType.value);
}

getFilters()
Gets all filters currently applied on the field.

TypeScript

getFilters(): PivotFilters;

Returns
ExcelScript.PivotFilters

getId()
ID of the PivotField.

TypeScript

getId(): string;

Returns
string

getItems()
Returns the PivotItems associated with the PivotField.

TypeScript

getItems(): PivotItem[];

Returns
ExcelScript.PivotItem[]

getName()
Name of the PivotField.

TypeScript

getName(): string;

Returns
string

getPivotItem(name)
Gets a PivotItem by name. If the PivotItem does not exist, then this method returns
undefined .

TypeScript

getPivotItem(name: string): PivotItem | undefined;

Parameters
name string
Name of the PivotItem to be retrieved.

Returns
ExcelScript.PivotItem | undefined

getShowAllItems()
Determines whether to show all items of the PivotField.

TypeScript

getShowAllItems(): boolean;

Returns
boolean

getSubtotals()
Subtotals of the PivotField.

TypeScript

getSubtotals(): Subtotals;

Returns
ExcelScript.Subtotals

isFiltered(filterType)
Checks if there are any applied filters on the field.

TypeScript

isFiltered(filterType?: PivotFilterType): boolean;

Parameters
filterType ExcelScript.PivotFilterType
The filter type to check. If no type is provided, this method will check if any filter is
applied.

Returns
boolean

setName(name)
Name of the PivotField.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

setShowAllItems(showAllItems)
Determines whether to show all items of the PivotField.

TypeScript

setShowAllItems(showAllItems: boolean): void;

Parameters
showAllItems boolean

Returns
void

setSubtotals(subtotals)
Subtotals of the PivotField.

TypeScript

setSubtotals(subtotals: Subtotals): void;

Parameters
subtotals ExcelScript.Subtotals
Returns
void

sortByLabels(sortBy)
Sorts the PivotField. If a DataPivotHierarchy is specified, then sort will be applied
based on it, if not sort will be based on the PivotField itself.

TypeScript

sortByLabels(sortBy: SortBy): void;

Parameters
sortBy ExcelScript.SortBy
Specifies if the sorting is done in ascending or descending order.

Returns
void

sortByValues(sortBy, valuesHierarchy, pivotItemScope)


Sorts the PivotField by specified values in a given scope. The scope defines which
specific values will be used to sort when there are multiple values from the same
DataPivotHierarchy.

TypeScript

sortByValues(
sortBy: SortBy,
valuesHierarchy: DataPivotHierarchy,
pivotItemScope?: Array<PivotItem | string>
): void;

Parameters
sortBy ExcelScript.SortBy
Specifies if the sorting is done in ascending or descending order.

valuesHierarchy ExcelScript.DataPivotHierarchy
Specifies the values hierarchy on the data axis to be used for sorting.
pivotItemScope Array<ExcelScript.PivotItem | string>
The items that should be used for the scope of the sorting. These will be the items
that make up the row or column that you want to sort on. If a string is used instead
of a PivotItem, the string represents the ID of the PivotItem. If there are no items
other than data hierarchy on the axis you want to sort on, this can be empty.

Returns
void

Examples

TypeScript

/**
* This sample sorts the rows of a PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get an existing PivotTable.
const pivotTable = workbook.getPivotTable("Farm Sales");

// Get the data hierarchy to use as the basis of the sort.


const valueFieldToSortOn = pivotTable.getDataHierarchy("Sum of Crates
Sold Wholesale");

// Get the row to sort.


const rowToSort = pivotTable.getRowHierarchy("Farm");

// Sort the "Farm" row's only field by the values in "Sum of Crates
Sold Wholesale".
rowToSort.getFields()[0].sortByValues(ExcelScript.SortBy.descending,
valueFieldToSortOn);
}

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotFilters interface
Reference
Package: ExcelScript

An interface representing all PivotFilters currently applied to a given PivotField.

Properties
ノ Expand table

dateFilter The PivotField's currently applied date filter. This property is null if no value filter is
applied.

labelFilter The PivotField's currently applied label filter. This property is null if no value filter
is applied.

manual The PivotField's currently applied manual filter. This property is null if no value
Filter filter is applied.

valueFilter The PivotField's currently applied value filter. This property is null if no value filter
is applied.

Property Details

dateFilter
The PivotField's currently applied date filter. This property is null if no value filter is
applied.

TypeScript

dateFilter?: PivotDateFilter;

Property Value
ExcelScript.PivotDateFilter

Examples

TypeScript
/**
* This script applies a filter to a PivotTable that filters out rows
* that aren't from this month.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the "Date Recorded" field to filter.
// The data in this field must be dates in order for the filter to
work.
const pivot = workbook.getPivotTables()[0];
const rowHierarchy = pivot.getRowHierarchy("Date Recorded");
const rowField = rowHierarchy.getFields()[0];

// Apply the date filter.


rowField.applyFilter({
dateFilter: {
// Setting the condition to `thisMonth` means items that are before
or
// after this month will not be displayed.
condition: ExcelScript.DateFilterCondition.thisMonth
}
});
}

labelFilter
The PivotField's currently applied label filter. This property is null if no value filter is
applied.

TypeScript

labelFilter?: PivotLabelFilter;

Property Value
ExcelScript.PivotLabelFilter

Examples

TypeScript

/**
* This script filters items that start with "L" from the "Type" field
* of the "Farm Sales" PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable.
const pivotTable = workbook.getActiveWorksheet().getPivotTable("Farm
Sales");

// Get the "Type" field.


const field = pivotTable.getHierarchy("Type").getPivotField("Type");

// Filter out any types that start with "L" (such as "Lemons" and
"Limes").
const filter: ExcelScript.PivotLabelFilter = {
condition: ExcelScript.LabelFilterCondition.beginsWith,
substring: "L",
exclusive: true
};

// Apply the label filter to the field.


field.applyFilter({ labelFilter: filter });
}

manualFilter
The PivotField's currently applied manual filter. This property is null if no value filter
is applied.

TypeScript

manualFilter?: PivotManualFilter;

Property Value
ExcelScript.PivotManualFilter

Examples

TypeScript

/**
* This script adds a manual filter to a PivotTable.
*/
function main(workbook: ExcelScript.Workbook)
{
// Get the first PivotTable in the workbook.
const pivot = workbook.getPivotTables()[0];

// Get the hierarchy to use as the filter.


const location = pivot.getHierarchy("Location");

// Use "Location" as the FilterHierarchy.


pivot.addFilterHierarchy(location);
// Select items for the filter.
// Note that hierarchies and fields have a 1:1 relationship in Excel,
// so `getFields()[0]` always gets the correct field.
location.getFields()[0].applyFilter({
manualFilter: {
selectedItems: ["Seattle", "Chicago"]
}
});
}

valueFilter
The PivotField's currently applied value filter. This property is null if no value filter is
applied.

TypeScript

valueFilter?: PivotValueFilter;

Property Value
ExcelScript.PivotValueFilter

Examples

TypeScript

/**
* This script applies a PivotValueFilter to the first row hierarchy in
the PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable on the current worksheet.
let sheet = workbook.getActiveWorksheet();
let pivotTable = sheet.getPivotTables()[0];

// Get the first row hierarchy to use as the field which gets filtered.
let rowHierarchy = pivotTable.getRowHierarchies()[0];

// Get the first data hierarchy to use as the values for filtering the
rows.
let dataHierarchy = pivotTable.getDataHierarchies()[0];

// Create a filter that excludes values greater than 500.


let filter: ExcelScript.PivotValueFilter = {
condition: ExcelScript.ValueFilterCondition.greaterThan,
comparator: 500,
value: dataHierarchy.getName()
};

// Apply the filter.


rowHierarchy.getPivotField(rowHierarchy.getName()).applyFilter({
valueFilter: filter
});
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotHierarchy interface
Reference
Package: ExcelScript

Represents the Excel PivotHierarchy.

Remarks

Examples

TypeScript

/**
* This script creates a PivotTable from an existing table and adds it to a
new worksheet.
* This script assumes there is a table in the current worksheet with
columns named "Type" and "Sales".
*/
function main(workbook: ExcelScript.Workbook) {
// Create a PivotTable based on a table in the current worksheet.
let sheet = workbook.getActiveWorksheet();
let table = sheet.getTables()[0];

// Add the PivotTable to a new worksheet.


let newSheet = workbook.addWorksheet("Pivot");
let pivotTable = newSheet.addPivotTable("My Pivot", table, "A1");

// Add fields to the PivotTable to show "Sales" per "Type".


pivotTable.addRowHierarchy(pivotTable.getHierarchy("Type"));
pivotTable.addDataHierarchy(pivotTable.getHierarchy("Sales"));
}

Methods
ノ Expand table

getFields() Returns the PivotFields associated with the PivotHierarchy.

getId() ID of the PivotHierarchy.

getName() Name of the PivotHierarchy.

getPivot Gets a PivotField by name. If the PivotField does not exist, then this method
Field(name) returns undefined .
setName(name) Name of the PivotHierarchy.

Method Details

getFields()
Returns the PivotFields associated with the PivotHierarchy.

TypeScript

getFields(): PivotField[];

Returns
ExcelScript.PivotField[]

getId()
ID of the PivotHierarchy.

TypeScript

getId(): string;

Returns
string

getName()
Name of the PivotHierarchy.

TypeScript

getName(): string;

Returns
string
getPivotField(name)
Gets a PivotField by name. If the PivotField does not exist, then this method returns
undefined .

TypeScript

getPivotField(name: string): PivotField | undefined;

Parameters
name string
Name of the PivotField to be retrieved.

Returns
ExcelScript.PivotField | undefined

setName(name)
Name of the PivotHierarchy.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our  Provide product feedback
contributor guide.
ExcelScript.PivotItem interface
Reference
Package: ExcelScript

Represents the Excel PivotItem.

Methods
ノ Expand table

getId() ID of the PivotItem.

getIsExpanded() Determines whether the item is expanded to show child items or if it's
collapsed and child items are hidden.

getName() Name of the PivotItem.

getVisible() Specifies if the PivotItem is visible.

setIsExpanded(is Determines whether the item is expanded to show child items or if it's
Expanded) collapsed and child items are hidden.

setName(name) Name of the PivotItem.

setVisible(visible) Specifies if the PivotItem is visible.

Method Details

getId()
ID of the PivotItem.

TypeScript

getId(): string;

Returns
string

getIsExpanded()
Determines whether the item is expanded to show child items or if it's collapsed and
child items are hidden.

TypeScript

getIsExpanded(): boolean;

Returns
boolean

getName()
Name of the PivotItem.

TypeScript

getName(): string;

Returns
string

getVisible()
Specifies if the PivotItem is visible.

TypeScript

getVisible(): boolean;

Returns
boolean

setIsExpanded(isExpanded)
Determines whether the item is expanded to show child items or if it's collapsed and
child items are hidden.

TypeScript
setIsExpanded(isExpanded: boolean): void;

Parameters
isExpanded boolean

Returns
void

setName(name)
Name of the PivotItem.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

setVisible(visible)
Specifies if the PivotItem is visible.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotLabelFilter interface
Reference
Package: ExcelScript

Configurable template for a label filter to apply to a PivotField. The condition defines
what criteria need to be set in order for the filter to operate.

Remarks

Examples

TypeScript

/**
* This script filters items that start with "L" from the "Type" field
* of the "Farm Sales" PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable.
const pivotTable = workbook.getActiveWorksheet().getPivotTable("Farm
Sales");

// Get the "Type" field.


const field = pivotTable.getHierarchy("Type").getPivotField("Type");

// Filter out any types that start with "L" (such as "Lemons" and
"Limes").
const filter: ExcelScript.PivotLabelFilter = {
condition: ExcelScript.LabelFilterCondition.beginsWith,
substring: "L",
exclusive: true
};

// Apply the label filter to the field.


field.applyFilter({ labelFilter: filter });
}

Properties
ノ Expand table

condition Specifies the condition for the filter, which defines the necessary filtering criteria.
exclusive If true , filter excludes items that meet criteria. The default is false (filter to include
items that meet criteria).

lower The lower-bound of the range for the between filter condition. Note: A numeric
Bound string is treated as a number when being compared against other numeric strings.

substring The substring used for the beginsWith , endsWith , and contains filter conditions.

upper The upper-bound of the range for the between filter condition. Note: A numeric
Bound string is treated as a number when being compared against other numeric strings.

Property Details

condition
Specifies the condition for the filter, which defines the necessary filtering criteria.

TypeScript

condition: LabelFilterCondition;

Property Value
ExcelScript.LabelFilterCondition

exclusive
If true , filter excludes items that meet criteria. The default is false (filter to include
items that meet criteria).

TypeScript

exclusive?: boolean;

Property Value
boolean

lowerBound
The lower-bound of the range for the between filter condition. Note: A numeric
string is treated as a number when being compared against other numeric strings.

TypeScript

lowerBound?: string;

Property Value
string

substring
The substring used for the beginsWith , endsWith , and contains filter conditions.

TypeScript

substring?: string;

Property Value
string

upperBound
The upper-bound of the range for the between filter condition. Note: A numeric
string is treated as a number when being compared against other numeric strings.

TypeScript

upperBound?: string;

Property Value
string

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
be found on GitHub, where you Select a link to provide feedback:
can also create and review
issues and pull requests. For  Open a documentation issue
more information, see our
contributor guide.  Provide product feedback
ExcelScript.PivotLayout interface
Reference
Package: ExcelScript

Represents the visual layout of the PivotTable.

Methods
ノ Expand table

getAutoFormat() Specifies if formatting will be automatically formatted when it's


refreshed or when fields are moved.

getBodyAndTotalRange() Returns the range where the PivotTable's data values reside.

getColumnLabelRange() Returns the range where the PivotTable's column labels reside.

getDataHierarchy(cell) Gets the DataHierarchy that is used to calculate the value in a


specified range within the PivotTable.

getEnableFieldList() Specifies if the field list can be shown in the UI.

getFilterAxisRange() Returns the range of the PivotTable's filter area.

getLayoutType() This property indicates the PivotLayoutType of all fields on the


PivotTable. If fields have different states, this will be null.

getPreserveFormatting() Specifies if formatting is preserved when the report is refreshed


or recalculated by operations such as pivoting, sorting, or
changing page field items.

getRange() Returns the range the PivotTable exists on, excluding the filter
area.

getRowLabelRange() Returns the range where the PivotTable's row labels reside.

getShowColumnGrand Specifies if the PivotTable report shows grand totals for columns.
Totals()

getShowRowGrandTotals() Specifies if the PivotTable report shows grand totals for rows.

getSubtotalLocation() This property indicates the SubtotalLocationType of all fields on


the PivotTable. If fields have different states, this will be null .

setAutoFormat(autoFormat) Specifies if formatting will be automatically formatted when it's


refreshed or when fields are moved.
setAutoSortOnCell(cell, sort Sets the PivotTable to automatically sort using the specified cell
By) to automatically select all necessary criteria and context. This
behaves identically to applying an autosort from the UI.

setEnableFieldList(enable Specifies if the field list can be shown in the UI.


FieldList)

setLayoutType(layoutType) This property indicates the PivotLayoutType of all fields on the


PivotTable. If fields have different states, this will be null.

setPreserve Specifies if formatting is preserved when the report is refreshed


Formatting(preserve or recalculated by operations such as pivoting, sorting, or
Formatting) changing page field items.

setShowColumnGrand Specifies if the PivotTable report shows grand totals for columns.
Totals(showColumnGrand
Totals)

setShowRowGrand Specifies if the PivotTable report shows grand totals for rows.
Totals(showRowGrandTotals)

setSubtotalLocation(subtotal This property indicates the SubtotalLocationType of all fields on


Location) the PivotTable. If fields have different states, this will be null .

Method Details

getAutoFormat()
Specifies if formatting will be automatically formatted when it's refreshed or when
fields are moved.

TypeScript

getAutoFormat(): boolean;

Returns
boolean

getBodyAndTotalRange()
Returns the range where the PivotTable's data values reside.

TypeScript
getBodyAndTotalRange(): Range;

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This sample finds the first PivotTable in the workbook and logs the
values in the "Grand Total" cells.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first PivotTable in the workbook.
let pivotTable = workbook.getPivotTables()[0];

// Get the names of each data column in the PivotTable.


let pivotColumnLabelRange =
pivotTable.getLayout().getColumnLabelRange();

// Get the range displaying the pivoted data.


let pivotDataRange = pivotTable.getLayout().getBodyAndTotalRange();

// Get the range with the "grand totals" for the PivotTable columns.
let grandTotalRange = pivotDataRange.getLastRow();

// Print each of the "Grand Totals" to the console.


grandTotalRange.getValues()[0].forEach((column, columnIndex) => {
console.log(`Grand total of ${pivotColumnLabelRange.getValues()[0]
[columnIndex]}: ${grandTotalRange.getValues()[0][columnIndex]}`);
// Example log: "Grand total of Sum of Crates Sold Wholesale: 11000"
});
}

getColumnLabelRange()
Returns the range where the PivotTable's column labels reside.

TypeScript

getColumnLabelRange(): Range;

Returns
ExcelScript.Range

getDataHierarchy(cell)
Gets the DataHierarchy that is used to calculate the value in a specified range within
the PivotTable.

TypeScript

getDataHierarchy(cell: Range | string): DataPivotHierarchy;

Parameters
cell ExcelScript.Range | string
A single cell within the PivotTable data body.

Returns
ExcelScript.DataPivotHierarchy

getEnableFieldList()
Specifies if the field list can be shown in the UI.

TypeScript

getEnableFieldList(): boolean;

Returns
boolean

getFilterAxisRange()
Returns the range of the PivotTable's filter area.

TypeScript

getFilterAxisRange(): Range;

Returns
ExcelScript.Range

getLayoutType()
This property indicates the PivotLayoutType of all fields on the PivotTable. If fields
have different states, this will be null.

TypeScript

getLayoutType(): PivotLayoutType;

Returns
ExcelScript.PivotLayoutType

getPreserveFormatting()
Specifies if formatting is preserved when the report is refreshed or recalculated by
operations such as pivoting, sorting, or changing page field items.

TypeScript

getPreserveFormatting(): boolean;

Returns
boolean

getRange()
Returns the range the PivotTable exists on, excluding the filter area.

TypeScript

getRange(): Range;

Returns
ExcelScript.Range

getRowLabelRange()
Returns the range where the PivotTable's row labels reside.

TypeScript

getRowLabelRange(): Range;

Returns
ExcelScript.Range

getShowColumnGrandTotals()
Specifies if the PivotTable report shows grand totals for columns.

TypeScript

getShowColumnGrandTotals(): boolean;

Returns
boolean

getShowRowGrandTotals()
Specifies if the PivotTable report shows grand totals for rows.

TypeScript

getShowRowGrandTotals(): boolean;

Returns
boolean

getSubtotalLocation()
This property indicates the SubtotalLocationType of all fields on the PivotTable. If
fields have different states, this will be null .

TypeScript
getSubtotalLocation(): SubtotalLocationType;

Returns
ExcelScript.SubtotalLocationType

setAutoFormat(autoFormat)
Specifies if formatting will be automatically formatted when it's refreshed or when
fields are moved.

TypeScript

setAutoFormat(autoFormat: boolean): void;

Parameters
autoFormat boolean

Returns
void

setAutoSortOnCell(cell, sortBy)
Sets the PivotTable to automatically sort using the specified cell to automatically
select all necessary criteria and context. This behaves identically to applying an
autosort from the UI.

TypeScript

setAutoSortOnCell(cell: Range | string, sortBy: SortBy): void;

Parameters
cell ExcelScript.Range | string
A single cell to use get the criteria from for applying the autosort.

sortBy ExcelScript.SortBy
The direction of the sort.
Returns
void

setEnableFieldList(enableFieldList)
Specifies if the field list can be shown in the UI.

TypeScript

setEnableFieldList(enableFieldList: boolean): void;

Parameters
enableFieldList boolean

Returns
void

setLayoutType(layoutType)
This property indicates the PivotLayoutType of all fields on the PivotTable. If fields
have different states, this will be null.

TypeScript

setLayoutType(layoutType: PivotLayoutType): void;

Parameters
layoutType ExcelScript.PivotLayoutType

Returns
void

Examples

TypeScript

/**
* This script sets the layout of the "Farms Sales" PivotTable to the
"tabular"
* setting. This places the fields from the Rows area in separate
columns.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Sales".
const pivot = workbook.getPivotTable("Farm Sales");

// Get the PivotLayout object.


const layout = pivot.getLayout();

// Set the layout type to "tabular".


layout.setLayoutType(ExcelScript.PivotLayoutType.tabular);
}

setPreserveFormatting(preserveFormatting)
Specifies if formatting is preserved when the report is refreshed or recalculated by
operations such as pivoting, sorting, or changing page field items.

TypeScript

setPreserveFormatting(preserveFormatting: boolean): void;

Parameters
preserveFormatting boolean

Returns
void

setShowColumnGrandTotals(showColumnGrandTotals)
Specifies if the PivotTable report shows grand totals for columns.

TypeScript

setShowColumnGrandTotals(showColumnGrandTotals: boolean): void;

Parameters
showColumnGrandTotals boolean
Returns
void

setShowRowGrandTotals(showRowGrandTotals)
Specifies if the PivotTable report shows grand totals for rows.

TypeScript

setShowRowGrandTotals(showRowGrandTotals: boolean): void;

Parameters
showRowGrandTotals boolean

Returns
void

setSubtotalLocation(subtotalLocation)
This property indicates the SubtotalLocationType of all fields on the PivotTable. If
fields have different states, this will be null .

TypeScript

setSubtotalLocation(subtotalLocation: SubtotalLocationType): void;

Parameters
subtotalLocation ExcelScript.SubtotalLocationType

Returns
void

Examples

TypeScript
/**
* This script displays group subtotals of the "Farms Sales" PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Sales".
const pivot = workbook.getPivotTable("Farm Sales");

// Get the PivotLayout object.


const layout = pivot.getLayout();

// Show all the subtotals at the bottom of each group.


layout.setSubtotalLocation(ExcelScript.SubtotalLocationType.atBottom);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotManualFilter interface
Reference
Package: ExcelScript

Configurable template for a manual filter to apply to a PivotField. The condition defines
what criteria need to be set in order for the filter to operate.

Remarks

Examples

TypeScript

/**
* This script adds a manual filter to a PivotTable.
*/
function main(workbook: ExcelScript.Workbook)
{
// Get the first PivotTable in the workbook.
const pivot = workbook.getPivotTables()[0];

// Get the hierarchy to use as the filter.


const location = pivot.getHierarchy("Location");

// Use "Location" as the FilterHierarchy.


pivot.addFilterHierarchy(location);

// Select items for the filter.


const cityFilter: ExcelScript.PivotManualFilter = {
selectedItems: ["Seattle", "Chicago"]
};

// Apply the filter


// Note that hierarchies and fields have a 1:1 relationship in Excel, so
`getFields()[0]` always gets the correct field.
location.getFields()[0].applyFilter({
manualFilter: cityFilter
});
}

Properties
ノ Expand table
selected A list of selected items to manually filter. These must be existing and valid items
Items from the chosen field.

Property Details

selectedItems
A list of selected items to manually filter. These must be existing and valid items
from the chosen field.

TypeScript

selectedItems?: (string | PivotItem)[];

Property Value
(string | ExcelScript.PivotItem)[]

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotTable interface
Reference
Package: ExcelScript

Represents an Excel PivotTable.

Remarks

Examples

TypeScript

/**
* This script creates a PivotTable from an existing table and adds it to a
new worksheet.
* This script assumes there is a table in the current worksheet with
columns named "Type" and "Sales".
*/
function main(workbook: ExcelScript.Workbook) {
// Create a PivotTable based on a table in the current worksheet.
let sheet = workbook.getActiveWorksheet();
let table = sheet.getTables()[0];

// Add the PivotTable to a new worksheet.


let newSheet = workbook.addWorksheet("Pivot");
let pivotTable = newSheet.addPivotTable("My Pivot", table, "A1");

// Add fields to the PivotTable to show "Sales" per "Type".


pivotTable.addRowHierarchy(pivotTable.getHierarchy("Type"));
pivotTable.addDataHierarchy(pivotTable.getHierarchy("Sales"));
}

Methods
ノ Expand table

addColumnHierarchy(pivot Adds the PivotHierarchy to the current axis. If the hierarchy is


Hierarchy) present elsewhere on the row, column, or filter axis, it will be
removed from that location.

addDataHierarchy(pivot Adds the PivotHierarchy to the current axis.


Hierarchy)
addFilterHierarchy(pivot Adds the PivotHierarchy to the current axis. If the hierarchy is
Hierarchy) present elsewhere on the row, column, or filter axis, it will be
removed from that location.

addRowHierarchy(pivot Adds the PivotHierarchy to the current axis. If the hierarchy is


Hierarchy) present elsewhere on the row, column, or filter axis, it will be
removed from that location.

delete() Deletes the PivotTable.

getAllowMultipleFiltersPer Specifies if the PivotTable allows the application of multiple


Field() PivotFilters on a given PivotField in the table.

getColumnHierarchies() The Column Pivot Hierarchies of the PivotTable.

getColumnHierarchy(name) Gets a RowColumnPivotHierarchy by name. If the


RowColumnPivotHierarchy does not exist, then this method
returns undefined .

getDataHierarchies() The Data Pivot Hierarchies of the PivotTable.

getDataHierarchy(name) Gets a DataPivotHierarchy by name. If the DataPivotHierarchy


does not exist, then this method returns undefined .

getEnableDataValueEditing() Specifies if the PivotTable allows values in the data body to be


edited by the user.

getFilterHierarchies() The Filter Pivot Hierarchies of the PivotTable.

getFilterHierarchy(name) Gets a FilterPivotHierarchy by name. If the FilterPivotHierarchy


does not exist, then this method returns undefined .

getHierarchies() The Pivot Hierarchies of the PivotTable.

getHierarchy(name) Gets a PivotHierarchy by name. If the PivotHierarchy does not


exist, then this method returns undefined .

getId() ID of the PivotTable.

getLayout() The PivotLayout describing the layout and visual structure of the
PivotTable.

getName() Name of the PivotTable.

getRowHierarchies() The Row Pivot Hierarchies of the PivotTable.

getRowHierarchy(name) Gets a RowColumnPivotHierarchy by name. If the


RowColumnPivotHierarchy does not exist, then this method
returns undefined .

getUseCustomSortLists() Specifies if the PivotTable uses custom lists when sorting.


getWorksheet() The worksheet containing the current PivotTable.

refresh() Refreshes the PivotTable.

removeColumnHierarchy(row Removes the PivotHierarchy from the current axis.


ColumnPivotHierarchy)

removeDataHierarchy(Data Removes the PivotHierarchy from the current axis.


PivotHierarchy)

removeFilterHierarchy(filter Removes the PivotHierarchy from the current axis.


PivotHierarchy)

removeRowHierarchy(row Removes the PivotHierarchy from the current axis.


ColumnPivotHierarchy)

setAllowMultipleFiltersPer Specifies if the PivotTable allows the application of multiple


Field(allowMultipleFiltersPer PivotFilters on a given PivotField in the table.
Field)

setEnableDataValue Specifies if the PivotTable allows values in the data body to be


Editing(enableDataValue edited by the user.
Editing)

setName(name) Name of the PivotTable.

setUseCustomSortLists(use Specifies if the PivotTable uses custom lists when sorting.


CustomSortLists)

Method Details

addColumnHierarchy(pivotHierarchy)
Adds the PivotHierarchy to the current axis. If the hierarchy is present elsewhere on
the row, column, or filter axis, it will be removed from that location.

TypeScript

addColumnHierarchy(
pivotHierarchy: PivotHierarchy
): RowColumnPivotHierarchy;

Parameters
pivotHierarchy ExcelScript.PivotHierarchy
Returns
ExcelScript.RowColumnPivotHierarchy

Examples

TypeScript

/**
* This script adds a row hierarchy to the PivotTable on the current
worksheet.
* This assumes the source data has columns named
* "Type", "Classification", and "Sales".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable on the current worksheet.
let sheet = workbook.getActiveWorksheet();
let pivotTable = sheet.getPivotTables()[0];

// Add the field "Type" to the PivotTable as a row hierarchy.


pivotTable.addRowHierarchy(pivotTable.getHierarchy("Type"));

// Add the field "Classification" to the PivotTable as a column


hierarchy.

pivotTable.addColumnHierarchy(pivotTable.getHierarchy("Classification"));

// Add the field "Sales" to the PivotTable as a data hierarchy.


// By default, this displays the sums of the values in "Sales" based on
the "Type".
pivotTable.addDataHierarchy(pivotTable.getHierarchy("Sales"));
}

addDataHierarchy(pivotHierarchy)
Adds the PivotHierarchy to the current axis.

TypeScript

addDataHierarchy(pivotHierarchy: PivotHierarchy): DataPivotHierarchy;

Parameters
pivotHierarchy ExcelScript.PivotHierarchy

Returns
ExcelScript.DataPivotHierarchy

Examples

TypeScript

/**
* This script creates a PivotTable from an existing table and adds it to
a new worksheet.
* This script assumes there is a table in the current worksheet with
columns named "Type" and "Sales".
*/
function main(workbook: ExcelScript.Workbook) {
// Create a PivotTable based on a table in the current worksheet.
let sheet = workbook.getActiveWorksheet();
let table = sheet.getTables()[0];

// Add the PivotTable to a new worksheet.


let newSheet = workbook.addWorksheet("Pivot");
let pivotTable = newSheet.addPivotTable("My Pivot", table, "A1");

// Add fields to the PivotTable to show "Sales" per "Type".


pivotTable.addRowHierarchy(pivotTable.getHierarchy("Type"));
pivotTable.addDataHierarchy(pivotTable.getHierarchy("Sales"));
}

addFilterHierarchy(pivotHierarchy)
Adds the PivotHierarchy to the current axis. If the hierarchy is present elsewhere on
the row, column, or filter axis, it will be removed from that location.

TypeScript

addFilterHierarchy(
pivotHierarchy: PivotHierarchy
): FilterPivotHierarchy;

Parameters
pivotHierarchy ExcelScript.PivotHierarchy

Returns
ExcelScript.FilterPivotHierarchy
Examples

TypeScript

/**
* This script adds a manual filter to a PivotTable.
*/
function main(workbook: ExcelScript.Workbook)
{
// Get the first PivotTable in the workbook.
const pivot = workbook.getPivotTables()[0];

// Get the hierarchy to use as the filter.


const location = pivot.getHierarchy("Location");

// Use "Location" as the FilterHierarchy.


pivot.addFilterHierarchy(location);

// Select items for the filter.


// Note that hierarchies and fields have a 1:1 relationship in Excel,
// so `getFields()[0]` always gets the correct field.
location.getFields()[0].applyFilter({
manualFilter: {
selectedItems: ["Seattle", "Chicago"]
}
});
}

addRowHierarchy(pivotHierarchy)
Adds the PivotHierarchy to the current axis. If the hierarchy is present elsewhere on
the row, column, or filter axis, it will be removed from that location.

TypeScript

addRowHierarchy(
pivotHierarchy: PivotHierarchy
): RowColumnPivotHierarchy;

Parameters
pivotHierarchy ExcelScript.PivotHierarchy

Returns
ExcelScript.RowColumnPivotHierarchy
Examples

TypeScript

/**
* This script creates a PivotTable from an existing table and adds it to
a new worksheet.
* This script assumes there is a table in the current worksheet with
columns named "Type" and "Sales".
*/
function main(workbook: ExcelScript.Workbook) {
// Create a PivotTable based on a table in the current worksheet.
let sheet = workbook.getActiveWorksheet();
let table = sheet.getTables()[0];

// Add the PivotTable to a new worksheet.


let newSheet = workbook.addWorksheet("Pivot");
let pivotTable = newSheet.addPivotTable("My Pivot", table, "A1");

// Add fields to the PivotTable to show "Sales" per "Type".


pivotTable.addRowHierarchy(pivotTable.getHierarchy("Type"));
pivotTable.addDataHierarchy(pivotTable.getHierarchy("Sales"));
}

delete()
Deletes the PivotTable.

TypeScript

delete(): void;

Returns
void

getAllowMultipleFiltersPerField()
Specifies if the PivotTable allows the application of multiple PivotFilters on a given
PivotField in the table.

TypeScript

getAllowMultipleFiltersPerField(): boolean;
Returns
boolean

getColumnHierarchies()
The Column Pivot Hierarchies of the PivotTable.

TypeScript

getColumnHierarchies(): RowColumnPivotHierarchy[];

Returns
ExcelScript.RowColumnPivotHierarchy[]

getColumnHierarchy(name)
Gets a RowColumnPivotHierarchy by name. If the RowColumnPivotHierarchy does
not exist, then this method returns undefined .

TypeScript

getColumnHierarchy(name: string): RowColumnPivotHierarchy | undefined;

Parameters
name string
Name of the RowColumnPivotHierarchy to be retrieved.

Returns
ExcelScript.RowColumnPivotHierarchy | undefined

getDataHierarchies()
The Data Pivot Hierarchies of the PivotTable.

TypeScript

getDataHierarchies(): DataPivotHierarchy[];
Returns
ExcelScript.DataPivotHierarchy[]

getDataHierarchy(name)
Gets a DataPivotHierarchy by name. If the DataPivotHierarchy does not exist, then
this method returns undefined .

TypeScript

getDataHierarchy(name: string): DataPivotHierarchy | undefined;

Parameters
name string
Name of the DataPivotHierarchy to be retrieved.

Returns
ExcelScript.DataPivotHierarchy | undefined

getEnableDataValueEditing()
Specifies if the PivotTable allows values in the data body to be edited by the user.

TypeScript

getEnableDataValueEditing(): boolean;

Returns
boolean

getFilterHierarchies()
The Filter Pivot Hierarchies of the PivotTable.

TypeScript

getFilterHierarchies(): FilterPivotHierarchy[];
Returns
ExcelScript.FilterPivotHierarchy[]

getFilterHierarchy(name)
Gets a FilterPivotHierarchy by name. If the FilterPivotHierarchy does not exist, then
this method returns undefined .

TypeScript

getFilterHierarchy(name: string): FilterPivotHierarchy | undefined;

Parameters
name string
Name of the FilterPivotHierarchy to be retrieved.

Returns
ExcelScript.FilterPivotHierarchy | undefined

getHierarchies()
The Pivot Hierarchies of the PivotTable.

TypeScript

getHierarchies(): PivotHierarchy[];

Returns
ExcelScript.PivotHierarchy[]

getHierarchy(name)
Gets a PivotHierarchy by name. If the PivotHierarchy does not exist, then this method
returns undefined .

TypeScript
getHierarchy(name: string): PivotHierarchy | undefined;

Parameters
name string
Name of the PivotHierarchy to be retrieved.

Returns
ExcelScript.PivotHierarchy | undefined

getId()
ID of the PivotTable.

TypeScript

getId(): string;

Returns
string

getLayout()
The PivotLayout describing the layout and visual structure of the PivotTable.

TypeScript

getLayout(): PivotLayout;

Returns
ExcelScript.PivotLayout

Examples

TypeScript

/**
* This script sets the layout of the "Farms Sales" PivotTable to the
"tabular"
* setting. This places the fields from the Rows area in separate
columns.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Sales".
const pivot = workbook.getPivotTable("Farm Sales");

// Get the PivotLayout object.


const layout = pivot.getLayout();

// Set the layout type to "tabular".


layout.setLayoutType(ExcelScript.PivotLayoutType.tabular);
}

getName()
Name of the PivotTable.

TypeScript

getName(): string;

Returns
string

getRowHierarchies()
The Row Pivot Hierarchies of the PivotTable.

TypeScript

getRowHierarchies(): RowColumnPivotHierarchy[];

Returns
ExcelScript.RowColumnPivotHierarchy[]

getRowHierarchy(name)
Gets a RowColumnPivotHierarchy by name. If the RowColumnPivotHierarchy does
not exist, then this method returns undefined .
TypeScript

getRowHierarchy(name: string): RowColumnPivotHierarchy | undefined;

Parameters
name string
Name of the RowColumnPivotHierarchy to be retrieved.

Returns
ExcelScript.RowColumnPivotHierarchy | undefined

Examples

TypeScript

/**
* This sample sorts the rows of a PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get an existing PivotTable.
const pivotTable = workbook.getPivotTable("Farm Sales");

// Get the data hierarchy to use as the basis of the sort.


const valueFieldToSortOn = pivotTable.getDataHierarchy("Sum of Crates
Sold Wholesale");

// Get the row to sort.


const rowToSort = pivotTable.getRowHierarchy("Farm");

// Sort the "Farm" row's only field by the values in "Sum of Crates
Sold Wholesale".
rowToSort.getFields()[0].sortByValues(ExcelScript.SortBy.descending,
valueFieldToSortOn);
}

getUseCustomSortLists()
Specifies if the PivotTable uses custom lists when sorting.

TypeScript

getUseCustomSortLists(): boolean;
Returns
boolean

getWorksheet()
The worksheet containing the current PivotTable.

TypeScript

getWorksheet(): Worksheet;

Returns
ExcelScript.Worksheet

refresh()
Refreshes the PivotTable.

TypeScript

refresh(): void;

Returns
void

removeColumnHierarchy(rowColumnPivotHierarchy)
Removes the PivotHierarchy from the current axis.

TypeScript

removeColumnHierarchy(
rowColumnPivotHierarchy: RowColumnPivotHierarchy
): void;

Parameters
rowColumnPivotHierarchy ExcelScript.RowColumnPivotHierarchy
Returns
void

removeDataHierarchy(DataPivotHierarchy)
Removes the PivotHierarchy from the current axis.

TypeScript

removeDataHierarchy(DataPivotHierarchy: DataPivotHierarchy): void;

Parameters
DataPivotHierarchy ExcelScript.DataPivotHierarchy

Returns
void

removeFilterHierarchy(filterPivotHierarchy)
Removes the PivotHierarchy from the current axis.

TypeScript

removeFilterHierarchy(filterPivotHierarchy: FilterPivotHierarchy): void;

Parameters
filterPivotHierarchy ExcelScript.FilterPivotHierarchy

Returns
void

removeRowHierarchy(rowColumnPivotHierarchy)
Removes the PivotHierarchy from the current axis.

TypeScript
removeRowHierarchy(
rowColumnPivotHierarchy: RowColumnPivotHierarchy
): void;

Parameters
rowColumnPivotHierarchy ExcelScript.RowColumnPivotHierarchy

Returns
void

setAllowMultipleFiltersPerField(allowMultipleFiltersPer
Field)
Specifies if the PivotTable allows the application of multiple PivotFilters on a given
PivotField in the table.

TypeScript

setAllowMultipleFiltersPerField(
allowMultipleFiltersPerField: boolean
): void;

Parameters
allowMultipleFiltersPerField boolean

Returns
void

setEnableDataValueEditing(enableDataValueEditing)
Specifies if the PivotTable allows values in the data body to be edited by the user.

TypeScript

setEnableDataValueEditing(enableDataValueEditing: boolean): void;

Parameters
enableDataValueEditing boolean

Returns
void

setName(name)
Name of the PivotTable.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

setUseCustomSortLists(useCustomSortLists)
Specifies if the PivotTable uses custom lists when sorting.

TypeScript

setUseCustomSortLists(useCustomSortLists: boolean): void;

Parameters
useCustomSortLists boolean

Returns
void

6 Collaborate with us on
Office Scripts feedback
GitHub Office Scripts is an open source project.
Select a link to provide feedback:
The source for this content can
be found on GitHub, where you  Open a documentation issue
can also create and review
issues and pull requests. For  Provide product feedback
more information, see our
contributor guide.
ExcelScript.PivotTableStyle interface
Reference
Package: ExcelScript

Represents a PivotTable style, which defines style elements by PivotTable region.

Methods
ノ Expand table

delete() Deletes the PivotTable style.

duplicate() Creates a duplicate of this PivotTable style with copies of all the style elements.

getName() Specifies the name of the PivotTable style.

getReadOnly() Specifies if this PivotTableStyle object is read-only.

setName(name) Specifies the name of the PivotTable style.

Method Details

delete()
Deletes the PivotTable style.

TypeScript

delete(): void;

Returns
void

duplicate()
Creates a duplicate of this PivotTable style with copies of all the style elements.

TypeScript
duplicate(): PivotTableStyle;

Returns
ExcelScript.PivotTableStyle

getName()
Specifies the name of the PivotTable style.

TypeScript

getName(): string;

Returns
string

getReadOnly()
Specifies if this PivotTableStyle object is read-only.

TypeScript

getReadOnly(): boolean;

Returns
boolean

setName(name)
Specifies the name of the PivotTable style.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PivotValueFilter interface
Reference
Package: ExcelScript

Configurable template for a value filter to apply to a PivotField. The condition defines
what criteria need to be set in order for the filter to operate.

Remarks

Examples

TypeScript

/**
* This script applies a PivotValueFilter to the first row hierarchy in the
PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable on the current worksheet.
let sheet = workbook.getActiveWorksheet();
let pivotTable = sheet.getPivotTables()[0];

// Get the first row hierarchy to use as the field which gets filtered.
let rowHierarchy = pivotTable.getRowHierarchies()[0];

// Get the first data hierarchy to use as the values for filtering the
rows.
let dataHierarchy = pivotTable.getDataHierarchies()[0];

// Create a filter that excludes values greater than 500.


let filter: ExcelScript.PivotValueFilter = {
condition: ExcelScript.ValueFilterCondition.greaterThan,
comparator: 500,
value: dataHierarchy.getName()
};

// Apply the filter.


rowHierarchy.getPivotField(rowHierarchy.getName()).applyFilter({
valueFilter: filter
});
}

Properties
ノ Expand table

comparator The comparator is the static value to which other values are compared. The type of
comparison is defined by the condition. For example, if comparator is "50" and
condition is "greaterThan", all item values that are not greater than 50 will be
removed by the filter.

condition Specifies the condition for the filter, which defines the necessary filtering criteria.

exclusive If true , filter excludes items that meet criteria. The default is false (filter to include
items that meet criteria).

lowerBound The lower-bound of the range for the between filter condition.

selection Specifies if the filter is for the top/bottom N items, top/bottom N percent, or
Type top/bottom N sum.

threshold The "N" threshold number of items, percent, or sum to be filtered for a top/bottom
filter condition.

upper The upper-bound of the range for the between filter condition.
Bound

value Name of the chosen "value" in the field by which to filter.

Property Details

comparator
The comparator is the static value to which other values are compared. The type of
comparison is defined by the condition. For example, if comparator is "50" and
condition is "greaterThan", all item values that are not greater than 50 will be
removed by the filter.

TypeScript

comparator?: number;

Property Value
number

condition
Specifies the condition for the filter, which defines the necessary filtering criteria.
TypeScript

condition: ValueFilterCondition;

Property Value
ExcelScript.ValueFilterCondition

exclusive
If true , filter excludes items that meet criteria. The default is false (filter to include
items that meet criteria).

TypeScript

exclusive?: boolean;

Property Value
boolean

lowerBound
The lower-bound of the range for the between filter condition.

TypeScript

lowerBound?: number;

Property Value
number

selectionType
Specifies if the filter is for the top/bottom N items, top/bottom N percent, or
top/bottom N sum.

TypeScript

selectionType?: TopBottomSelectionType;
Property Value
ExcelScript.TopBottomSelectionType

threshold
The "N" threshold number of items, percent, or sum to be filtered for a top/bottom
filter condition.

TypeScript

threshold?: number;

Property Value
number

upperBound
The upper-bound of the range for the between filter condition.

TypeScript

upperBound?: number;

Property Value
number

value
Name of the chosen "value" in the field by which to filter.

TypeScript

value: string;

Property Value
string
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PredefinedCellStyle interface
Reference
Package: ExcelScript

An object encapsulating a style's format and other properties.

Methods
ノ Expand table

delete() Deletes this style.

getAutoIndent() Specifies if text is automatically indented when the text alignment in


a cell is set to equal distribution.

getBorders() A collection of four border objects that represent the style of the
four borders.

getBuiltIn() Specifies if the style is a built-in style.

getFill() The fill of the style.

getFont() A Font object that represents the font of the style.

getFormulaHidden() Specifies if the formula will be hidden when the worksheet is


protected.

getHorizontalAlignment() Represents the horizontal alignment for the style. See


ExcelScript.HorizontalAlignment for details.

getIncludeAlignment() Specifies if the style includes the auto indent, horizontal alignment,
vertical alignment, wrap text, indent level, and text orientation
properties.

getIncludeBorder() Specifies if the style includes the color, color index, line style, and
weight border properties.

getIncludeFont() Specifies if the style includes the background, bold, color, color
index, font style, italic, name, size, strikethrough, subscript,
superscript, and underline font properties.

getIncludeNumber() Specifies if the style includes the number format property.

getIncludePatterns() Specifies if the style includes the color, color index, invert if negative,
pattern, pattern color, and pattern color index interior properties.
getIncludeProtection() Specifies if the style includes the formula hidden and locked
protection properties.

getIndentLevel() An integer from 0 to 250 that indicates the indent level for the style.

getLocked() Specifies if the object is locked when the worksheet is protected.

getName() The name of the style.

getNumberFormat() The format code of the number format for the style.

getNumberFormatLocal() The localized format code of the number format for the style.

getRangeBorder(index) Gets a border object using its name.

getRangeBorderTintAnd Specifies a double that lightens or darkens a color for range


Shade() borders. The value is between -1 (darkest) and 1 (brightest), with 0
for the original color. A null value indicates that the entire border
collection doesn't have a uniform tintAndShade setting.

getReadingOrder() The reading order for the style.

getShrinkToFit() Specifies if text automatically shrinks to fit in the available column


width.

getTextOrientation() The text orientation for the style.

getVerticalAlignment() Specifies the vertical alignment for the style. See


ExcelScript.VerticalAlignment for details.

getWrapText() Specifies if Excel wraps the text in the object.

setAutoIndent(autoIndent) Specifies if text is automatically indented when the text alignment in


a cell is set to equal distribution.

setFormulaHidden(formula Specifies if the formula will be hidden when the worksheet is


Hidden) protected.

setHorizontal Represents the horizontal alignment for the style. See


Alignment(horizontal ExcelScript.HorizontalAlignment for details.
Alignment)

setInclude Specifies if the style includes the auto indent, horizontal alignment,
Alignment(include vertical alignment, wrap text, indent level, and text orientation
Alignment) properties.

setIncludeBorder(include Specifies if the style includes the color, color index, line style, and
Border) weight border properties.

setIncludeFont(include Specifies if the style includes the background, bold, color, color
Font) index, font style, italic, name, size, strikethrough, subscript,
superscript, and underline font properties.
setIncludeNumber(include Specifies if the style includes the number format property.
Number)

setIncludePatterns(include Specifies if the style includes the color, color index, invert if negative,
Patterns) pattern, pattern color, and pattern color index interior properties.

setInclude Specifies if the style includes the formula hidden and locked
Protection(include protection properties.
Protection)

setIndentLevel(indent An integer from 0 to 250 that indicates the indent level for the style.
Level)

setLocked(locked) Specifies if the object is locked when the worksheet is protected.

setNumberFormat(number The format code of the number format for the style.
Format)

setNumberFormat The localized format code of the number format for the style.
Local(numberFormatLocal)

setRangeBorderTintAnd Specifies a double that lightens or darkens a color for range


Shade(rangeBorderTint borders. The value is between -1 (darkest) and 1 (brightest), with 0
AndShade) for the original color. A null value indicates that the entire border
collection doesn't have a uniform tintAndShade setting.

setReadingOrder(reading The reading order for the style.


Order)

setShrinkToFit(shrinkToFit) Specifies if text automatically shrinks to fit in the available column


width.

setTextOrientation(text The text orientation for the style.


Orientation)

setVertical Specifies the vertical alignment for the style. See


Alignment(vertical ExcelScript.VerticalAlignment for details.
Alignment)

setWrapText(wrapText) Specifies if Excel wraps the text in the object.

Method Details

delete()
Deletes this style.

TypeScript
delete(): void;

Returns
void

getAutoIndent()
Specifies if text is automatically indented when the text alignment in a cell is set to
equal distribution.

TypeScript

getAutoIndent(): boolean;

Returns
boolean

getBorders()
A collection of four border objects that represent the style of the four borders.

TypeScript

getBorders(): RangeBorder[];

Returns
ExcelScript.RangeBorder[]

getBuiltIn()
Specifies if the style is a built-in style.

TypeScript

getBuiltIn(): boolean;
Returns
boolean

getFill()
The fill of the style.

TypeScript

getFill(): RangeFill;

Returns
ExcelScript.RangeFill

getFont()
A Font object that represents the font of the style.

TypeScript

getFont(): RangeFont;

Returns
ExcelScript.RangeFont

getFormulaHidden()
Specifies if the formula will be hidden when the worksheet is protected.

TypeScript

getFormulaHidden(): boolean;

Returns
boolean

getHorizontalAlignment()
Represents the horizontal alignment for the style. See
ExcelScript.HorizontalAlignment for details.

TypeScript

getHorizontalAlignment(): HorizontalAlignment;

Returns
ExcelScript.HorizontalAlignment

getIncludeAlignment()
Specifies if the style includes the auto indent, horizontal alignment, vertical
alignment, wrap text, indent level, and text orientation properties.

TypeScript

getIncludeAlignment(): boolean;

Returns
boolean

getIncludeBorder()
Specifies if the style includes the color, color index, line style, and weight border
properties.

TypeScript

getIncludeBorder(): boolean;

Returns
boolean

getIncludeFont()
Specifies if the style includes the background, bold, color, color index, font style,
italic, name, size, strikethrough, subscript, superscript, and underline font properties.
TypeScript

getIncludeFont(): boolean;

Returns
boolean

getIncludeNumber()
Specifies if the style includes the number format property.

TypeScript

getIncludeNumber(): boolean;

Returns
boolean

getIncludePatterns()
Specifies if the style includes the color, color index, invert if negative, pattern, pattern
color, and pattern color index interior properties.

TypeScript

getIncludePatterns(): boolean;

Returns
boolean

getIncludeProtection()
Specifies if the style includes the formula hidden and locked protection properties.

TypeScript

getIncludeProtection(): boolean;
Returns
boolean

getIndentLevel()
An integer from 0 to 250 that indicates the indent level for the style.

TypeScript

getIndentLevel(): number;

Returns
number

getLocked()
Specifies if the object is locked when the worksheet is protected.

TypeScript

getLocked(): boolean;

Returns
boolean

getName()
The name of the style.

TypeScript

getName(): string;

Returns
string

getNumberFormat()
The format code of the number format for the style.

TypeScript

getNumberFormat(): string;

Returns
string

getNumberFormatLocal()
The localized format code of the number format for the style.

TypeScript

getNumberFormatLocal(): string;

Returns
string

getRangeBorder(index)
Gets a border object using its name.

TypeScript

getRangeBorder(index: BorderIndex): RangeBorder;

Parameters
index ExcelScript.BorderIndex
Index value of the border object to be retrieved. See ExcelScript.BorderIndex for
details.

Returns
ExcelScript.RangeBorder

getRangeBorderTintAndShade()
Specifies a double that lightens or darkens a color for range borders. The value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the entire border collection doesn't have a uniform tintAndShade
setting.

TypeScript

getRangeBorderTintAndShade(): number;

Returns
number

getReadingOrder()
The reading order for the style.

TypeScript

getReadingOrder(): ReadingOrder;

Returns
ExcelScript.ReadingOrder

getShrinkToFit()
Specifies if text automatically shrinks to fit in the available column width.

TypeScript

getShrinkToFit(): boolean;

Returns
boolean

getTextOrientation()
The text orientation for the style.
TypeScript

getTextOrientation(): number;

Returns
number

getVerticalAlignment()
Specifies the vertical alignment for the style. See ExcelScript.VerticalAlignment for
details.

TypeScript

getVerticalAlignment(): VerticalAlignment;

Returns
ExcelScript.VerticalAlignment

getWrapText()
Specifies if Excel wraps the text in the object.

TypeScript

getWrapText(): boolean;

Returns
boolean

setAutoIndent(autoIndent)
Specifies if text is automatically indented when the text alignment in a cell is set to
equal distribution.

TypeScript

setAutoIndent(autoIndent: boolean): void;


Parameters
autoIndent boolean

Returns
void

setFormulaHidden(formulaHidden)
Specifies if the formula will be hidden when the worksheet is protected.

TypeScript

setFormulaHidden(formulaHidden: boolean): void;

Parameters
formulaHidden boolean

Returns
void

setHorizontalAlignment(horizontalAlignment)
Represents the horizontal alignment for the style. See
ExcelScript.HorizontalAlignment for details.

TypeScript

setHorizontalAlignment(horizontalAlignment: HorizontalAlignment): void;

Parameters
horizontalAlignment ExcelScript.HorizontalAlignment

Returns
void

setIncludeAlignment(includeAlignment)
Specifies if the style includes the auto indent, horizontal alignment, vertical
alignment, wrap text, indent level, and text orientation properties.

TypeScript

setIncludeAlignment(includeAlignment: boolean): void;

Parameters
includeAlignment boolean

Returns
void

setIncludeBorder(includeBorder)
Specifies if the style includes the color, color index, line style, and weight border
properties.

TypeScript

setIncludeBorder(includeBorder: boolean): void;

Parameters
includeBorder boolean

Returns
void

setIncludeFont(includeFont)
Specifies if the style includes the background, bold, color, color index, font style,
italic, name, size, strikethrough, subscript, superscript, and underline font properties.

TypeScript

setIncludeFont(includeFont: boolean): void;


Parameters
includeFont boolean

Returns
void

setIncludeNumber(includeNumber)
Specifies if the style includes the number format property.

TypeScript

setIncludeNumber(includeNumber: boolean): void;

Parameters
includeNumber boolean

Returns
void

setIncludePatterns(includePatterns)
Specifies if the style includes the color, color index, invert if negative, pattern, pattern
color, and pattern color index interior properties.

TypeScript

setIncludePatterns(includePatterns: boolean): void;

Parameters
includePatterns boolean

Returns
void

setIncludeProtection(includeProtection)
Specifies if the style includes the formula hidden and locked protection properties.

TypeScript

setIncludeProtection(includeProtection: boolean): void;

Parameters
includeProtection boolean

Returns
void

setIndentLevel(indentLevel)
An integer from 0 to 250 that indicates the indent level for the style.

TypeScript

setIndentLevel(indentLevel: number): void;

Parameters
indentLevel number

Returns
void

setLocked(locked)
Specifies if the object is locked when the worksheet is protected.

TypeScript

setLocked(locked: boolean): void;

Parameters
locked boolean
Returns
void

setNumberFormat(numberFormat)
The format code of the number format for the style.

TypeScript

setNumberFormat(numberFormat: string): void;

Parameters
numberFormat string

Returns
void

setNumberFormatLocal(numberFormatLocal)
The localized format code of the number format for the style.

TypeScript

setNumberFormatLocal(numberFormatLocal: string): void;

Parameters
numberFormatLocal string

Returns
void

setRangeBorderTintAndShade(rangeBorderTintAnd
Shade)
Specifies a double that lightens or darkens a color for range borders. The value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the entire border collection doesn't have a uniform tintAndShade
setting.

TypeScript

setRangeBorderTintAndShade(rangeBorderTintAndShade: number): void;

Parameters
rangeBorderTintAndShade number

Returns
void

setReadingOrder(readingOrder)
The reading order for the style.

TypeScript

setReadingOrder(readingOrder: ReadingOrder): void;

Parameters
readingOrder ExcelScript.ReadingOrder

Returns
void

setShrinkToFit(shrinkToFit)
Specifies if text automatically shrinks to fit in the available column width.

TypeScript

setShrinkToFit(shrinkToFit: boolean): void;

Parameters
shrinkToFit boolean
Returns
void

setTextOrientation(textOrientation)
The text orientation for the style.

TypeScript

setTextOrientation(textOrientation: number): void;

Parameters
textOrientation number

Returns
void

setVerticalAlignment(verticalAlignment)
Specifies the vertical alignment for the style. See ExcelScript.VerticalAlignment for
details.

TypeScript

setVerticalAlignment(verticalAlignment: VerticalAlignment): void;

Parameters
verticalAlignment ExcelScript.VerticalAlignment

Returns
void

setWrapText(wrapText)
Specifies if Excel wraps the text in the object.

TypeScript
setWrapText(wrapText: boolean): void;

Parameters
wrapText boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.PresetCriteriaConditional
Format interface
Reference
Package: ExcelScript

Represents the preset criteria conditional format such as above average, below average,
unique values, contains blank, nonblank, error, and noerror.

Remarks

Examples

TypeScript

/**
* This script applies a conditional format that uses a preset criterion.
* Any cell in row 1 will have the color fill set to green if it is a
duplicate value
* (of anything else in row 1).
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range for row 1.
const sheet = workbook.getActiveWorksheet();
const formattedRange = sheet.getRange("1:1");

// Add new conditional formatting to that range.


const conditionalFormat = formattedRange.addConditionalFormat(
ExcelScript.ConditionalFormatType.presetCriteria);

// Set the conditional formatting to apply a green fill.


const presetFormat: ExcelScript.PresetCriteriaConditionalFormat =
conditionalFormat.getPreset();
presetFormat.getFormat().getFill().setColor("green");

// Set a rule to apply the conditional format when values are duplicated
in the range.
const duplicateRule: ExcelScript.ConditionalPresetCriteriaRule = {
criterion: ExcelScript.ConditionalFormatPresetCriterion.duplicateValues
};
presetFormat.setRule(duplicateRule);
}

Methods
ノ Expand table

getFormat() Returns a format object, encapsulating the conditional formats font, fill, borders,
and other properties.

getRule() The rule of the conditional format.

set The rule of the conditional format.


Rule(rule)

Method Details

getFormat()
Returns a format object, encapsulating the conditional formats font, fill, borders, and
other properties.

TypeScript

getFormat(): ConditionalRangeFormat;

Returns
ExcelScript.ConditionalRangeFormat

getRule()
The rule of the conditional format.

TypeScript

getRule(): ConditionalPresetCriteriaRule;

Returns
ExcelScript.ConditionalPresetCriteriaRule

setRule(rule)
The rule of the conditional format.

TypeScript
setRule(rule: ConditionalPresetCriteriaRule): void;

Parameters
rule ExcelScript.ConditionalPresetCriteriaRule

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Query interface
Reference
Package: ExcelScript

Represents a Power Query query.

Remarks

Examples

TypeScript

/**
* This script logs information about all the Power Query queries in the
workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get all the Power Query queries in the workbook.
const queries = workbook.getQueries();

// For each query, log the date it was last refreshed.


queries.forEach((query: ExcelScript.Query) => {
console.log(`Query ${query.getName()} - last refreshed
${query.getRefreshDate()}`);
});
}

Methods
ノ Expand table

getError() Gets the query error message from when the query was last refreshed.

getLoadedTo() Gets the query loaded to object type.

getLoadedToData Specifies if the query loaded to the data model.


Model()

getName() Gets the name of the query. Query names cannot contain periods or
quotation marks.

getRefreshDate() Gets the date and time when the query was last refreshed.
getRowsLoaded Gets the number of rows that were loaded when the query was last
Count() refreshed. If last refresh has errors the value will be -1.

Method Details

getError()
Gets the query error message from when the query was last refreshed.

TypeScript

getError(): QueryError;

Returns
ExcelScript.QueryError

getLoadedTo()
Gets the query loaded to object type.

TypeScript

getLoadedTo(): LoadToType;

Returns
ExcelScript.LoadToType

getLoadedToDataModel()
Specifies if the query loaded to the data model.

TypeScript

getLoadedToDataModel(): boolean;

Returns
boolean
getName()
Gets the name of the query. Query names cannot contain periods or quotation
marks.

TypeScript

getName(): string;

Returns
string

getRefreshDate()
Gets the date and time when the query was last refreshed.

TypeScript

getRefreshDate(): Date;

Returns
Date

getRowsLoadedCount()
Gets the number of rows that were loaded when the query was last refreshed. If last
refresh has errors the value will be -1.

TypeScript

getRowsLoadedCount(): number;

Returns
number
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Range interface
Reference
Package: ExcelScript

Range represents a set of one or more contiguous cells such as a cell, a row, a column,
or a block of cells.

Remarks

Examples

TypeScript

/**
* This script logs the address of the used range in the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current, active worksheet.
let currentWorksheet = workbook.getActiveWorksheet();

// Get the range containing all the cells with data or formatting.
let usedRange = currentWorksheet.getUsedRange();

// Log the range's address to the console.


console.log(usedRange.getAddress());
}

Methods
ノ Expand table

addConditionalFormat(type) Adds a new conditional format to the collection at the first/top


priority.

autoFill(destinationRange, auto Fills a range from the current range to the destination range
FillType) using the specified AutoFill logic. The destination range can be
null or can extend the source range either horizontally or
vertically. Discontiguous ranges are not supported.

calculate() Calculates a range of cells on a worksheet.

clear(applyTo) Clear range values, format, fill, border, etc.


clearAllConditionalFormats() Clears all conditional formats active on the current specified
range.

convertDataTypeToText() Converts the range cells with data types into text.

copyFrom(sourceRange, copy Copies cell data or formatting from the source range or
Type, skipBlanks, transpose) RangeAreas to the current range. The destination range can be
a different size than the source range or RangeAreas . The
destination is expanded automatically if it's smaller than the
source. Note: Like the copy functionality in the Excel UI, if the
destination range is an exact multiple greater than the source
range in either rows or columns, then the source content is
replicated multiple times. For example, a 2x2 range copy into a
2x6 range will result in 3 copies of the original 2x2 range.

delete(shift) Deletes the cells associated with the range.

find(text, criteria) Finds the given string based on the criteria specified. If the
current range is larger than a single cell, then the search will be
limited to that range, else the search will cover the entire sheet
starting after that cell. If there are no matches, then this
method returns undefined .

flashFill() Does a Flash Fill to the current range. Flash Fill automatically
fills data when it senses a pattern, so the range must be a
single column range and have data around it in order to find a
pattern.

getAbsoluteResizedRange(num Gets a Range object with the same top-left cell as the current
Rows, numColumns) Range object, but with the specified numbers of rows and
columns.

getAddress() Specifies the range reference in A1-style. Address value


contains the sheet reference (e.g., "Sheet1!A1:B4").

getAddressLocal() Represents the range reference for the specified range in the
language of the user.

getBoundingRect(another Gets the smallest range object that encompasses the given
Range) ranges. For example, the GetBoundingRect of "B2:C5" and
"D10:E15" is "B2:E15".

getCell(row, column) Gets the range object containing the single cell based on row
and column numbers. The cell can be outside the bounds of its
parent range, so long as it stays within the worksheet grid. The
returned cell is located relative to the top left cell of the range.

getCellCount() Specifies the number of cells in the range. This API will return
-1 if the cell count exceeds 2^31-1 (2,147,483,647).

getColumn(column) Gets a column contained in the range.


getColumnCount() Specifies the total number of columns in the range.

getColumnHidden() Represents if all columns in the current range are hidden. Value
is true when all columns in a range are hidden. Value is false
when no columns in the range are hidden. Value is null when
some columns in a range are hidden and other columns in the
same range are not hidden.

getColumnIndex() Specifies the column number of the first cell in the range. Zero-
indexed.

getColumnsAfter(count) Gets a certain number of columns to the right of the current


Range object.

getColumnsBefore(count) Gets a certain number of columns to the left of the current


Range object.

getConditionalFormat(id) Returns a conditional format identified by its ID. If the


conditional format object does not exist, then this method
returns undefined .

getConditionalFormats() The collection of ConditionalFormats that intersect the range.

getDataValidation() Returns a data validation object.

getDirectPrecedents() Returns a WorkbookRangeAreas object that represents the range


containing all the direct precedent cells of a specified range in
the same worksheet or across multiple worksheets.

getEntireColumn() Gets an object that represents the entire column of the range
(for example, if the current range represents cells "B4:E11", its
getEntireColumn is a range that represents columns "B:E").

getEntireRow() Gets an object that represents the entire row of the range (for
example, if the current range represents cells "B4:E11", its
GetEntireRow is a range that represents rows "4:11").

getExtendedRange(direction, Returns a range object that includes the current range and up
activeCell) to the edge of the range, based on the provided direction. This
matches the Ctrl+Shift+Arrow key behavior in the Excel on
Windows UI.

getFormat() Returns a format object, encapsulating the range's font, fill,


borders, alignment, and other properties.

getFormula() Represents the cell formula in A1-style notation. If the range


contains multiple cells, the data from first cell (represented by
row index of 0 and column index of 0) will be returned.

getFormulaLocal() Represents the cell formula in A1-style notation, in the user's


language and number-formatting locale. For example, the
English "=SUM(A1, 1.5)" formula would become "=SUMME(A1;
1,5)" in German. If the range contains multiple cells, the data
from first cell (represented by row index of 0 and column index
of 0) will be returned.

getFormulaR1C1() Represents the cell formula in R1C1-style notation. If the range


contains multiple cells, the data from first cell (represented by
row index of 0 and column index of 0) will be returned.

getFormulas() Represents the formula in A1-style notation. If a cell has no


formula, its value is returned instead.

getFormulasLocal() Represents the formula in A1-style notation, in the user's


language and number-formatting locale. For example, the
English "=SUM(A1, 1.5)" formula would become "=SUMME(A1;
1,5)" in German. If a cell has no formula, its value is returned
instead.

getFormulasR1C1() Represents the formula in R1C1-style notation. If a cell has no


formula, its value is returned instead.

getHasSpill() Represents if all cells have a spill border. Returns true if all
cells have a spill border, or false if all cells do not have a spill
border. Returns null if there are cells both with and without
spill borders within the range.

getHeight() Returns the distance in points, for 100% zoom, from the top
edge of the range to the bottom edge of the range.

getHidden() Represents if all cells in the current range are hidden. Value is
true when all cells in a range are hidden. Value is false when
no cells in the range are hidden. Value is null when some cells
in a range are hidden and other cells in the same range are not
hidden.

getHyperlink() Represents the hyperlink for the current range.

getImage() Renders the range as a base64-encoded png image.

getIntersection(anotherRange) Gets the range object that represents the rectangular


intersection of the given ranges. If no intersection is found,
then this method returns undefined .

getIsEntireColumn() Represents if the current range is an entire column.

getIsEntireRow() Represents if the current range is an entire row.

getLastCell() Gets the last cell within the range. For example, the last cell of
"B2:D5" is "D5".

getLastColumn() Gets the last column within the range. For example, the last
column of "B2:D5" is "D2:D5".
getLastRow() Gets the last row within the range. For example, the last row of
"B2:D5" is "B5:D5".

getLeft() Returns the distance in points, for 100% zoom, from the left
edge of the worksheet to the left edge of the range.

getLinkedDataTypeState() Represents the data type state of the cell.

getLinkedDataTypeStates() Represents the data type state of each cell.

getMergedAreas() Returns a RangeAreas object that represents the merged areas


in this range. Note that if the merged areas count in this range
is more than 512, then this method will fail to return the result.
If the RangeAreas object doesn't exist, then this function returns
undefined .

getNumberFormat() Represents cell Excel number format code for the given range.
If the range contains multiple cells, the data from first cell
(represented by row index of 0 and column index of 0) will be
returned.

getNumberFormatCategories() Represents the category of number format of each cell.

getNumberFormatCategory() Specifies the number format category of first cell in the range
(represented by row index of 0 and column index of 0).

getNumberFormatLocal() Represents cell Excel number format code for the given range,
based on the language settings of the user.​Excel does not
perform any language or format coercion when getting or
setting the numberFormatLocal property. Any returned text uses
the locally-formatted strings based on the language specified
in the system settings. If the range contains multiple cells, the
data from first cell (represented by row index of 0 and column
index of 0) will be returned.

getNumberFormats() Represents Excel's number format code for the given range.

getNumberFormatsLocal() Represents Excel's number format code for the given range,
based on the language settings of the user. Excel does not
perform any language or format coercion when getting or
setting the numberFormatLocal property. Any returned text uses
the locally-formatted strings based on the language specified
in the system settings.

getOffsetRange(rowOffset, Gets an object which represents a range that's offset from the
columnOffset) specified range. The dimension of the returned range will
match this range. If the resulting range is forced outside the
bounds of the worksheet grid, an error will be thrown.

getPivotTables(fullyContained) Gets a scoped collection of PivotTables that overlap with the


range.
getPredefinedCellStyle() Represents the style of the current range. If the styles of the
cells are inconsistent, null will be returned. For custom styles,
the style name will be returned. For built-in styles, a string
representing a value in the BuiltInStyle enum will be
returned.

getRangeEdge(direction, active Returns a range object that is the edge cell of the data region
Cell) that corresponds to the provided direction. This matches the
Ctrl+Arrow key behavior in the Excel on Windows UI.

getResizedRange(deltaRows, Gets a Range object similar to the current Range object, but
deltaColumns) with its bottom-right corner expanded (or contracted) by some
number of rows and columns.

getRow(row) Gets a row contained in the range.

getRowCount() Returns the total number of rows in the range.

getRowHidden() Represents if all rows in the current range are hidden. Value is
true when all rows in a range are hidden. Value is false when
no rows in the range are hidden. Value is null when some
rows in a range are hidden and other rows in the same range
are not hidden.

getRowIndex() Returns the row number of the first cell in the range. Zero-
indexed.

getRowsAbove(count) Gets a certain number of rows above the current Range object.

getRowsBelow(count) Gets a certain number of rows below the current Range object.

getSavedAsArray() Represents if all the cells would be saved as an array formula.


Returns true if all cells would be saved as an array formula, or
false if all cells would not be saved as an array formula.
Returns null if some cells would be saved as an array formula
and some would not be.

getSort() Represents the range sort of the current range.

getSpecialCells(cellType, cell Gets the RangeAreas object, comprising one or more ranges,
ValueType) that represents all the cells that match the specified type and
value. If no special cells are found, then this method returns
undefined .

getSpillingToRange() Gets the range object containing the spill range when called on
an anchor cell. If the range isn't an anchor cell or the spill range
can't be found, then this method returns undefined .

getSpillParent() Gets the range object containing the anchor cell for the cell
getting spilled into. If it's not a spilled cell, or more than one
cell is given, then this method returns undefined .
getSurroundingRegion() Returns a Range object that represents the surrounding region
for the top-left cell in this range. A surrounding region is a
range bounded by any combination of blank rows and blank
columns relative to this range.

getTables(fullyContained) Gets a scoped collection of tables that overlap with the range.

getText() Represents Text value of the specified range. The Text value will
not depend on the cell width. The # sign substitution that
happens in Excel UI will not affect the text value returned by
the API. If the range contains multiple cells, the data from first
cell (represented by row index of 0 and column index of 0) will
be returned.

getTexts() Text values of the specified range. The text value will not
depend on the cell width. The number sign (#) substitution that
happens in the Excel UI will not affect the text value returned
by the API.

getTop() Returns the distance in points, for 100% zoom, from the top
edge of the worksheet to the top edge of the range.

getUsedRange(valuesOnly) Returns the used range of the given range object. If there are
no used cells within the range, then this method returns
undefined .

getValue() Represents the raw value of the specified range. The data
returned could be of type string, number, or a boolean. Cell
that contain an error will return the error string. If the range
contains multiple cells, the data from first cell (represented by
row index of 0 and column index of 0) will be returned.

getValues() Represents the raw values of the specified range. The data
returned could be a string, number, or boolean. Cells that
contain an error will return the error string. If the returned
value starts with a plus ("+"), minus ("-"), or equal sign ("="),
Excel interprets this value as a formula.

getValueType() Represents the type of data in the cell. If the range contains
multiple cells, the data from first cell (represented by row index
of 0 and column index of 0) will be returned.

getValueTypes() Specifies the type of data in each cell.

getVisibleView() Represents the visible rows of the current range.

getWidth() Returns the distance in points, for 100% zoom, from the left
edge of the range to the right edge of the range.

getWorksheet() The worksheet containing the current range.


group(groupOption) Groups columns and rows for an outline.

hideGroupDetails(groupOption) Hides the details of the row or column group.

insert(shift) Inserts a cell or a range of cells into the worksheet in place of


this range, and shifts the other cells to make space. Returns a
new Range object at the now blank space.

merge(across) Merge the range cells into one region in the worksheet.

moveTo(destinationRange) Moves cell values, formatting, and formulas from current range
to the destination range, replacing the old information in those
cells. The destination range will be expanded automatically if it
is smaller than the current range. Any cells in the destination
range that are outside of the original range's area are not
changed.

removeDuplicates(columns, Removes duplicate values from the range specified by the


includesHeader) columns.

replaceAll(text, replacement, Finds and replaces the given string based on the criteria
criteria) specified within the current range.

select() Selects the specified range in the Excel UI.

setColumnHidden(column Represents if all columns in the current range are hidden. Value
Hidden) is true when all columns in a range are hidden. Value is false
when no columns in the range are hidden. Value is null when
some columns in a range are hidden and other columns in the
same range are not hidden.

setDirty() Set a range to be recalculated when the next recalculation


occurs.

setFormula(formula) Sets the cell formula in A1-style notation. If the range contains
multiple cells, each cell in the given range will be updated with
the input data.

setFormulaLocal(formulaLocal) Set the cell formula in A1-style notation, in the user's language
and number-formatting locale. For example, the English
"=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in
German. If the range contains multiple cells, each cell in the
given range will be updated with the input data.

setFormulaR1C1(formulaR1C1) Sets the cell formula in R1C1-style notation. If the range


contains multiple cells, each cell in the given range will be
updated with the input data.

setFormulas(formulas) Represents the formula in A1-style notation. If a cell has no


formula, its value is returned instead.
setFormulasLocal(formulas Represents the formula in A1-style notation, in the user's
Local) language and number-formatting locale. For example, the
English "=SUM(A1, 1.5)" formula would become "=SUMME(A1;
1,5)" in German. If a cell has no formula, its value is returned
instead.

set Represents the formula in R1C1-style notation. If a cell has no


FormulasR1C1(formulasR1C1) formula, its value is returned instead.

setHyperlink(hyperlink) Represents the hyperlink for the current range.

setNumberFormat(number Sets cell Excel number format code for the given range. If the
Format) range contains multiple cells, each cell in the given range will
be updated with the input data.

setNumberFormatLocal(number Sets cell Excel number format code for the given range, based
FormatLocal) on the language settings of the user.​Excel does not perform
any language or format coercion when getting or setting the
numberFormatLocal property. Any returned text uses the locally-
formatted strings based on the language specified in the
system settings. If the range contains multiple cells, each cell in
the given range will be updated with the input data.

setNumberFormats(number Represents Excel's number format code for the given range.
Formats)

setNumberFormats Represents Excel's number format code for the given range,
Local(numberFormatsLocal) based on the language settings of the user. Excel does not
perform any language or format coercion when getting or
setting the numberFormatLocal property. Any returned text uses
the locally-formatted strings based on the language specified
in the system settings.

setPredefinedCell Represents the style of the current range.


Style(predefinedCellStyle)

setRowHidden(rowHidden) Represents if all rows in the current range are hidden. Value is
true when all rows in a range are hidden. Value is false when
no rows in the range are hidden. Value is null when some
rows in a range are hidden and other rows in the same range
are not hidden.

setValue(value) Sets the raw value of the specified range. The data being set
could be of type string, number, or a boolean. null value will
be ignored (not set or overwritten in Excel). If the range
contains multiple cells, each cell in the given range will be
updated with the input data.

setValues(values) Sets the raw values of the specified range. The data provided
could be a string, number, or boolean. If the provided value
starts with a plus ("+"), minus ("-"), or equal sign ("="), Excel
interprets this value as a formula.

showCard() Displays the card for an active cell if it has rich value content.

showGroupDetails(group Shows the details of the row or column group.


Option)

ungroup(groupOption) Ungroups columns and rows for an outline.

unmerge() Unmerge the range cells into separate cells.

Method Details

addConditionalFormat(type)
Adds a new conditional format to the collection at the first/top priority.

TypeScript

addConditionalFormat(type: ConditionalFormatType): ConditionalFormat;

Parameters
type ExcelScript.ConditionalFormatType
The type of conditional format being added. See ExcelScript.ConditionalFormatType
for details.

Returns
ExcelScript.ConditionalFormat

Examples

TypeScript

/**
* This sample applies conditional formatting to the currently used range
in the worksheet.
* The conditional formatting is a green fill for the top 10% of values.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();
// Get the used range in the worksheet.
let range = selectedSheet.getUsedRange();

// Set the fill color to green for the top 10% of values in the range.
let conditionalFormat =
range.addConditionalFormat(ExcelScript.ConditionalFormatType.topBottom)

conditionalFormat.getTopBottom().getFormat().getFill().setColor("green");
conditionalFormat.getTopBottom().setRule({
rank: 10, // The percentage threshold.
type: ExcelScript.ConditionalTopBottomCriterionType.topPercent // The
type of the top/bottom condition.
});
}

autoFill(destinationRange, autoFillType)
Fills a range from the current range to the destination range using the specified
AutoFill logic. The destination range can be null or can extend the source range
either horizontally or vertically. Discontiguous ranges are not supported.

TypeScript

autoFill(
destinationRange?: Range | string,
autoFillType?: AutoFillType
): void;

Parameters
destinationRange ExcelScript.Range | string
The destination range to AutoFill. If the destination range is null , data is filled out
based on the surrounding cells (which is the behavior when double-clicking the UI's
range fill handle).

autoFillType ExcelScript.AutoFillType
The type of AutoFill. Specifies how the destination range is to be filled, based on the
contents of the current range. Default is "FillDefault".

Returns
void

Examples
TypeScript

/**
* This script uses the autofill feature to complete a table.
* See https://support.microsoft.com/office/74e31bdd-d993-45da-aa82-
35a236c5b5db
* for examples of autofill scenarios.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current, active worksheet.
let currentWorksheet = workbook.getActiveWorksheet();

// Get the data range that shows the pattern.


let dataRange = currentWorksheet.getRange("C2:C3");

// Autofill the connected range. C2:C3 are filled in. C4:C14 are blank.
// This uses the default behavior to match a pattern with the table's
contents.
dataRange.autoFill("C2:C14");
}

calculate()
Calculates a range of cells on a worksheet.

TypeScript

calculate(): void;

Returns
void

Examples

TypeScript

/**
* This script recalculates the used range of a specific worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Only recalculate if the calculation mode is not set to automatic.
if (workbook.getApplication().getCalculationMode() !==
ExcelScript.CalculationMode.automatic) {
// Get the used range from a worksheet named "Monthly Report".
const sheet = workbook.getWorksheet("Monthly Report");
const range = sheet.getUsedRange();
console.log(`Calculating ${range.getAddress()}`);
// Force all the used cells in that worksheet to calculate.
sheet.getUsedRange().calculate();
}
}

clear(applyTo)
Clear range values, format, fill, border, etc.

TypeScript

clear(applyTo?: ClearApplyTo): void;

Parameters
applyTo ExcelScript.ClearApplyTo
Optional. Determines the type of clear action. See ExcelScript.ClearApplyTo for
details.

Returns
void

Examples

TypeScript

/**
* This script removes all the formatting from the selected range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected range.
let range = workbook.getSelectedRange();

// Clear all the formatting in that range.


range.clear(ExcelScript.ClearApplyTo.formats);
}

clearAllConditionalFormats()
Clears all conditional formats active on the current specified range.
TypeScript

clearAllConditionalFormats(): void;

Returns
void

convertDataTypeToText()
Converts the range cells with data types into text.

TypeScript

convertDataTypeToText(): void;

Returns
void

copyFrom(sourceRange, copyType, skipBlanks, transpose)


Copies cell data or formatting from the source range or RangeAreas to the current
range. The destination range can be a different size than the source range or
RangeAreas . The destination is expanded automatically if it's smaller than the source.

Note: Like the copy functionality in the Excel UI, if the destination range is an exact
multiple greater than the source range in either rows or columns, then the source
content is replicated multiple times. For example, a 2x2 range copy into a 2x6 range
will result in 3 copies of the original 2x2 range.

TypeScript

copyFrom(
sourceRange: Range | RangeAreas | string,
copyType?: RangeCopyType,
skipBlanks?: boolean,
transpose?: boolean
): void;

Parameters
sourceRange ExcelScript.Range | ExcelScript.RangeAreas | string
The source range or RangeAreas to copy from. When the source RangeAreas has
multiple ranges, their form must be able to be created by removing full rows or
columns from a rectangular range.

copyType ExcelScript.RangeCopyType
The type of cell data or formatting to copy over. Default is "All".

skipBlanks boolean
True if to skip blank cells in the source range. Default is false.

transpose boolean
True if to transpose the cells in the destination range. Default is false.

Returns
void

Examples

TypeScript

/**
* This script copies a table from one worksheet to a new worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the worksheet named "TableTemplate".
let base = workbook.getWorksheet("TableTemplate");

// Get the range to be copied based on the first table.


let tableRange = base.getTables()[0].getRange();

// Get the area in a new worksheet for the new table.


let newWorksheet = workbook.addWorksheet();
let newRange = newWorksheet.getRangeByIndexes(0,0,
tableRange.getRowCount(), tableRange.getColumnCount());

// Copy the existing data into the new range.


newRange.copyFrom(tableRange);
}

delete(shift)
Deletes the cells associated with the range.

TypeScript
delete(shift: DeleteShiftDirection): void;

Parameters
shift ExcelScript.DeleteShiftDirection
Specifies which way to shift the cells. See ExcelScript.DeleteShiftDirection for
details.

Returns
void

Examples

TypeScript

/**
* This sample creates a sample range, then deletes
* "A1" using different DeleteShiftDirection values.
*/
function main(workbook: ExcelScript.Workbook) {
// Add sample data to better visualize the delete changes.
const currentSheet = workbook.getActiveWorksheet();
currentSheet.getRange("A1:D4").setValues([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]);

// Delete A1 and shift the cells from the right to fill the space.
// The value being deleted is 1.

currentSheet.getRange("A1").delete(ExcelScript.DeleteShiftDirection.left)
;

// Delete A1 and shift the cells from the bottom to fill the space.
// The value being deleted is 2.

currentSheet.getRange("A1").delete(ExcelScript.DeleteShiftDirection.up);

// Log the sample range. The values should be:


/*
5, 3, 4, "",
9, 6, 7, 8,
13, 10, 11, 12,
"", 14, 15, 16
*/
console.log(currentSheet.getRange("A1:D4").getValues());
}

find(text, criteria)
Finds the given string based on the criteria specified. If the current range is larger
than a single cell, then the search will be limited to that range, else the search will
cover the entire sheet starting after that cell. If there are no matches, then this
method returns undefined .

TypeScript

find(text: string, criteria: SearchCriteria): Range;

Parameters
text string
The string to find.

criteria ExcelScript.SearchCriteria
Additional search criteria, including the search direction and whether the search
needs to match the entire cell or be case-sensitive.

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script searches through a table column and finds cells marked "no
change".
* Those cells have "no change" replaced with the value from the cell to
the left.
* This script uses Range.find instead of Worksheet.findAll
* to limit the search to a specific range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range of a table named "Orders".
let table = workbook.getTable("Orders");
let range = table.getColumnByName("March").getRange();
// Find all cells with the value "no change".
let cellToOverwrite = range.find("no change", { completeMatch: true });
while (cellToOverwrite) {
let cellToCopyFrom = cellToOverwrite.getOffsetRange(0,-1);
cellToOverwrite.setValue(cellToCopyFrom.getValue());
cellToOverwrite = range.find("no change", { completeMatch: true });
}
}

flashFill()
Does a Flash Fill to the current range. Flash Fill automatically fills data when it senses
a pattern, so the range must be a single column range and have data around it in
order to find a pattern.

TypeScript

flashFill(): void;

Returns
void

Examples

TypeScript

/**
* This script uses the Flash Fill feature to complete a table.
* See https://support.microsoft.com/office/3f9bcf1e-db93-4890-94a0-
1578341f73f7
* for the example table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current, active worksheet.
let currentWorksheet = workbook.getActiveWorksheet();

// Get the data range with a pattern and cells to fill. C2 is filled
in. C3:C6 are blank.
let dataRange = currentWorksheet.getRange("C2:C6");

// Flash fill the connected range.


dataRange.flashFill();
}
getAbsoluteResizedRange(numRows, numColumns)
Gets a Range object with the same top-left cell as the current Range object, but with
the specified numbers of rows and columns.

TypeScript

getAbsoluteResizedRange(numRows: number, numColumns: number): Range;

Parameters
numRows number
The number of rows of the new range size.

numColumns number
The number of columns of the new range size.

Returns
ExcelScript.Range

getAddress()
Specifies the range reference in A1-style. Address value contains the sheet reference
(e.g., "Sheet1!A1:B4").

TypeScript

getAddress(): string;

Returns
string

Examples

TypeScript

/**
* This script logs the address of the used range in each worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Iterate over every worksheet in the workbook.
workbook.getWorksheets().forEach((sheet) => {
// Get the used range for a single worksheet.
let range = sheet.getUsedRange();

// Print the address of the used range to the console.


console.log(range.getAddress());
});
}

getAddressLocal()
Represents the range reference for the specified range in the language of the user.

TypeScript

getAddressLocal(): string;

Returns
string

getBoundingRect(anotherRange)
Gets the smallest range object that encompasses the given ranges. For example, the
GetBoundingRect of "B2:C5" and "D10:E15" is "B2:E15".

TypeScript

getBoundingRect(anotherRange: Range | string): Range;

Parameters
anotherRange ExcelScript.Range | string
The range object, address, or range name.

Returns
ExcelScript.Range

Examples
TypeScript

/**
* This script gets the bounding range of two existing ranges and puts a
border around it.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let sheet = workbook.getActiveWorksheet();

// Create two range objects for the sample.


let range1 = sheet.getRange("B2:C5");
let range2 = sheet.getRange("D10:E15");

// Get the rectangular range that fully includes both ranges.


let boundingRectangle = range1.getBoundingRect(range2);

// Add a border around the whole bounding range (B2:E15).


let format = boundingRectangle.getFormat();

format.getRangeBorder(ExcelScript.BorderIndex.edgeTop).setStyle(ExcelScri
pt.BorderLineStyle.continuous); // Top border

format.getRangeBorder(ExcelScript.BorderIndex.edgeBottom).setStyle(ExcelS
cript.BorderLineStyle.continuous); // Bottom border

format.getRangeBorder(ExcelScript.BorderIndex.edgeLeft).setStyle(ExcelScr
ipt.BorderLineStyle.continuous); // Left border

format.getRangeBorder(ExcelScript.BorderIndex.edgeRight).setStyle(ExcelSc
ript.BorderLineStyle.continuous); // Right border
}

getCell(row, column)
Gets the range object containing the single cell based on row and column numbers.
The cell can be outside the bounds of its parent range, so long as it stays within the
worksheet grid. The returned cell is located relative to the top left cell of the range.

TypeScript

getCell(row: number, column: number): Range;

Parameters
row number
Row number of the cell to be retrieved. Zero-indexed.
column number
Column number of the cell to be retrieved. Zero-indexed.

Returns
ExcelScript.Range

getCellCount()
Specifies the number of cells in the range. This API will return -1 if the cell count
exceeds 2^31-1 (2,147,483,647).

TypeScript

getCellCount(): number;

Returns
number

getColumn(column)
Gets a column contained in the range.

TypeScript

getColumn(column: number): Range;

Parameters
column number
Column number of the range to be retrieved. Zero-indexed.

Returns
ExcelScript.Range

getColumnCount()
Specifies the total number of columns in the range.
TypeScript

getColumnCount(): number;

Returns
number

Examples

TypeScript

/**
* This sample provides the count of negative numbers that are present
* in the used range of the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the working range.
let usedRange = workbook.getActiveWorksheet().getUsedRange();
let rowCount = usedRange.getRowCount();
let columnCount = usedRange.getColumnCount();

// Save the values locally to avoid repeatedly asking the workbook.


let usedRangeValues = usedRange.getValues();

// Start the negative number counter.


let negativeCount = 0;

// Iterate over the entire range looking for negative numbers.


for (let i = 0; i < rowCount; i++) {
for (let j = 0; j < columnCount; j++) {
if (usedRangeValues[i][j] < 0) {
negativeCount++;
}
}
}

// Log the negative number count to the console.


console.log(negativeCount);
}

getColumnHidden()
Represents if all columns in the current range are hidden. Value is true when all
columns in a range are hidden. Value is false when no columns in the range are
hidden. Value is null when some columns in a range are hidden and other columns
in the same range are not hidden.
TypeScript

getColumnHidden(): boolean;

Returns
boolean

getColumnIndex()
Specifies the column number of the first cell in the range. Zero-indexed.

TypeScript

getColumnIndex(): number;

Returns
number

getColumnsAfter(count)
Gets a certain number of columns to the right of the current Range object.

TypeScript

getColumnsAfter(count?: number): Range;

Parameters
count number
Optional. The number of columns to include in the resulting range. In general, use a
positive number to create a range outside the current range. You can also use a
negative number to create a range within the current range. The default value is 1.

Returns
ExcelScript.Range

getColumnsBefore(count)
Gets a certain number of columns to the left of the current Range object.

TypeScript

getColumnsBefore(count?: number): Range;

Parameters
count number
Optional. The number of columns to include in the resulting range. In general, use a
positive number to create a range outside the current range. You can also use a
negative number to create a range within the current range. The default value is 1.

Returns
ExcelScript.Range

getConditionalFormat(id)
Returns a conditional format identified by its ID. If the conditional format object does
not exist, then this method returns undefined .

TypeScript

getConditionalFormat(id: string): ConditionalFormat | undefined;

Parameters
id string
The ID of the conditional format.

Returns
ExcelScript.ConditionalFormat | undefined

getConditionalFormats()
The collection of ConditionalFormats that intersect the range.

TypeScript
getConditionalFormats(): ConditionalFormat[];

Returns
ExcelScript.ConditionalFormat[]

getDataValidation()
Returns a data validation object.

TypeScript

getDataValidation(): DataValidation;

Returns
ExcelScript.DataValidation

Examples

TypeScript

/**
* This script creates a drop-down selection list for a cell. It uses the
existing values of the selected range as the choices for the list.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the values for data validation.
let selectedRange = workbook.getSelectedRange();
let 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.
let targetCell = selectedRange.getCell(0,0);
let dataValidation = targetCell.getDataValidation();
// Set the content of the drop-down list.
dataValidation.setRule({
list: {
inCellDropDown: true,
source: dataValidationListString
}
});
}

getDirectPrecedents()
Returns a WorkbookRangeAreas object that represents the range containing all the
direct precedent cells of a specified range in the same worksheet or across multiple
worksheets.

TypeScript

getDirectPrecedents(): WorkbookRangeAreas;

Returns
ExcelScript.WorkbookRangeAreas

Examples

TypeScript

/**
* This script finds the direct precedents of the active cell.
* It changes the font and color of those precedent cells.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the active cell.
const selected = workbook.getActiveCell();

// Get the cells that are direct precedents of the current cell.
const precedents : ExcelScript.WorkbookRangeAreas =
selected.getDirectPrecedents();

// Set the font to bold and the fill color to orange for all the
precedent cells.
precedents.getRanges().forEach(range => {
range.getFormat().getFill().setColor("orange");
range.getFormat().getFont().setBold(true);
});
}
getEntireColumn()
Gets an object that represents the entire column of the range (for example, if the
current range represents cells "B4:E11", its getEntireColumn is a range that
represents columns "B:E").

TypeScript

getEntireColumn(): Range;

Returns
ExcelScript.Range

getEntireRow()
Gets an object that represents the entire row of the range (for example, if the current
range represents cells "B4:E11", its GetEntireRow is a range that represents rows
"4:11").

TypeScript

getEntireRow(): Range;

Returns
ExcelScript.Range

getExtendedRange(direction, activeCell)
Returns a range object that includes the current range and up to the edge of the
range, based on the provided direction. This matches the Ctrl+Shift+Arrow key
behavior in the Excel on Windows UI.

TypeScript

getExtendedRange(
direction: KeyboardDirection,
activeCell?: Range | string
): Range;
Parameters
direction ExcelScript.KeyboardDirection
The direction from the active cell.

activeCell ExcelScript.Range | string


The active cell in this range. By default, the active cell is the top-left cell of the range.
An error is thrown if the active cell is not in this range.

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script makes the font bold on all the contiguous cells between
* A1 and the bottom of the used range of the first column.
*/
function main(workbook: ExcelScript.Workbook)
{
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get every cell that's used between A1 and the end of the column.
// This recreates the Ctrl+Shift+Down arrow key behavior.
let firstCell = selectedSheet.getRange("A1");
let firstColumn =
firstCell.getExtendedRange(ExcelScript.KeyboardDirection.down);

// Set the font to bold in that range.


firstColumn.getFormat().getFont().setBold(true);
}

getFormat()
Returns a format object, encapsulating the range's font, fill, borders, alignment, and
other properties.

TypeScript

getFormat(): RangeFormat;
Returns
ExcelScript.RangeFormat

Examples

TypeScript

/**
* This script gives the total row of a table a green color fill.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the workbook.
let table = workbook.getTables()[0];

// Get the range for the total row of the table.


let totalRange = table.getTotalRowRange();

// Set the fill color to green.


totalRange.getFormat().getFill().setColor("green");
}

getFormula()
Represents the cell formula in A1-style notation. If the range contains multiple cells,
the data from first cell (represented by row index of 0 and column index of 0) will be
returned.

TypeScript

getFormula(): string;

Returns
string

Examples

TypeScript

/*
* This script sets a cell's formula,
* then displays how Excel stores the cell's formula and value
separately.
*/
function main(workbook: ExcelScript.Workbook) {
let selectedSheet = workbook.getActiveWorksheet();

// Set A1 to 2.
let a1 = selectedSheet.getRange("A1");
a1.setValue(2);

// Set B1 to the formula =(2*A1), which should equal 4.


let b1 = selectedSheet.getRange("B1")
b1.setFormula("=(2*A1)");

// Log the current results for `getFormula` and `getValue` at B1.


console.log(`B1 - Formula: ${b1.getFormula()} | Value:
${b1.getValue()}`);
}

getFormulaLocal()
Represents the cell formula in A1-style notation, in the user's language and number-
formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become
"=SUMME(A1; 1,5)" in German. If the range contains multiple cells, the data from first
cell (represented by row index of 0 and column index of 0) will be returned.

TypeScript

getFormulaLocal(): string;

Returns
string

getFormulaR1C1()
Represents the cell formula in R1C1-style notation. If the range contains multiple
cells, the data from first cell (represented by row index of 0 and column index of 0)
will be returned.

TypeScript

getFormulaR1C1(): string;

Returns
string
getFormulas()
Represents the formula in A1-style notation. If a cell has no formula, its value is
returned instead.

TypeScript

getFormulas(): string[][];

Returns
string[][]

getFormulasLocal()
Represents the formula in A1-style notation, in the user's language and number-
formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become
"=SUMME(A1; 1,5)" in German. If a cell has no formula, its value is returned instead.

TypeScript

getFormulasLocal(): string[][];

Returns
string[][]

getFormulasR1C1()
Represents the formula in R1C1-style notation. If a cell has no formula, its value is
returned instead.

TypeScript

getFormulasR1C1(): string[][];

Returns
string[][]

getHasSpill()
Represents if all cells have a spill border. Returns true if all cells have a spill border,
or false if all cells do not have a spill border. Returns null if there are cells both
with and without spill borders within the range.

TypeScript

getHasSpill(): boolean;

Returns
boolean

getHeight()
Returns the distance in points, for 100% zoom, from the top edge of the range to the
bottom edge of the range.

TypeScript

getHeight(): number;

Returns
number

getHidden()
Represents if all cells in the current range are hidden. Value is true when all cells in a
range are hidden. Value is false when no cells in the range are hidden. Value is null
when some cells in a range are hidden and other cells in the same range are not
hidden.

TypeScript

getHidden(): boolean;

Returns
boolean
getHyperlink()
Represents the hyperlink for the current range.

TypeScript

getHyperlink(): RangeHyperlink;

Returns
ExcelScript.RangeHyperlink

Examples

TypeScript

/**
* This sample clears all of the hyperlinks from the current worksheet
* and removes the usual hyperlink formatting.
*/
function main(workbook: ExcelScript.Workbook, sheetName: string =
'Sheet1') {
// Get the active worksheet.
let sheet = workbook.getWorksheet(sheetName);

// Get the used range to operate on.


// For large ranges (over 10000 entries), consider splitting the
operation into batches for performance.
const targetRange = sheet.getUsedRange(true);
console.log(`Target Range to clear hyperlinks from:
${targetRange.getAddress()}`);

const rowCount = targetRange.getRowCount();


const colCount = targetRange.getColumnCount();
console.log(`Searching for hyperlinks in ${targetRange.getAddress()}
which contains ${(rowCount * colCount)} cells`);

// Go through each individual cell looking for a hyperlink.


// This allows us to limit the formatting changes to only the cells
with hyperlink formatting.
let clearedCount = 0;
for (let i = 0; i < rowCount; i++) {
for (let j = 0; j < colCount; j++) {
const cell = targetRange.getCell(i, j);
const hyperlink = cell.getHyperlink();
if (hyperlink) {
cell.clear(ExcelScript.ClearApplyTo.hyperlinks);

cell.getFormat().getFont().setUnderline(ExcelScript.RangeUnderlineStyle.n
one);
cell.getFormat().getFont().setColor('Black');
clearedCount++;
}
}
}

console.log(`Done. Cleared hyperlinks from ${clearedCount} cells`);


}

getImage()
Renders the range as a base64-encoded png image.

TypeScript

getImage(): string;

Returns
string

getIntersection(anotherRange)
Gets the range object that represents the rectangular intersection of the given
ranges. If no intersection is found, then this method returns undefined .

TypeScript

getIntersection(anotherRange: Range | string): Range;

Parameters
anotherRange ExcelScript.Range | string
The range object or range address that will be used to determine the intersection of
ranges.

Returns
ExcelScript.Range

getIsEntireColumn()
Represents if the current range is an entire column.

TypeScript

getIsEntireColumn(): boolean;

Returns
boolean

getIsEntireRow()
Represents if the current range is an entire row.

TypeScript

getIsEntireRow(): boolean;

Returns
boolean

getLastCell()
Gets the last cell within the range. For example, the last cell of "B2:D5" is "D5".

TypeScript

getLastCell(): Range;

Returns
ExcelScript.Range

getLastColumn()
Gets the last column within the range. For example, the last column of "B2:D5" is
"D2:D5".

TypeScript
getLastColumn(): Range;

Returns
ExcelScript.Range

getLastRow()
Gets the last row within the range. For example, the last row of "B2:D5" is "B5:D5".

TypeScript

getLastRow(): Range;

Returns
ExcelScript.Range

getLeft()
Returns the distance in points, for 100% zoom, from the left edge of the worksheet
to the left edge of the range.

TypeScript

getLeft(): number;

Returns
number

getLinkedDataTypeState()
Represents the data type state of the cell.

TypeScript

getLinkedDataTypeState(): LinkedDataTypeState;

Returns
ExcelScript.LinkedDataTypeState

getLinkedDataTypeStates()
Represents the data type state of each cell.

TypeScript

getLinkedDataTypeStates(): LinkedDataTypeState[][];

Returns
ExcelScript.LinkedDataTypeState[][]

getMergedAreas()
Returns a RangeAreas object that represents the merged areas in this range. Note
that if the merged areas count in this range is more than 512, then this method will
fail to return the result. If the RangeAreas object doesn't exist, then this function
returns undefined .

TypeScript

getMergedAreas(): RangeAreas;

Returns
ExcelScript.RangeAreas

getNumberFormat()
Represents cell Excel number format code for the given range. If the range contains
multiple cells, the data from first cell (represented by row index of 0 and column
index of 0) will be returned.

TypeScript

getNumberFormat(): string;

Returns
string

getNumberFormatCategories()
Represents the category of number format of each cell.

TypeScript

getNumberFormatCategories(): NumberFormatCategory[][];

Returns
ExcelScript.NumberFormatCategory[][]

Examples

TypeScript

/**
* This script finds cells in a table column that are not formatted as
currency
* and sets the fill color to red.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the "Cost" column from the "Expenses" table.
const table = workbook.getTable("Expenses");
const costColumn = table.getColumnByName("Cost");
const costColumnRange = costColumn.getRangeBetweenHeaderAndTotal();

// Get the number format categories for the column's range.


const numberFormatCategories =
costColumnRange.getNumberFormatCategories();

// If any cell in the column doesn't have a currency format, make the
cell red.
numberFormatCategories.forEach((category, index) =>{
if (category[0] != ExcelScript.NumberFormatCategory.currency) {
costColumnRange.getCell(index,
0).getFormat().getFill().setColor("red");
}
});
}

getNumberFormatCategory()
Specifies the number format category of first cell in the range (represented by row
index of 0 and column index of 0).

TypeScript

getNumberFormatCategory(): NumberFormatCategory;

Returns
ExcelScript.NumberFormatCategory

getNumberFormatLocal()
Represents cell Excel number format code for the given range, based on the
language settings of the user.​Excel does not perform any language or format
coercion when getting or setting the numberFormatLocal property. Any returned text
uses the locally-formatted strings based on the language specified in the system
settings. If the range contains multiple cells, the data from first cell (represented by
row index of 0 and column index of 0) will be returned.

TypeScript

getNumberFormatLocal(): string;

Returns
string

getNumberFormats()
Represents Excel's number format code for the given range.

TypeScript

getNumberFormats(): string[][];

Returns
string[][]

getNumberFormatsLocal()
Represents Excel's number format code for the given range, based on the language
settings of the user. Excel does not perform any language or format coercion when
getting or setting the numberFormatLocal property. Any returned text uses the
locally-formatted strings based on the language specified in the system settings.

TypeScript

getNumberFormatsLocal(): string[][];

Returns
string[][]

getOffsetRange(rowOffset, columnOffset)
Gets an object which represents a range that's offset from the specified range. The
dimension of the returned range will match this range. If the resulting range is forced
outside the bounds of the worksheet grid, an error will be thrown.

TypeScript

getOffsetRange(rowOffset: number, columnOffset: number): Range;

Parameters
rowOffset number
The number of rows (positive, negative, or 0) by which the range is to be offset.
Positive values are offset downward, and negative values are offset upward.

columnOffset number
The number of columns (positive, negative, or 0) by which the range is to be offset.
Positive values are offset to the right, and negative values are offset to the left.

Returns
ExcelScript.Range

Examples

TypeScript
/**
* This script gets adjacent cells using relative references.
* Note that if the active cell is on the top row, part of the script
fails,
* because it references the cell above the currently selected one.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the currently active cell in the workbook.
let activeCell = workbook.getActiveCell();
console.log(`The active cell's address is:
${activeCell.getAddress()}`);

// Get the cell to the right of the active cell and set its value and
color.
let rightCell = activeCell.getOffsetRange(0,1);
rightCell.setValue("Right cell");
console.log(`The right cell's address is: ${rightCell.getAddress()}`);
rightCell.getFormat().getFont().setColor("Magenta");
rightCell.getFormat().getFill().setColor("Cyan");

// Get the cell to the above of the active cell and set its value and
color.
// Note that this operation will fail if the active cell is in the top
row.
let aboveCell = activeCell.getOffsetRange(-1, 0);
aboveCell.setValue("Above cell");
console.log(`The above cell's address is: ${aboveCell.getAddress()}`);
aboveCell.getFormat().getFont().setColor("White");
aboveCell.getFormat().getFill().setColor("Black");
}

getPivotTables(fullyContained)
Gets a scoped collection of PivotTables that overlap with the range.

TypeScript

getPivotTables(fullyContained?: boolean): PivotTable[];

Parameters
fullyContained boolean
If true , returns only PivotTables that are fully contained within the range bounds.
The default value is false .

Returns
ExcelScript.PivotTable[]

getPredefinedCellStyle()
Represents the style of the current range. If the styles of the cells are inconsistent,
null will be returned. For custom styles, the style name will be returned. For built-in

styles, a string representing a value in the BuiltInStyle enum will be returned.

TypeScript

getPredefinedCellStyle(): string;

Returns
string

getRangeEdge(direction, activeCell)
Returns a range object that is the edge cell of the data region that corresponds to
the provided direction. This matches the Ctrl+Arrow key behavior in the Excel on
Windows UI.

TypeScript

getRangeEdge(
direction: KeyboardDirection,
activeCell?: Range | string
): Range;

Parameters
direction ExcelScript.KeyboardDirection
The direction from the active cell.

activeCell ExcelScript.Range | string


The active cell in this range. By default, the active cell is the top-left cell of the range.
An error is thrown if the active cell is not in this range.

Returns
ExcelScript.Range
Examples

TypeScript

/**
* This script adds the value "Total" after the end of the first column.
*/
function main(workbook: ExcelScript.Workbook)
{
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get the last used cell at the end of the column.


// This recreates the Ctrl+Down arrow key behavior.
let firstCell = selectedSheet.getRange("A1");
let firstColumn =
selectedSheet.getRange("A1").getRangeEdge(ExcelScript.KeyboardDirection.d
own);
let cellAfter = firstColumn.getOffsetRange(1, 0);

// Set the value of the cell after the current end of the used column
to "Total".
cellAfter.setValue("Total");
}

getResizedRange(deltaRows, deltaColumns)
Gets a Range object similar to the current Range object, but with its bottom-right
corner expanded (or contracted) by some number of rows and columns.

TypeScript

getResizedRange(deltaRows: number, deltaColumns: number): Range;

Parameters
deltaRows number
The number of rows by which to expand the bottom-right corner, relative to the
current range. Use a positive number to expand the range, or a negative number to
decrease it.

deltaColumns number
The number of columns by which to expand the bottom-right corner, relative to the
current range. Use a positive number to expand the range, or a negative number to
decrease it.
Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script copies the formatting in the active cell to the
neighboring cells.
* Note that this script only works when the active cell isn't on an edge
of the worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the active cell.
let activeCell = workbook.getActiveCell();

// Get the cell that's one row above and one column to the left of the
active cell.
let cornerCell = activeCell.getOffsetRange(-1,-1);

// Get a range that includes all the cells surrounding the active cell.
let surroundingRange = cornerCell.getResizedRange(2, 2)

// Copy the formatting from the active cell to the new range.
surroundingRange.copyFrom(
activeCell, /* The source range. */
ExcelScript.RangeCopyType.formats /* What to copy. */
);
}

getRow(row)
Gets a row contained in the range.

TypeScript

getRow(row: number): Range;

Parameters
row number
Row number of the range to be retrieved. Zero-indexed.

Returns
ExcelScript.Range

getRowCount()
Returns the total number of rows in the range.

TypeScript

getRowCount(): number;

Returns
number

Examples

TypeScript

/**
* This sample provides the count of negative numbers that are present
* in the used range of the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the working range.
let usedRange = workbook.getActiveWorksheet().getUsedRange();
let rowCount = usedRange.getRowCount();
let columnCount = usedRange.getColumnCount();

// Save the values locally to avoid repeatedly asking the workbook.


let usedRangeValues = usedRange.getValues();

// Start the negative number counter.


let negativeCount = 0;

// Iterate over the entire range looking for negative numbers.


for (let i = 0; i < rowCount; i++) {
for (let j = 0; j < columnCount; j++) {
if (usedRangeValues[i][j] < 0) {
negativeCount++;
}
}
}

// Log the negative number count to the console.


console.log(negativeCount);
}
getRowHidden()
Represents if all rows in the current range are hidden. Value is true when all rows in
a range are hidden. Value is false when no rows in the range are hidden. Value is
null when some rows in a range are hidden and other rows in the same range are

not hidden.

TypeScript

getRowHidden(): boolean;

Returns
boolean

getRowIndex()
Returns the row number of the first cell in the range. Zero-indexed.

TypeScript

getRowIndex(): number;

Returns
number

getRowsAbove(count)
Gets a certain number of rows above the current Range object.

TypeScript

getRowsAbove(count?: number): Range;

Parameters
count number
Optional. The number of rows to include in the resulting range. In general, use a
positive number to create a range outside the current range. You can also use a
negative number to create a range within the current range. The default value is 1.
Returns
ExcelScript.Range

getRowsBelow(count)
Gets a certain number of rows below the current Range object.

TypeScript

getRowsBelow(count?: number): Range;

Parameters
count number
Optional. The number of rows to include in the resulting range. In general, use a
positive number to create a range outside the current range. You can also use a
negative number to create a range within the current range. The default value is 1.

Returns
ExcelScript.Range

getSavedAsArray()
Represents if all the cells would be saved as an array formula. Returns true if all cells
would be saved as an array formula, or false if all cells would not be saved as an
array formula. Returns null if some cells would be saved as an array formula and
some would not be.

TypeScript

getSavedAsArray(): boolean;

Returns
boolean

getSort()
Represents the range sort of the current range.
TypeScript

getSort(): RangeSort;

Returns
ExcelScript.RangeSort

getSpecialCells(cellType, cellValueType)
Gets the RangeAreas object, comprising one or more ranges, that represents all the
cells that match the specified type and value. If no special cells are found, then this
method returns undefined .

TypeScript

getSpecialCells(
cellType: SpecialCellType,
cellValueType?: SpecialCellValueType
): RangeAreas;

Parameters
cellType ExcelScript.SpecialCellType
The type of cells to include.

cellValueType ExcelScript.SpecialCellValueType
If cellType is either constants or formulas , this argument is used to determine
which types of cells to include in the result. These values can be combined together
to return more than one type. The default is to select all constants or formulas, no
matter what the type.

Returns
ExcelScript.RangeAreas

Examples

TypeScript

/**
* This sample gets all the blank cells in the current worksheet's used
range. It then highlights all those cells with a yellow background.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current used range.
let range = workbook.getActiveWorksheet().getUsedRange();

// Get all the blank cells.


let blankCells =
range.getSpecialCells(ExcelScript.SpecialCellType.blanks);
// Highlight the blank cells with a yellow background.
blankCells.getFormat().getFill().setColor("yellow");
}

getSpillingToRange()
Gets the range object containing the spill range when called on an anchor cell. If the
range isn't an anchor cell or the spill range can't be found, then this method returns
undefined .

TypeScript

getSpillingToRange(): Range;

Returns
ExcelScript.Range

getSpillParent()
Gets the range object containing the anchor cell for the cell getting spilled into. If it's
not a spilled cell, or more than one cell is given, then this method returns undefined .

TypeScript

getSpillParent(): Range;

Returns
ExcelScript.Range

getSurroundingRegion()
Returns a Range object that represents the surrounding region for the top-left cell in
this range. A surrounding region is a range bounded by any combination of blank
rows and blank columns relative to this range.

TypeScript

getSurroundingRegion(): Range;

Returns
ExcelScript.Range

getTables(fullyContained)
Gets a scoped collection of tables that overlap with the range.

TypeScript

getTables(fullyContained?: boolean): Table[];

Parameters
fullyContained boolean
If true , returns only tables that are fully contained within the range bounds. The
default value is false .

Returns
ExcelScript.Table[]

getText()
Represents Text value of the specified range. The Text value will not depend on the
cell width. The # sign substitution that happens in Excel UI will not affect the text
value returned by the API. If the range contains multiple cells, the data from first cell
(represented by row index of 0 and column index of 0) will be returned.

TypeScript

getText(): string;
Returns
string

getTexts()
Text values of the specified range. The text value will not depend on the cell width.
The number sign (#) substitution that happens in the Excel UI will not affect the text
value returned by the API.

TypeScript

getTexts(): string[][];

Returns
string[][]

getTop()
Returns the distance in points, for 100% zoom, from the top edge of the worksheet
to the top edge of the range.

TypeScript

getTop(): number;

Returns
number

getUsedRange(valuesOnly)
Returns the used range of the given range object. If there are no used cells within
the range, then this method returns undefined .

TypeScript

getUsedRange(valuesOnly?: boolean): Range;

Parameters
valuesOnly boolean
Considers only cells with values as used cells.

Returns
ExcelScript.Range

getValue()
Represents the raw value of the specified range. The data returned could be of type
string, number, or a boolean. Cell that contain an error will return the error string. If
the range contains multiple cells, the data from first cell (represented by row index of
0 and column index of 0) will be returned.

TypeScript

getValue(): string | number | boolean;

Returns
string | number | boolean

Examples

TypeScript

/**
* This sample reads the value of A1 and prints it to the console.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get the value of cell A1.


let range = selectedSheet.getRange("A1");

// Print the value of A1.


console.log(range.getValue());
}

getValues()
Represents the raw values of the specified range. The data returned could be a
string, number, or boolean. Cells that contain an error will return the error string. If
the returned value starts with a plus ("+"), minus ("-"), or equal sign ("="), Excel
interprets this value as a formula.

TypeScript

getValues(): (string | number | boolean)[][];

Returns
(string | number | boolean)[][]

getValueType()
Represents the type of data in the cell. If the range contains multiple cells, the data
from first cell (represented by row index of 0 and column index of 0) will be returned.

TypeScript

getValueType(): RangeValueType;

Returns
ExcelScript.RangeValueType

Examples

TypeScript

/**
* This script formats rows in a worksheet based on the first value in
that row.
* If it's the boolean value TRUE, the row is bolded.
* If it's FALSE, nothing is changed.
* If the value type isn't a boolean, the row is italicized.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range in the active worksheet.
const sheet = workbook.getActiveWorksheet();
const usedRange = sheet.getUsedRange();

// Get the values in the first column.


const firstColumnValues = usedRange.getColumn(0).getValues();
// Look at the first cell in each row.
const rowCount = usedRange.getRowCount();
for (let i = 0; i < rowCount; i++) {
// Get the type of the first cell to make sure it's a boolean.
let firstValueType = usedRange.getCell(i, 0).getValueType();

// Set the bold or italic of the row as described earlier.


if (firstValueType === ExcelScript.RangeValueType.boolean) {
if (firstColumnValues[i][0] as boolean === true) {
usedRange.getRow(i).getFormat().getFont().setBold(true);
} else {
usedRange.getRow(i).getFormat().getFont().setBold(false);
}
} else {
usedRange.getRow(i).getFormat().getFont().setItalic(true);
}
}
}

getValueTypes()
Specifies the type of data in each cell.

TypeScript

getValueTypes(): RangeValueType[][];

Returns
ExcelScript.RangeValueType[][]

getVisibleView()
Represents the visible rows of the current range.

TypeScript

getVisibleView(): RangeView;

Returns
ExcelScript.RangeView

Examples
TypeScript

/**
* This script copies values and formatting from the
* visible range of a table in Sheet1 into Sheet2.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the filtered data from Sheet1.
const currentSheet = workbook.getWorksheet("Sheet1");
const table = currentSheet.getTables()[0];
const visibleTableRange: ExcelScript.RangeView =
table.getRange().getVisibleView();
const source =
currentSheet.getRanges(visibleTableRange.getCellAddresses().toString());

// Copy the data into the other sheet.


const otherSheet = workbook.getWorksheet("Sheet2");
const otherRangeCorner = otherSheet.getRange("A1");
otherRangeCorner.copyFrom(source, ExcelScript.RangeCopyType.all);
}

getWidth()
Returns the distance in points, for 100% zoom, from the left edge of the range to the
right edge of the range.

TypeScript

getWidth(): number;

Returns
number

getWorksheet()
The worksheet containing the current range.

TypeScript

getWorksheet(): Worksheet;

Returns
ExcelScript.Worksheet
group(groupOption)
Groups columns and rows for an outline.

TypeScript

group(groupOption: GroupOption): void;

Parameters
groupOption ExcelScript.GroupOption
Specifies how the range can be grouped by rows or columns. An InvalidArgument
error is thrown when the group option differs from the range's isEntireRow or
isEntireColumn property (i.e., range.isEntireRow is true and groupOption is

"ByColumns" or range.isEntireColumn is true and groupOption is "ByRows").

Returns
void

Examples

TypeScript

/**
* This script creates a two-level column-based outline on Sheet1.
*/
function main(workbook: ExcelScript.Workbook) {
// Group columns A-F in the worksheet named Sheet1.
const sheet = workbook.getWorksheet("Sheet1");
const firstLevel = sheet.getRange("A:F");
firstLevel.group(ExcelScript.GroupOption.byColumns);

// Create a second level to the outline by grouping subsections.


sheet.getRange("A:B").group(ExcelScript.GroupOption.byColumns);
sheet.getRange("D:E").group(ExcelScript.GroupOption.byColumns);
}

hideGroupDetails(groupOption)
Hides the details of the row or column group.

TypeScript
hideGroupDetails(groupOption: GroupOption): void;

Parameters
groupOption ExcelScript.GroupOption
Specifies whether to hide the details of grouped rows or grouped columns.

Returns
void

insert(shift)
Inserts a cell or a range of cells into the worksheet in place of this range, and shifts
the other cells to make space. Returns a new Range object at the now blank space.

TypeScript

insert(shift: InsertShiftDirection): Range;

Parameters
shift ExcelScript.InsertShiftDirection
Specifies which way to shift the cells. See ExcelScript.InsertShiftDirection for
details.

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script inserts headers at the top of the worksheet.
*/
function main(workbook: ExcelScript.Workbook)
{
let currentSheet = workbook.getActiveWorksheet();

// Create headers for 3 columns.


let myHeaders = [["NAME", "ID", "ROLE"]];

// Add a blank first row and push existing data down a row.
let firstRow = currentSheet.getRange("1:1");
firstRow.insert(ExcelScript.InsertShiftDirection.down);

// Add the headers.


currentSheet.getRange("A1:C1").setValues(myHeaders);
}

merge(across)
Merge the range cells into one region in the worksheet.

TypeScript

merge(across?: boolean): void;

Parameters
across boolean
Optional. Set true to merge cells in each row of the specified range as separate
merged cells. The default value is false .

Returns
void

Examples

TypeScript

/**
* This script merges a group of cells into a single region.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the active worksheet.
const selectedSheet = workbook.getActiveWorksheet();

// Merge cells A1 through A4.


const range = selectedSheet.getRange("A1:A4");
range.merge();
}
moveTo(destinationRange)
Moves cell values, formatting, and formulas from current range to the destination
range, replacing the old information in those cells. The destination range will be
expanded automatically if it is smaller than the current range. Any cells in the
destination range that are outside of the original range's area are not changed.

TypeScript

moveTo(destinationRange: Range | string): void;

Parameters
destinationRange ExcelScript.Range | string
destinationRange Specifies the range to where the information in this range will be
moved.

Returns
void

removeDuplicates(columns, includesHeader)
Removes duplicate values from the range specified by the columns.

TypeScript

removeDuplicates(
columns: number[],
includesHeader: boolean
): RemoveDuplicatesResult;

Parameters
columns number[]
The columns inside the range that may contain duplicates. At least one column
needs to be specified. Zero-indexed.

includesHeader boolean
True if the input data contains header. Default is false.
Returns
ExcelScript.RemoveDuplicatesResult

Examples

TypeScript

/**
* This script removes duplicate rows from a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range of the active worksheet.
const usedRange = workbook.getActiveWorksheet().getUsedRange();

// Remove any row that has a same value in the 0-indexed column as a
previous row.
const removedResults = usedRange.removeDuplicates([0], true);

// Log the count of removed rows.


console.log(`Rows removed: ${removedResults.getRemoved()}.`);
}

replaceAll(text, replacement, criteria)


Finds and replaces the given string based on the criteria specified within the current
range.

TypeScript

replaceAll(
text: string,
replacement: string,
criteria: ReplaceCriteria
): number;

Parameters
text string
String to find.

replacement string
The string that replaces the original string.

criteria ExcelScript.ReplaceCriteria
Additional replacement criteria.

Returns
number

Examples

TypeScript

/**
* This script searches through a table column and replaces
* cells marked "monthly special" with "parsnip".
* This script uses Range.replaceAll instead of Worksheet.replaceAll
* to limit the search to a specific range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range of a table named "Orders".
let table = workbook.getTable("Orders");
let range = table.getColumnByName("Vegetable").getRange();

// Change the value of any cells with the value "monthly special".
range.replaceAll("monthly special", "parsnip", {completeMatch: true});
}

select()
Selects the specified range in the Excel UI.

TypeScript

select(): void;

Returns
void

Examples

TypeScript

/**
* This script selects the first row of a table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
const sheet = workbook.getActiveWorksheet()
const table = sheet.getTables()[0];

// Get the first data row in the table.


const row = table.getRangeBetweenHeaderAndTotal().getRow(0);

// Select the first data row.


row.select();
}

setColumnHidden(columnHidden)
Represents if all columns in the current range are hidden. Value is true when all
columns in a range are hidden. Value is false when no columns in the range are
hidden. Value is null when some columns in a range are hidden and other columns
in the same range are not hidden.

TypeScript

setColumnHidden(columnHidden: boolean): void;

Parameters
columnHidden boolean

Returns
void

setDirty()
Set a range to be recalculated when the next recalculation occurs.

TypeScript

setDirty(): void;

Returns
void
setFormula(formula)
Sets the cell formula in A1-style notation. If the range contains multiple cells, each
cell in the given range will be updated with the input data.

TypeScript

setFormula(formula: string): void;

Parameters
formula string

Returns
void

Examples

TypeScript

/*
* This script sets a cell's formula,
* then displays how Excel stores the cell's formula and value
separately.
*/
function main(workbook: ExcelScript.Workbook) {
let selectedSheet = workbook.getActiveWorksheet();

// Set A1 to 2.
let a1 = selectedSheet.getRange("A1");
a1.setValue(2);

// Set B1 to the formula =(2*A1), which should equal 4.


let b1 = selectedSheet.getRange("B1")
b1.setFormula("=(2*A1)");

// Log the current results for `getFormula` and `getValue` at B1.


console.log(`B1 - Formula: ${b1.getFormula()} | Value:
${b1.getValue()}`);
}

setFormulaLocal(formulaLocal)
Set the cell formula in A1-style notation, in the user's language and number-
formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become
"=SUMME(A1; 1,5)" in German. If the range contains multiple cells, each cell in the
given range will be updated with the input data.

TypeScript

setFormulaLocal(formulaLocal: string): void;

Parameters
formulaLocal string

Returns
void

setFormulaR1C1(formulaR1C1)
Sets the cell formula in R1C1-style notation. If the range contains multiple cells, each
cell in the given range will be updated with the input data.

TypeScript

setFormulaR1C1(formulaR1C1: string): void;

Parameters
formulaR1C1 string

Returns
void

setFormulas(formulas)
Represents the formula in A1-style notation. If a cell has no formula, its value is
returned instead.

TypeScript

setFormulas(formulas: string[][]): void;


Parameters
formulas string[][]

Returns
void

Examples

TypeScript

/**
* This script sets the values of a range, then adds SUM formulas to
calculate
* the totals for each row of that range.
*/
function main(workbook: ExcelScript.Workbook)
{
let currentSheet = workbook.getActiveWorksheet();

// Set the values of a range.


let values = [[1, 2, 4], [8, 16, 32], [64, 128, 256]];
let valueRange = currentSheet.getRange("A1:C3");
valueRange.setValues(values);

// Set the formulas of a range.


let formulas = [["=SUM(A1:C1)"], ["=SUM(A2:C2)"], ["=SUM(A3:C3)"]];
let formulaRange = currentSheet.getRange("D1:D3");
formulaRange.setFormulas(formulas);
}

setFormulasLocal(formulasLocal)
Represents the formula in A1-style notation, in the user's language and number-
formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become
"=SUMME(A1; 1,5)" in German. If a cell has no formula, its value is returned instead.

TypeScript

setFormulasLocal(formulasLocal: string[][]): void;

Parameters
formulasLocal string[][]
Returns
void

setFormulasR1C1(formulasR1C1)
Represents the formula in R1C1-style notation. If a cell has no formula, its value is
returned instead.

TypeScript

setFormulasR1C1(formulasR1C1: string[][]): void;

Parameters
formulasR1C1 string[][]

Returns
void

setHyperlink(hyperlink)
Represents the hyperlink for the current range.

TypeScript

setHyperlink(hyperlink: RangeHyperlink): void;

Parameters
hyperlink ExcelScript.RangeHyperlink

Returns
void

Examples

TypeScript

/**
* This script inserts a hyperlink to the first cell of the last
worksheet in the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the active cell.
let cell = workbook.getActiveCell();

// Get the last worksheet in the workbook.


// Note that this might be the current sheet if there's only one
worksheet.
let lastSheet = workbook.getLastWorksheet();

// Get sheet name.


let linkedSheetName = lastSheet.getName();
console.log(`Setting hyperlink of ${cell.getAddress()} to the
${linkedSheetName} sheet's A1 cell`);

// Set the text for the hyperlink.


let value = `Click to go to: ${linkedSheetName}`;

// Create the hyperlink using that cell's value.


cell.setHyperlink({
textToDisplay: value.toString(),
screenTip: `Navigate to ${linkedSheetName}`,
documentReference: `${linkedSheetName}!A1`
});
}

setNumberFormat(numberFormat)
Sets cell Excel number format code for the given range. If the range contains
multiple cells, each cell in the given range will be updated with the input data.

TypeScript

setNumberFormat(numberFormat: string): void;

Parameters
numberFormat string

Returns
void

Examples

TypeScript
/**
* This script sets the number format in column C to show the data as a
percentage.
*/
function main(workbook: ExcelScript.Workbook) {
const selectedSheet = workbook.getActiveWorksheet();

// Set number format for column C to a percentage that rounds to the


nearest percentage point.
selectedSheet.getRange("C:C").setNumberFormat("0%");
}

setNumberFormatLocal(numberFormatLocal)
Sets cell Excel number format code for the given range, based on the language
settings of the user.​Excel does not perform any language or format coercion when
getting or setting the numberFormatLocal property. Any returned text uses the
locally-formatted strings based on the language specified in the system settings. If
the range contains multiple cells, each cell in the given range will be updated with
the input data.

TypeScript

setNumberFormatLocal(numberFormatLocal: string): void;

Parameters
numberFormatLocal string

Returns
void

Examples

TypeScript

/**
* This script sets the number format in column D to show the data as a
percentage with a decimal.
*/
function main(workbook: ExcelScript.Workbook) {
const selectedSheet = workbook.getActiveWorksheet();
// Set number format for column D to a percentage that rounds to the
nearest tenth of a percentage.
selectedSheet.getRange("D:D").setNumberFormatLocal("0.0%");
}

setNumberFormats(numberFormats)
Represents Excel's number format code for the given range.

TypeScript

setNumberFormats(numberFormats: string[][]): void;

Parameters
numberFormats string[][]

Returns
void

setNumberFormatsLocal(numberFormatsLocal)
Represents Excel's number format code for the given range, based on the language
settings of the user. Excel does not perform any language or format coercion when
getting or setting the numberFormatLocal property. Any returned text uses the
locally-formatted strings based on the language specified in the system settings.

TypeScript

setNumberFormatsLocal(numberFormatsLocal: string[][]): void;

Parameters
numberFormatsLocal string[][]

Returns
void

setPredefinedCellStyle(predefinedCellStyle)
Represents the style of the current range.

TypeScript

setPredefinedCellStyle(predefinedCellStyle: string): void;

Parameters
predefinedCellStyle string

Returns
void

setRowHidden(rowHidden)
Represents if all rows in the current range are hidden. Value is true when all rows in
a range are hidden. Value is false when no rows in the range are hidden. Value is
null when some rows in a range are hidden and other rows in the same range are

not hidden.

TypeScript

setRowHidden(rowHidden: boolean): void;

Parameters
rowHidden boolean

Returns
void

setValue(value)
Sets the raw value of the specified range. The data being set could be of type string,
number, or a boolean. null value will be ignored (not set or overwritten in Excel). If
the range contains multiple cells, each cell in the given range will be updated with
the input data.

TypeScript
setValue(value: any): void;

Parameters
value any

Returns
void

setValues(values)
Sets the raw values of the specified range. The data provided could be a string,
number, or boolean. If the provided value starts with a plus ("+"), minus ("-"), or
equal sign ("="), Excel interprets this value as a formula.

TypeScript

setValues(values: (string | number | boolean)[][]): void;

Parameters
values (string | number | boolean)[][]

Returns
void

Examples

TypeScript

/**
* This sample inserts some pre-loaded data into a range.
* It also shows how to get a range that fits the data.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the active cell.
let currentCell = workbook.getActiveCell();

// Calculate the range needed to fit the given data.


let targetRange = currentCell.getResizedRange(DATA.length - 1,
DATA[0].length - 1);
// Set range values to the data.
targetRange.setValues(DATA);

// Autofit the columns so the worksheet is readable.


targetRange.getFormat().autofitColumns();
}

/*
* This sample's data is in a static 2-dimensional array.
* You could also get the input from other ranges or sources.
* Note that each row must have the same number of columns to be valid.
*/
const DATA = [
['Date', 'Salesperson', 'Product', 'Amount']
, ['3/2/2020', 'Anne', 'Pizza', '$1400']
, ['3/2/2020', 'Mariya', 'Pizza', '$1700']
, ['3/7/2020', 'Mark', 'Sandwiches', '$1010']
, ['3/24/2020', 'Anne', 'Pizza', '$750']
, ['3/28/2020', 'Mark', 'Salads', '$510']
, ['4/17/2020', 'Laura', 'Salads', '$900']
, ['4/17/2020', 'Mariya', 'Salads', '$1600']
, ['4/28/2020', 'Laura', 'Sandwiches', '$680']
];

showCard()
Displays the card for an active cell if it has rich value content.

TypeScript

showCard(): void;

Returns
void

showGroupDetails(groupOption)
Shows the details of the row or column group.

TypeScript

showGroupDetails(groupOption: GroupOption): void;

Parameters
groupOption ExcelScript.GroupOption
Specifies whether to show the details of grouped rows or grouped columns.

Returns
void

ungroup(groupOption)
Ungroups columns and rows for an outline.

TypeScript

ungroup(groupOption: GroupOption): void;

Parameters
groupOption ExcelScript.GroupOption
Specifies how the range can be ungrouped by rows or columns.

Returns
void

unmerge()
Unmerge the range cells into separate cells.

TypeScript

unmerge(): void;

Returns
void

Examples

TypeScript

/**
* This script unmerges every used cell in the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the active worksheet.
const selectedSheet = workbook.getActiveWorksheet();

// Separate all regions into single cells in the currently used range.
const range = selectedSheet.getUsedRange();
range.unmerge();
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RangeAreas interface
Reference
Package: ExcelScript

RangeAreas represents a collection of one or more rectangular ranges in the same

worksheet.

Remarks

Examples

TypeScript

/**
* This script clears all the cells in the current worksheet that are
displaying errors.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range on the current sheet.
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// Get the RangeAreas object for each cell with a formula error.
const errorCells =
usedRange.getSpecialCells(ExcelScript.SpecialCellType.formulas,
ExcelScript.SpecialCellValueType.errors);

// If there are any error cells, clear them.


if (errorCells) {
errorCells.clear();
}
}

Methods
ノ Expand table

addConditional Adds a new conditional format to the collection at the first/top


Format(type) priority.

calculate() Calculates all cells in the RangeAreas .

clear(applyTo) Clears values, format, fill, border, and other properties on each of
the areas that comprise this RangeAreas object.

clearAllConditional Clears all conditional formats active on the current specified range.
Formats()

convertDataTypeToText() Converts all cells in the RangeAreas with data types into text.

copyFrom(sourceRange, Copies cell data or formatting from the source range or RangeAreas
copyType, skipBlanks, to the current RangeAreas . The destination RangeAreas can be a
transpose) different size than the source range or RangeAreas . The destination
will be expanded automatically if it is smaller than the source.

getAddress() Returns the RangeAreas reference in A1-style. Address value will


contain the worksheet name for each rectangular block of cells
(e.g., "Sheet1!A1:B4, Sheet1!D1:D4").

getAddressLocal() Returns the RangeAreas reference in the user locale.

getAreaCount() Returns the number of rectangular ranges that comprise this


RangeAreas object.

getAreas() Returns a collection of rectangular ranges that comprise this


RangeAreas object.

getCellCount() Returns the number of cells in the RangeAreas object, summing up


the cell counts of all of the individual rectangular ranges. Returns -1
if the cell count exceeds 2^31-1 (2,147,483,647).

getConditionalFormat(id) Returns a conditional format identified by its ID. If the conditional


format object does not exist, then this method returns undefined .

getConditionalFormats() Returns a collection of conditional formats that intersect with any


cells in this RangeAreas object.

getDataValidation() Returns a data validation object for all ranges in the RangeAreas .

getEntireColumn() Returns a RangeAreas object that represents the entire columns of


the RangeAreas (for example, if the current RangeAreas represents
cells "B4:E11, H2", it returns a RangeAreas that represents columns
"B:E, H:H").

getEntireRow() Returns a RangeAreas object that represents the entire rows of the
RangeAreas (for example, if the current RangeAreas represents cells
"B4:E11", it returns a RangeAreas that represents rows "4:11").

getFormat() Returns a RangeFormat object, encapsulating the font, fill, borders,


alignment, and other properties for all ranges in the RangeAreas
object.

getIntersection(another Returns the RangeAreas object that represents the intersection of


Range) the given ranges or RangeAreas . If no intersection is found, then
this method returns undefined .

getIsEntireColumn() Specifies if all the ranges on this RangeAreas object represent entire
columns (e.g., "A:C, Q:Z").

getIsEntireRow() Specifies if all the ranges on this RangeAreas object represent entire
rows (e.g., "1:3, 5:7").

getOffsetRangeAreas(row Returns a RangeAreas object that is shifted by the specific row and
Offset, columnOffset) column offset. The dimension of the returned RangeAreas will
match the original object. If the resulting RangeAreas is forced
outside the bounds of the worksheet grid, an error will be thrown.

getPredefinedCellStyle() Represents the style for all ranges in this RangeAreas object. If the
styles of the cells are inconsistent, null will be returned. For
custom styles, the style name will be returned. For built-in styles, a
string representing a value in the BuiltInStyle enum will be
returned.

getSpecialCells(cellType, Returns a RangeAreas object that represents all the cells that match
cellValueType) the specified type and value. If no special cells are found that
match the criteria, then this method returns undefined .

getTables(fullyContained) Returns a scoped collection of tables that overlap with any range in
this RangeAreas object.

getUsedRangeAreas(values Returns the used RangeAreas that comprises all the used areas of
Only) individual rectangular ranges in the RangeAreas object. If there are
no used cells within the RangeAreas , then this method returns
undefined .

getWorksheet() Returns the worksheet for the current RangeAreas .

setDirty() Sets the RangeAreas to be recalculated when the next recalculation


occurs.

setPredefinedCell Represents the style for all ranges in this RangeAreas object. If the
Style(predefinedCellStyle) styles of the cells are inconsistent, null will be returned. For
custom styles, the style name will be returned. For built-in styles, a
string representing a value in the BuiltInStyle enum will be
returned.

Method Details

addConditionalFormat(type)
Adds a new conditional format to the collection at the first/top priority.
TypeScript

addConditionalFormat(type: ConditionalFormatType): ConditionalFormat;

Parameters
type ExcelScript.ConditionalFormatType
The type of conditional format being added. See ExcelScript.ConditionalFormatType
for details.

Returns
ExcelScript.ConditionalFormat

calculate()
Calculates all cells in the RangeAreas .

TypeScript

calculate(): void;

Returns
void

clear(applyTo)
Clears values, format, fill, border, and other properties on each of the areas that
comprise this RangeAreas object.

TypeScript

clear(applyTo?: ClearApplyTo): void;

Parameters
applyTo ExcelScript.ClearApplyTo
Optional. Determines the type of clear action. See ExcelScript.ClearApplyTo for
details. Default is "All".
Returns
void

Examples

TypeScript

/**
* This script clears all the cells in the current worksheet that are
displaying errors.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range on the current sheet.
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// Get the RangeAreas object for each cell with a formula error.
const errorCells =
usedRange.getSpecialCells(ExcelScript.SpecialCellType.formulas,
ExcelScript.SpecialCellValueType.errors);

// If there are any error cells, clear them.


if (errorCells) {
errorCells.clear();
}
}

clearAllConditionalFormats()
Clears all conditional formats active on the current specified range.

TypeScript

clearAllConditionalFormats(): void;

Returns
void

convertDataTypeToText()
Converts all cells in the RangeAreas with data types into text.

TypeScript
convertDataTypeToText(): void;

Returns
void

copyFrom(sourceRange, copyType, skipBlanks, transpose)


Copies cell data or formatting from the source range or RangeAreas to the current
RangeAreas . The destination RangeAreas can be a different size than the source range

or RangeAreas . The destination will be expanded automatically if it is smaller than the


source.

TypeScript

copyFrom(
sourceRange: Range | RangeAreas | string,
copyType?: RangeCopyType,
skipBlanks?: boolean,
transpose?: boolean
): void;

Parameters
sourceRange ExcelScript.Range | ExcelScript.RangeAreas | string
The source range or RangeAreas to copy from. When the source RangeAreas has
multiple ranges, their form must able to be created by removing full rows or columns
from a rectangular range.

copyType ExcelScript.RangeCopyType
The type of cell data or formatting to copy over. Default is "All".

skipBlanks boolean
True if to skip blank cells in the source range or RangeAreas . Default is false.

transpose boolean
True if to transpose the cells in the destination RangeAreas . Default is false.

Returns
void
getAddress()
Returns the RangeAreas reference in A1-style. Address value will contain the
worksheet name for each rectangular block of cells (e.g., "Sheet1!A1:B4,
Sheet1!D1:D4").

TypeScript

getAddress(): string;

Returns
string

getAddressLocal()
Returns the RangeAreas reference in the user locale.

TypeScript

getAddressLocal(): string;

Returns
string

getAreaCount()
Returns the number of rectangular ranges that comprise this RangeAreas object.

TypeScript

getAreaCount(): number;

Returns
number

getAreas()
Returns a collection of rectangular ranges that comprise this RangeAreas object.
TypeScript

getAreas(): Range[];

Returns
ExcelScript.Range[]

getCellCount()
Returns the number of cells in the RangeAreas object, summing up the cell counts of
all of the individual rectangular ranges. Returns -1 if the cell count exceeds 2^31-1
(2,147,483,647).

TypeScript

getCellCount(): number;

Returns
number

getConditionalFormat(id)
Returns a conditional format identified by its ID. If the conditional format object does
not exist, then this method returns undefined .

TypeScript

getConditionalFormat(id: string): ConditionalFormat | undefined;

Parameters
id string
The ID of the conditional format.

Returns
ExcelScript.ConditionalFormat | undefined
getConditionalFormats()
Returns a collection of conditional formats that intersect with any cells in this
RangeAreas object.

TypeScript

getConditionalFormats(): ConditionalFormat[];

Returns
ExcelScript.ConditionalFormat[]

getDataValidation()
Returns a data validation object for all ranges in the RangeAreas .

TypeScript

getDataValidation(): DataValidation;

Returns
ExcelScript.DataValidation

getEntireColumn()
Returns a RangeAreas object that represents the entire columns of the RangeAreas
(for example, if the current RangeAreas represents cells "B4:E11, H2", it returns a
RangeAreas that represents columns "B:E, H:H").

TypeScript

getEntireColumn(): RangeAreas;

Returns
ExcelScript.RangeAreas

getEntireRow()
Returns a RangeAreas object that represents the entire rows of the RangeAreas (for
example, if the current RangeAreas represents cells "B4:E11", it returns a RangeAreas
that represents rows "4:11").

TypeScript

getEntireRow(): RangeAreas;

Returns
ExcelScript.RangeAreas

getFormat()
Returns a RangeFormat object, encapsulating the font, fill, borders, alignment, and
other properties for all ranges in the RangeAreas object.

TypeScript

getFormat(): RangeFormat;

Returns
ExcelScript.RangeFormat

Examples

TypeScript

/**
* This script finds and highlights all the cells in the current
worksheet that contain a formula.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range on the current sheet.
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// Get the RangeAreas object for each cell with a formula.


const formulaCells =
usedRange.getSpecialCells(ExcelScript.SpecialCellType.formulas);

// Add a light blue background to the cells containing formulas.


formulaCells.getFormat().getFill().setColor("#ADD8E6");
}

getIntersection(anotherRange)
Returns the RangeAreas object that represents the intersection of the given ranges or
RangeAreas . If no intersection is found, then this method returns undefined .

TypeScript

getIntersection(anotherRange: Range | RangeAreas | string): RangeAreas;

Parameters
anotherRange ExcelScript.Range | ExcelScript.RangeAreas | string
The range, RangeAreas object, or address that will be used to determine the
intersection.

Returns
ExcelScript.RangeAreas

getIsEntireColumn()
Specifies if all the ranges on this RangeAreas object represent entire columns (e.g.,
"A:C, Q:Z").

TypeScript

getIsEntireColumn(): boolean;

Returns
boolean

getIsEntireRow()
Specifies if all the ranges on this RangeAreas object represent entire rows (e.g., "1:3,
5:7").

TypeScript
getIsEntireRow(): boolean;

Returns
boolean

getOffsetRangeAreas(rowOffset, columnOffset)
Returns a RangeAreas object that is shifted by the specific row and column offset.
The dimension of the returned RangeAreas will match the original object. If the
resulting RangeAreas is forced outside the bounds of the worksheet grid, an error will
be thrown.

TypeScript

getOffsetRangeAreas(
rowOffset: number,
columnOffset: number
): RangeAreas;

Parameters
rowOffset number
The number of rows (positive, negative, or 0) by which the RangeAreas is to be offset.
Positive values are offset downward, and negative values are offset upward.

columnOffset number
The number of columns (positive, negative, or 0) by which the RangeAreas is to be
offset. Positive values are offset to the right, and negative values are offset to the left.

Returns
ExcelScript.RangeAreas

getPredefinedCellStyle()
Represents the style for all ranges in this RangeAreas object. If the styles of the cells
are inconsistent, null will be returned. For custom styles, the style name will be
returned. For built-in styles, a string representing a value in the BuiltInStyle enum
will be returned.
TypeScript

getPredefinedCellStyle(): string;

Returns
string

getSpecialCells(cellType, cellValueType)
Returns a RangeAreas object that represents all the cells that match the specified
type and value. If no special cells are found that match the criteria, then this method
returns undefined .

TypeScript

getSpecialCells(
cellType: SpecialCellType,
cellValueType?: SpecialCellValueType
): RangeAreas;

Parameters
cellType ExcelScript.SpecialCellType
The type of cells to include.

cellValueType ExcelScript.SpecialCellValueType
If cellType is either constants or formulas , this argument is used to determine
which types of cells to include in the result. These values can be combined together
to return more than one type. The default is to select all constants or formulas, no
matter what the type.

Returns
ExcelScript.RangeAreas

getTables(fullyContained)
Returns a scoped collection of tables that overlap with any range in this RangeAreas
object.
TypeScript

getTables(fullyContained?: boolean): Table[];

Parameters
fullyContained boolean
If true , returns only tables that are fully contained within the range bounds. Default
is false .

Returns
ExcelScript.Table[]

getUsedRangeAreas(valuesOnly)
Returns the used RangeAreas that comprises all the used areas of individual
rectangular ranges in the RangeAreas object. If there are no used cells within the
RangeAreas , then this method returns undefined .

TypeScript

getUsedRangeAreas(valuesOnly?: boolean): RangeAreas;

Parameters
valuesOnly boolean
Whether to only consider cells with values as used cells.

Returns
ExcelScript.RangeAreas

getWorksheet()
Returns the worksheet for the current RangeAreas .

TypeScript

getWorksheet(): Worksheet;
Returns
ExcelScript.Worksheet

setDirty()
Sets the RangeAreas to be recalculated when the next recalculation occurs.

TypeScript

setDirty(): void;

Returns
void

setPredefinedCellStyle(predefinedCellStyle)
Represents the style for all ranges in this RangeAreas object. If the styles of the cells
are inconsistent, null will be returned. For custom styles, the style name will be
returned. For built-in styles, a string representing a value in the BuiltInStyle enum
will be returned.

TypeScript

setPredefinedCellStyle(predefinedCellStyle: string): void;

Parameters
predefinedCellStyle string

Returns
void

Examples

TypeScript

/**
* This script sets the cell style to "warning text"
* on every cell with a formula error.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range in the current worksheet.
const sheet = workbook.getActiveWorksheet();
const usedRange = sheet.getUsedRange();

// Get any cells that are displaying errors.


const errorCells = usedRange.getSpecialCells(
ExcelScript.SpecialCellType.formulas,
ExcelScript.SpecialCellValueType.errors
);

// Check if there are error cells before proceeding.


if (errorCells) {
// Use the built-in warning text style on the error cells.
errorCells.setPredefinedCellStyle(
ExcelScript.BuiltInStyle.warningText.toString()
);
} else {
console.log("No formula errors in the worksheet.");
}
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RangeBorder interface
Reference
Package: ExcelScript

Represents the border of an object.

Methods
ノ Expand table

getColor() HTML color code representing the color of the border line, in the form
#RRGGBB (e.g., "FFA500"), or as a named HTML color (e.g., "orange").

getSideIndex() Constant value that indicates the specific side of the border. See
ExcelScript.BorderIndex for details.

getStyle() One of the constants of line style specifying the line style for the border. See
ExcelScript.BorderLineStyle for details.

getTintAndShade() Specifies a double that lightens or darkens a color for the range border, the
value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
A null value indicates that the border doesn't have a uniform tintAndShade
setting.

getWeight() Specifies the weight of the border around a range. See


ExcelScript.BorderWeight for details.

setColor(color) HTML color code representing the color of the border line, in the form
#RRGGBB (e.g., "FFA500"), or as a named HTML color (e.g., "orange").

setStyle(style) One of the constants of line style specifying the line style for the border. See
ExcelScript.BorderLineStyle for details.

setTintAnd Specifies a double that lightens or darkens a color for the range border, the
Shade(tintAnd value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
Shade) A null value indicates that the border doesn't have a uniform tintAndShade
setting.

setWeight(weight) Specifies the weight of the border around a range. See


ExcelScript.BorderWeight for details.

Method Details

getColor()
HTML color code representing the color of the border line, in the form #RRGGBB
(e.g., "FFA500"), or as a named HTML color (e.g., "orange").

TypeScript

getColor(): string;

Returns
string

getSideIndex()
Constant value that indicates the specific side of the border. See
ExcelScript.BorderIndex for details.

TypeScript

getSideIndex(): BorderIndex;

Returns
ExcelScript.BorderIndex

getStyle()
One of the constants of line style specifying the line style for the border. See
ExcelScript.BorderLineStyle for details.

TypeScript

getStyle(): BorderLineStyle;

Returns
ExcelScript.BorderLineStyle

getTintAndShade()
Specifies a double that lightens or darkens a color for the range border, the value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the border doesn't have a uniform tintAndShade setting.

TypeScript

getTintAndShade(): number;

Returns
number

getWeight()
Specifies the weight of the border around a range. See ExcelScript.BorderWeight for
details.

TypeScript

getWeight(): BorderWeight;

Returns
ExcelScript.BorderWeight

setColor(color)
HTML color code representing the color of the border line, in the form #RRGGBB
(e.g., "FFA500"), or as a named HTML color (e.g., "orange").

TypeScript

setColor(color: string): void;

Parameters
color string

Returns
void

setStyle(style)
One of the constants of line style specifying the line style for the border. See
ExcelScript.BorderLineStyle for details.

TypeScript

setStyle(style: BorderLineStyle): void;

Parameters
style ExcelScript.BorderLineStyle

Returns
void

Examples

TypeScript

/**
* This script adds a border around the outside of a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get a range from the current worksheet.
let range = workbook.getActiveWorksheet().getRange("B2:E15");

// Add a border around the whole bounding range.


let format = range.getFormat();

format.getRangeBorder(ExcelScript.BorderIndex.edgeTop).setStyle(ExcelScri
pt.BorderLineStyle.continuous); // Top border

format.getRangeBorder(ExcelScript.BorderIndex.edgeBottom).setStyle(ExcelS
cript.BorderLineStyle.continuous); // Bottom border

format.getRangeBorder(ExcelScript.BorderIndex.edgeLeft).setStyle(ExcelScr
ipt.BorderLineStyle.continuous); // Left border

format.getRangeBorder(ExcelScript.BorderIndex.edgeRight).setStyle(ExcelSc
ript.BorderLineStyle.continuous); // Right border
}

setTintAndShade(tintAndShade)
Specifies a double that lightens or darkens a color for the range border, the value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the border doesn't have a uniform tintAndShade setting.

TypeScript

setTintAndShade(tintAndShade: number): void;

Parameters
tintAndShade number

Returns
void

setWeight(weight)
Specifies the weight of the border around a range. See ExcelScript.BorderWeight for
details.

TypeScript

setWeight(weight: BorderWeight): void;

Parameters
weight ExcelScript.BorderWeight

Returns
void

Examples

TypeScript

/**
* This script creates a border around a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the RangeFormat object for the range "B2:G10".
const currentSheet = workbook.getActiveWorksheet();
const rangeForBorder = currentSheet.getRange("B2:G10");
const format = rangeForBorder.getFormat();
// Get a RangeBorder object for each edge of the range and set the
border properties.
let edgeTop = format.getRangeBorder(ExcelScript.BorderIndex.edgeTop);
edgeTop.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeTop.setWeight(ExcelScript.BorderWeight.thick);

let edgeBottom =
format.getRangeBorder(ExcelScript.BorderIndex.edgeBottom);
edgeBottom.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeBottom.setWeight(ExcelScript.BorderWeight.thick);

let edgeLeft = format.getRangeBorder(ExcelScript.BorderIndex.edgeLeft);


edgeLeft.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeLeft.setWeight(ExcelScript.BorderWeight.thick);

let edgeRight =
format.getRangeBorder(ExcelScript.BorderIndex.edgeRight);
edgeRight.setStyle(ExcelScript.BorderLineStyle.dashDot);
edgeRight.setWeight(ExcelScript.BorderWeight.thick);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RangeFill interface
Reference
Package: ExcelScript

Represents the background of a range object.

Remarks

Examples

TypeScript

/**
* This script sets the fill color of the used range to green.
*/
function main(workbook: ExcelScript.Workbook)
{
// Get the used range of the current worksheet.
let currentSheet = workbook.getActiveWorksheet();
let usedRange = currentSheet.getUsedRange();

// Get the RangeFill object.


let fill = usedRange.getFormat().getFill();

// Set the fill color to green.


fill.setColor("green");
}

Methods
ノ Expand table

clear() Resets the range background.

getColor() HTML color code representing the color of the background, in the form
#RRGGBB (e.g., "FFA500"), or as a named HTML color (e.g., "orange")

getPattern() The pattern of a range. See ExcelScript.FillPattern for details.


LinearGradient and RectangularGradient are not supported. A null value
indicates that the entire range doesn't have a uniform pattern setting.

getPatternColor() The HTML color code representing the color of the range pattern, in the
form #RRGGBB (e.g., "FFA500"), or as a named HTML color (e.g.,
"orange").

getPatternTintAnd Specifies a double that lightens or darkens a pattern color for the range
Shade() fill. The value is between -1 (darkest) and 1 (brightest), with 0 for the
original color. A null value indicates that the range doesn't have
uniform patternTintAndShade settings.

getTintAndShade() Specifies a double that lightens or darkens a color for the range fill. The
value is between -1 (darkest) and 1 (brightest), with 0 for the original
color. A null value indicates that the range doesn't have uniform
tintAndShade settings.

setColor(color) HTML color code representing the color of the background, in the form
#RRGGBB (e.g., "FFA500"), or as a named HTML color (e.g., "orange")

setPattern(pattern) The pattern of a range. See ExcelScript.FillPattern for details.


LinearGradient and RectangularGradient are not supported. A null value
indicates that the entire range doesn't have a uniform pattern setting.

setPattern The HTML color code representing the color of the range pattern, in the
Color(patternColor) form #RRGGBB (e.g., "FFA500"), or as a named HTML color (e.g.,
"orange").

setPatternTintAnd Specifies a double that lightens or darkens a pattern color for the range
Shade(patternTintAnd fill. The value is between -1 (darkest) and 1 (brightest), with 0 for the
Shade) original color. A null value indicates that the range doesn't have
uniform patternTintAndShade settings.

setTintAndShade(tint Specifies a double that lightens or darkens a color for the range fill. The
AndShade) value is between -1 (darkest) and 1 (brightest), with 0 for the original
color. A null value indicates that the range doesn't have uniform
tintAndShade settings.

Method Details

clear()
Resets the range background.

TypeScript

clear(): void;

Returns
void
Examples

TypeScript

/**
* This script removes all fill color and styles from the used range.
*/
function main(workbook: ExcelScript.Workbook)
{
// Get the used range of the current worksheet.
let currentSheet = workbook.getActiveWorksheet();
let usedRange = currentSheet.getUsedRange();

// Clear the fill from the entire range.


usedRange.getFormat().getFill().clear();
}

getColor()
HTML color code representing the color of the background, in the form #RRGGBB
(e.g., "FFA500"), or as a named HTML color (e.g., "orange")

TypeScript

getColor(): string;

Returns
string

getPattern()
The pattern of a range. See ExcelScript.FillPattern for details. LinearGradient and
RectangularGradient are not supported. A null value indicates that the entire range
doesn't have a uniform pattern setting.

TypeScript

getPattern(): FillPattern;

Returns
ExcelScript.FillPattern
getPatternColor()
The HTML color code representing the color of the range pattern, in the form
#RRGGBB (e.g., "FFA500"), or as a named HTML color (e.g., "orange").

TypeScript

getPatternColor(): string;

Returns
string

getPatternTintAndShade()
Specifies a double that lightens or darkens a pattern color for the range fill. The
value is between -1 (darkest) and 1 (brightest), with 0 for the original color. A null
value indicates that the range doesn't have uniform patternTintAndShade settings.

TypeScript

getPatternTintAndShade(): number;

Returns
number

getTintAndShade()
Specifies a double that lightens or darkens a color for the range fill. The value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the range doesn't have uniform tintAndShade settings.

TypeScript

getTintAndShade(): number;

Returns
number
setColor(color)
HTML color code representing the color of the background, in the form #RRGGBB
(e.g., "FFA500"), or as a named HTML color (e.g., "orange")

TypeScript

setColor(color: string): void;

Parameters
color string

Returns
void

Examples

TypeScript

/**
* This script sets the fill color of cell A2 to blue.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range representing cell A2 from the current worksheet.
let cell = workbook.getActiveWorksheet().getRange("A2");

// Set the fill color to blue.


cell.getFormat().getFill().setColor("blue");
}

setPattern(pattern)
The pattern of a range. See ExcelScript.FillPattern for details. LinearGradient and
RectangularGradient are not supported. A null value indicates that the entire range
doesn't have a uniform pattern setting.

TypeScript

setPattern(pattern: FillPattern): void;


Parameters
pattern ExcelScript.FillPattern

Returns
void

Examples

TypeScript

/**
* This script sets a black-checkered fill on the selected range.
*/
function main(workbook: ExcelScript.Workbook) {
const selected = workbook.getSelectedRange();

selected.getFormat().getFill().setPattern(ExcelScript.FillPattern.checker
);
selected.getFormat().getFill().setPatternColor("black");
}

setPatternColor(patternColor)
The HTML color code representing the color of the range pattern, in the form
#RRGGBB (e.g., "FFA500"), or as a named HTML color (e.g., "orange").

TypeScript

setPatternColor(patternColor: string): void;

Parameters
patternColor string

Returns
void

setPatternTintAndShade(patternTintAndShade)
Specifies a double that lightens or darkens a pattern color for the range fill. The
value is between -1 (darkest) and 1 (brightest), with 0 for the original color. A null
value indicates that the range doesn't have uniform patternTintAndShade settings.

TypeScript

setPatternTintAndShade(patternTintAndShade: number): void;

Parameters
patternTintAndShade number

Returns
void

setTintAndShade(tintAndShade)
Specifies a double that lightens or darkens a color for the range fill. The value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the range doesn't have uniform tintAndShade settings.

TypeScript

setTintAndShade(tintAndShade: number): void;

Parameters
tintAndShade number

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.RangeFont interface
Reference
Package: ExcelScript

This object represents the font attributes (font name, font size, color, etc.) for an object.

Remarks

Examples

TypeScript

/**
* This script sets the font of A1 to Arial, size 16.
*/
function main(workbook: ExcelScript.Workbook) {
// Get A1 on the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0,0);

// Adjust the font settings for that cell.


const cellFont = cell.getFormat().getFont();
cellFont.setName("Arial");
cellFont.setSize(16);
}

Methods
ノ Expand table

getBold() Represents the bold status of the font.

getColor() HTML color code representation of the text color (e.g., #FF0000
represents Red).

getItalic() Specifies the italic status of the font.

getName() Font name (e.g., "Calibri"). The name's length should not be
greater than 31 characters.

getSize() Font size.

getStrikethrough() Specifies the strikethrough status of font. A null value indicates


that the entire range doesn't have a uniform strikethrough setting.
getSubscript() Specifies the subscript status of font. Returns true if all the fonts
of the range are subscript. Returns false if all the fonts of the
range are superscript or normal (neither superscript, nor
subscript). Returns null otherwise.

getSuperscript() Specifies the superscript status of font. Returns true if all the
fonts of the range are superscript. Returns false if all the fonts of
the range are subscript or normal (neither superscript, nor
subscript). Returns null otherwise.

getTintAndShade() Specifies a double that lightens or darkens a color for the range
font. The value is between -1 (darkest) and 1 (brightest), with 0 for
the original color. A null value indicates that the entire range
doesn't have a uniform font tintAndShade setting.

getUnderline() Type of underline applied to the font. See


ExcelScript.RangeUnderlineStyle for details.

setBold(bold) Represents the bold status of the font.

setColor(color) HTML color code representation of the text color (e.g., #FF0000
represents Red).

setItalic(italic) Specifies the italic status of the font.

setName(name) Font name (e.g., "Calibri"). The name's length should not be
greater than 31 characters.

setSize(size) Font size.

set Specifies the strikethrough status of font. A null value indicates


Strikethrough(strikethrough) that the entire range doesn't have a uniform strikethrough setting.

setSubscript(subscript) Specifies the subscript status of font. Returns true if all the fonts
of the range are subscript. Returns false if all the fonts of the
range are superscript or normal (neither superscript, nor
subscript). Returns null otherwise.

setSuperscript(superscript) Specifies the superscript status of font. Returns true if all the
fonts of the range are superscript. Returns false if all the fonts of
the range are subscript or normal (neither superscript, nor
subscript). Returns null otherwise.

setTintAndShade(tintAnd Specifies a double that lightens or darkens a color for the range
Shade) font. The value is between -1 (darkest) and 1 (brightest), with 0 for
the original color. A null value indicates that the entire range
doesn't have a uniform font tintAndShade setting.

setUnderline(underline) Type of underline applied to the font. See


ExcelScript.RangeUnderlineStyle for details.
Method Details

getBold()
Represents the bold status of the font.

TypeScript

getBold(): boolean;

Returns
boolean

getColor()
HTML color code representation of the text color (e.g., #FF0000 represents Red).

TypeScript

getColor(): string;

Returns
string

getItalic()
Specifies the italic status of the font.

TypeScript

getItalic(): boolean;

Returns
boolean

getName()
Font name (e.g., "Calibri"). The name's length should not be greater than 31
characters.

TypeScript

getName(): string;

Returns
string

getSize()
Font size.

TypeScript

getSize(): number;

Returns
number

getStrikethrough()
Specifies the strikethrough status of font. A null value indicates that the entire
range doesn't have a uniform strikethrough setting.

TypeScript

getStrikethrough(): boolean;

Returns
boolean

getSubscript()
Specifies the subscript status of font. Returns true if all the fonts of the range are
subscript. Returns false if all the fonts of the range are superscript or normal
(neither superscript, nor subscript). Returns null otherwise.
TypeScript

getSubscript(): boolean;

Returns
boolean

getSuperscript()
Specifies the superscript status of font. Returns true if all the fonts of the range are
superscript. Returns false if all the fonts of the range are subscript or normal
(neither superscript, nor subscript). Returns null otherwise.

TypeScript

getSuperscript(): boolean;

Returns
boolean

getTintAndShade()
Specifies a double that lightens or darkens a color for the range font. The value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the entire range doesn't have a uniform font tintAndShade setting.

TypeScript

getTintAndShade(): number;

Returns
number

getUnderline()
Type of underline applied to the font. See ExcelScript.RangeUnderlineStyle for
details.
TypeScript

getUnderline(): RangeUnderlineStyle;

Returns
ExcelScript.RangeUnderlineStyle

setBold(bold)
Represents the bold status of the font.

TypeScript

setBold(bold: boolean): void;

Parameters
bold boolean

Returns
void

Examples

TypeScript

/**
* This script bolds the text of cell A1.
*/
function main(workbook: ExcelScript.Workbook) {
// Get A1 on the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0,0);

// Bold the font for that cell


cell.getFormat().getFont().setBold(true);
}

setColor(color)
HTML color code representation of the text color (e.g., #FF0000 represents Red).
TypeScript

setColor(color: string): void;

Parameters
color string

Returns
void

setItalic(italic)
Specifies the italic status of the font.

TypeScript

setItalic(italic: boolean): void;

Parameters
italic boolean

Returns
void

setName(name)
Font name (e.g., "Calibri"). The name's length should not be greater than 31
characters.

TypeScript

setName(name: string): void;

Parameters
name string
Returns
void

Examples

TypeScript

/**
* This script sets the font style of A1 to Arial.
*/
function main(workbook: ExcelScript.Workbook) {
// Get A1 on the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0,0);

// Adjust the font settings for that cell.


cell.getFormat().getFont().setName("Arial");
}

setSize(size)
Font size.

TypeScript

setSize(size: number): void;

Parameters
size number

Returns
void

Examples

TypeScript

/**
* This script sets the font size of A1 to 16.
*/
function main(workbook: ExcelScript.Workbook) {
// Get A1 on the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0,0);
// Adjust the font settings for that cell.clear
cell.getFormat().getFont().setSize(16);
}

setStrikethrough(strikethrough)
Specifies the strikethrough status of font. A null value indicates that the entire
range doesn't have a uniform strikethrough setting.

TypeScript

setStrikethrough(strikethrough: boolean): void;

Parameters
strikethrough boolean

Returns
void

setSubscript(subscript)
Specifies the subscript status of font. Returns true if all the fonts of the range are
subscript. Returns false if all the fonts of the range are superscript or normal
(neither superscript, nor subscript). Returns null otherwise.

TypeScript

setSubscript(subscript: boolean): void;

Parameters
subscript boolean

Returns
void

setSuperscript(superscript)
Specifies the superscript status of font. Returns true if all the fonts of the range are
superscript. Returns false if all the fonts of the range are subscript or normal
(neither superscript, nor subscript). Returns null otherwise.

TypeScript

setSuperscript(superscript: boolean): void;

Parameters
superscript boolean

Returns
void

setTintAndShade(tintAndShade)
Specifies a double that lightens or darkens a color for the range font. The value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the entire range doesn't have a uniform font tintAndShade setting.

TypeScript

setTintAndShade(tintAndShade: number): void;

Parameters
tintAndShade number

Returns
void

setUnderline(underline)
Type of underline applied to the font. See ExcelScript.RangeUnderlineStyle for
details.

TypeScript
setUnderline(underline: RangeUnderlineStyle): void;

Parameters
underline ExcelScript.RangeUnderlineStyle

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RangeFormat interface
Reference
Package: ExcelScript

A format object encapsulating the range's font, fill, borders, alignment, and other
properties.

Remarks

Examples

TypeScript

/**
* This script applies some simple formatting to the top row of the used
range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the top row of the used range in the current worksheet.
const selectedSheet = workbook.getActiveWorksheet();
const topRow = selectedSheet.getUsedRange().getRow(0);

// For the top row, set the fill to black, the font color to white, and
the font to be bold.
const format: ExcelScript.RangeFormat = topRow.getFormat();
format.getFill().setColor("black");
format.getFont().setColor("white");
format.getFont().setBold(true);
}

Methods
ノ Expand table

adjustIndent(amount) Adjusts the indentation of the range formatting. The indent value
ranges from 0 to 250 and is measured in characters.

autofitColumns() Changes the width of the columns of the current range to achieve the
best fit, based on the current data in the columns.

autofitRows() Changes the height of the rows of the current range to achieve the
best fit, based on the current data in the columns.
getAutoIndent() Specifies if text is automatically indented when text alignment is set
to equal distribution.

getBorders() Collection of border objects that apply to the overall range.

getColumnWidth() Specifies the width of all columns within the range. If the column
widths are not uniform, null will be returned.

getFill() Returns the fill object defined on the overall range.

getFont() Returns the font object defined on the overall range.

getHorizontalAlignment() Represents the horizontal alignment for the specified object. See
ExcelScript.HorizontalAlignment for details.

getIndentLevel() An integer from 0 to 250 that indicates the indent level.

getProtection() Returns the format protection object for a range.

getRangeBorder(index) Gets a border object using its name.

getRangeBorderTintAnd Specifies a double that lightens or darkens a color for range borders.
Shade() The value is between -1 (darkest) and 1 (brightest), with 0 for the
original color. A null value indicates that the entire border collection
doesn't have a uniform tintAndShade setting.

getReadingOrder() The reading order for the range.

getRowHeight() The height of all rows in the range. If the row heights are not uniform,
null will be returned.

getShrinkToFit() Specifies if text automatically shrinks to fit in the available column


width.

getTextOrientation() The text orientation of all the cells within the range. The text
orientation should be an integer either from -90 to 90, or 180 for
vertically-oriented text. If the orientation within a range are not
uniform, then null will be returned.

getUseStandardHeight() Determines if the row height of the Range object equals the standard
height of the sheet. Returns true if the row height of the Range
object equals the standard height of the sheet. Returns null if the
range contains more than one row and the rows aren't all the same
height. Returns false otherwise.

getUseStandardWidth() Specifies if the column width of the Range object equals the standard
width of the sheet. Returns true if the column width of the Range
object equals the standard width of the sheet. Returns null if the
range contains more than one column and the columns aren't all the
same height. Returns false otherwise.
getVerticalAlignment() Represents the vertical alignment for the specified object. See
ExcelScript.VerticalAlignment for details.

getWrapText() Specifies if Excel wraps the text in the object. A null value indicates
that the entire range doesn't have a uniform wrap setting

setAutoIndent(auto Specifies if text is automatically indented when text alignment is set


Indent) to equal distribution.

setColumnWidth(column Specifies the width of all columns within the range.


Width)

setHorizontal Represents the horizontal alignment for the specified object. See
Alignment(horizontal ExcelScript.HorizontalAlignment for details.
Alignment)

setIndentLevel(indent An integer from 0 to 250 that indicates the indent level.


Level)

setRangeBorderTintAnd Specifies a double that lightens or darkens a color for range borders.
Shade(rangeBorderTint The value is between -1 (darkest) and 1 (brightest), with 0 for the
AndShade) original color. A null value indicates that the entire border collection
doesn't have a uniform tintAndShade setting.

setReadingOrder(reading The reading order for the range.


Order)

setRowHeight(rowHeight) Specifies the height of all rows in the range.

setShrinkToFit(shrink Specifies if text automatically shrinks to fit in the available column


ToFit) width.

setTextOrientation(text The text orientation of all the cells within the range. The text
Orientation) orientation should be an integer either from -90 to 90, or 180 for
vertically-oriented text. If the orientation within a range are not
uniform, then null will be returned.

setUseStandard Determines if the row height of the Range object equals the standard
Height(useStandard height of the sheet. Note: This property is only intended to be set to
Height) true . Setting it to false has no effect.

setUseStandardWidth(use Specifies if the column width of the Range object equals the standard
StandardWidth) width of the sheet. Note: This property is only intended to be set to
true . Setting it to false has no effect.

setVertical Represents the vertical alignment for the specified object. See
Alignment(vertical ExcelScript.VerticalAlignment for details.
Alignment)

setWrapText(wrapText) Specifies if Excel wraps the text in the object. A null value indicates
that the entire range doesn't have a uniform wrap setting
Method Details

adjustIndent(amount)
Adjusts the indentation of the range formatting. The indent value ranges from 0 to
250 and is measured in characters.

TypeScript

adjustIndent(amount: number): void;

Parameters
amount number
The number of character spaces by which the current indent is adjusted. This value
should be between -250 and 250. Note: If the amount would raise the indent level
above 250, the indent level stays with 250. Similarly, if the amount would lower the
indent level below 0, the indent level stays 0.

Returns
void

Examples

TypeScript

/**
* This script adjusts the indentation of a specific table column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the current worksheet.
const selectedSheet = workbook.getActiveWorksheet();
const table = selectedSheet.getTables()[0];

// Get the data range of the second column.


const secondColumn = table.getColumn(2);
const data = secondColumn.getRangeBetweenHeaderAndTotal();

// Add an indentation of 1 character space to the data range.


data.getFormat().adjustIndent(1);
}
autofitColumns()
Changes the width of the columns of the current range to achieve the best fit, based
on the current data in the columns.

TypeScript

autofitColumns(): void;

Returns
void

Examples

TypeScript

/**
* This script creates a new table from existing data and autofits the
columns.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// Create the table.


const table = currentSheet.addTable(usedRange, true);

// Format the table columns.


table.getRange().getFormat().autofitColumns();
}

autofitRows()
Changes the height of the rows of the current range to achieve the best fit, based on
the current data in the columns.

TypeScript

autofitRows(): void;

Returns
void
Examples

TypeScript

/**
* This script creates a new table from existing data and autofits the
rows.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// Create the table.


const table = currentSheet.addTable(usedRange, true);

// Format the table rows.


table.getRange().getFormat().autofitRows();
}

getAutoIndent()
Specifies if text is automatically indented when text alignment is set to equal
distribution.

TypeScript

getAutoIndent(): boolean;

Returns
boolean

getBorders()
Collection of border objects that apply to the overall range.

TypeScript

getBorders(): RangeBorder[];

Returns
ExcelScript.RangeBorder[]
getColumnWidth()
Specifies the width of all columns within the range. If the column widths are not
uniform, null will be returned.

TypeScript

getColumnWidth(): number;

Returns
number

Examples

TypeScript

/**
* This script doubles the column width for every column in the active
worksheet's used range.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// To optimize performance, get all the current row heights before


setting them.
let currentWidths = Array<number>(usedRange.getColumnCount());
for (let column = 0; column < currentWidths.length; column++) {
currentWidths[column] =
usedRange.getColumn(column).getFormat().getColumnWidth();
}

// Set the new column widths.


for (let column = 0; column < currentWidths.length; column++) {
usedRange.getFormat().setColumnWidth(currentWidths[column] * 2);
}

getFill()
Returns the fill object defined on the overall range.

TypeScript

getFill(): RangeFill;
Returns
ExcelScript.RangeFill

Examples

TypeScript

/**
* This script gives the total row of a table a green color fill.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the workbook.
let table = workbook.getTables()[0];

// Get the range for the total row of the table.


let totalRange = table.getTotalRowRange();

// Set the fill color to green.


totalRange.getFormat().getFill().setColor("green");
}

getFont()
Returns the font object defined on the overall range.

TypeScript

getFont(): RangeFont;

Returns
ExcelScript.RangeFont

Examples

TypeScript

/**
* This script bolds the text of cell A1.
*/
function main(workbook: ExcelScript.Workbook) {
// Get A1 on the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0,0);

// Bold the font for that cell


cell.getFormat().getFont().setBold(true);
}

getHorizontalAlignment()
Represents the horizontal alignment for the specified object. See
ExcelScript.HorizontalAlignment for details.

TypeScript

getHorizontalAlignment(): HorizontalAlignment;

Returns
ExcelScript.HorizontalAlignment

getIndentLevel()
An integer from 0 to 250 that indicates the indent level.

TypeScript

getIndentLevel(): number;

Returns
number

getProtection()
Returns the format protection object for a range.

TypeScript

getProtection(): FormatProtection;

Returns
ExcelScript.FormatProtection

getRangeBorder(index)
Gets a border object using its name.

TypeScript

getRangeBorder(index: BorderIndex): RangeBorder;

Parameters
index ExcelScript.BorderIndex
Index value of the border object to be retrieved. See ExcelScript.BorderIndex for
details.

Returns
ExcelScript.RangeBorder

Examples

TypeScript

/**
* This script adds a border around the outside of a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get a range from the current worksheet.
let range = workbook.getActiveWorksheet().getRange("B2:E15");

// Add a border around the whole bounding range.


let format = range.getFormat();

format.getRangeBorder(ExcelScript.BorderIndex.edgeTop).setStyle(ExcelScri
pt.BorderLineStyle.continuous); // Top border

format.getRangeBorder(ExcelScript.BorderIndex.edgeBottom).setStyle(ExcelS
cript.BorderLineStyle.continuous); // Bottom border

format.getRangeBorder(ExcelScript.BorderIndex.edgeLeft).setStyle(ExcelScr
ipt.BorderLineStyle.continuous); // Left border

format.getRangeBorder(ExcelScript.BorderIndex.edgeRight).setStyle(ExcelSc
ript.BorderLineStyle.continuous); // Right border
}

getRangeBorderTintAndShade()
Specifies a double that lightens or darkens a color for range borders. The value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the entire border collection doesn't have a uniform tintAndShade
setting.

TypeScript

getRangeBorderTintAndShade(): number;

Returns
number

getReadingOrder()
The reading order for the range.

TypeScript

getReadingOrder(): ReadingOrder;

Returns
ExcelScript.ReadingOrder

getRowHeight()
The height of all rows in the range. If the row heights are not uniform, null will be
returned.

TypeScript

getRowHeight(): number;

Returns
number

Examples

TypeScript
/**
* This script doubles the row height for every row in the active
worksheet's used range.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// To optimize performance, get all the current row heights before


setting them.
let currentHeights = Array<number>(usedRange.getRowCount());
for (let row = 0; row < currentHeights.length; row++) {
currentHeights[row] =
usedRange.getRow(row).getFormat().getRowHeight();
}

// Set the new row heights.


for (let row = 0; row < currentHeights.length; row++) {
usedRange.getFormat().setRowHeight(currentHeights[row] * 2);
}
}

getShrinkToFit()
Specifies if text automatically shrinks to fit in the available column width.

TypeScript

getShrinkToFit(): boolean;

Returns
boolean

getTextOrientation()
The text orientation of all the cells within the range. The text orientation should be
an integer either from -90 to 90, or 180 for vertically-oriented text. If the orientation
within a range are not uniform, then null will be returned.

TypeScript

getTextOrientation(): number;
Returns
number

getUseStandardHeight()
Determines if the row height of the Range object equals the standard height of the
sheet. Returns true if the row height of the Range object equals the standard height
of the sheet. Returns null if the range contains more than one row and the rows
aren't all the same height. Returns false otherwise.

TypeScript

getUseStandardHeight(): boolean;

Returns
boolean

getUseStandardWidth()
Specifies if the column width of the Range object equals the standard width of the
sheet. Returns true if the column width of the Range object equals the standard
width of the sheet. Returns null if the range contains more than one column and
the columns aren't all the same height. Returns false otherwise.

TypeScript

getUseStandardWidth(): boolean;

Returns
boolean

getVerticalAlignment()
Represents the vertical alignment for the specified object. See
ExcelScript.VerticalAlignment for details.

TypeScript
getVerticalAlignment(): VerticalAlignment;

Returns
ExcelScript.VerticalAlignment

getWrapText()
Specifies if Excel wraps the text in the object. A null value indicates that the entire
range doesn't have a uniform wrap setting

TypeScript

getWrapText(): boolean;

Returns
boolean

setAutoIndent(autoIndent)
Specifies if text is automatically indented when text alignment is set to equal
distribution.

TypeScript

setAutoIndent(autoIndent: boolean): void;

Parameters
autoIndent boolean

Returns
void

setColumnWidth(columnWidth)
Specifies the width of all columns within the range.
TypeScript

setColumnWidth(columnWidth: number): void;

Parameters
columnWidth number

Returns
void

Examples

TypeScript

/**
* This script inserts a new column and sets that column's width to 100
pixels wide.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();

// Insert a new column between the current B and C columns.


const bcRange = currentSheet.getRange("C:C");
const newColumn =
bcRange.insert(ExcelScript.InsertShiftDirection.right);

// Set the column width of the new column to 100 pixels.


newColumn.getFormat().setColumnWidth(100);
}

setHorizontalAlignment(horizontalAlignment)
Represents the horizontal alignment for the specified object. See
ExcelScript.HorizontalAlignment for details.

TypeScript

setHorizontalAlignment(horizontalAlignment: HorizontalAlignment): void;

Parameters
horizontalAlignment ExcelScript.HorizontalAlignment
Returns
void

Examples

TypeScript

/**
* This script centers the text in a table's header row cells.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const table = currentSheet.getTables()[0];

// Get the header range.


const headerRange = table.getHeaderRowRange();

// Set the horizontal text alignment to `center`.

headerRange.getFormat().setHorizontalAlignment(ExcelScript.HorizontalAlig
nment.center);
}

setIndentLevel(indentLevel)
An integer from 0 to 250 that indicates the indent level.

TypeScript

setIndentLevel(indentLevel: number): void;

Parameters
indentLevel number

Returns
void

setRangeBorderTintAndShade(rangeBorderTintAnd
Shade)
Specifies a double that lightens or darkens a color for range borders. The value is
between -1 (darkest) and 1 (brightest), with 0 for the original color. A null value
indicates that the entire border collection doesn't have a uniform tintAndShade
setting.

TypeScript

setRangeBorderTintAndShade(rangeBorderTintAndShade: number): void;

Parameters
rangeBorderTintAndShade number

Returns
void

setReadingOrder(readingOrder)
The reading order for the range.

TypeScript

setReadingOrder(readingOrder: ReadingOrder): void;

Parameters
readingOrder ExcelScript.ReadingOrder

Returns
void

setRowHeight(rowHeight)
Specifies the height of all rows in the range.

TypeScript

setRowHeight(rowHeight: number): void;


Parameters
rowHeight number

Returns
void

Examples

TypeScript

/**
* This script inserts a new row and sets that row's width to 100 pixels
tall.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();

// Insert a new row between the current 2 and 3 rows.


const bcRange = currentSheet.getRange("3:3");
const newRow = bcRange.insert(ExcelScript.InsertShiftDirection.down);

// Set the row height of the new row to 100 pixels.


newRow.getFormat().setRowHeight(100);
}

setShrinkToFit(shrinkToFit)
Specifies if text automatically shrinks to fit in the available column width.

TypeScript

setShrinkToFit(shrinkToFit: boolean): void;

Parameters
shrinkToFit boolean

Returns
void

setTextOrientation(textOrientation)
The text orientation of all the cells within the range. The text orientation should be
an integer either from -90 to 90, or 180 for vertically-oriented text. If the orientation
within a range are not uniform, then null will be returned.

TypeScript

setTextOrientation(textOrientation: number): void;

Parameters
textOrientation number

Returns
void

setUseStandardHeight(useStandardHeight)
Determines if the row height of the Range object equals the standard height of the
sheet. Note: This property is only intended to be set to true . Setting it to false has
no effect.

TypeScript

setUseStandardHeight(useStandardHeight: boolean): void;

Parameters
useStandardHeight boolean

Returns
void

setUseStandardWidth(useStandardWidth)
Specifies if the column width of the Range object equals the standard width of the
sheet. Note: This property is only intended to be set to true . Setting it to false has
no effect.

TypeScript
setUseStandardWidth(useStandardWidth: boolean): void;

Parameters
useStandardWidth boolean

Returns
void

setVerticalAlignment(verticalAlignment)
Represents the vertical alignment for the specified object. See
ExcelScript.VerticalAlignment for details.

TypeScript

setVerticalAlignment(verticalAlignment: VerticalAlignment): void;

Parameters
verticalAlignment ExcelScript.VerticalAlignment

Returns
void

Examples

TypeScript

/**
* This script sets the vertical alignment formatting to "top"
* for every cell in the row.
*/
function main(workbook: ExcelScript.Workbook) {
// Get row 1 for the current worksheet.
const sheet = workbook.getActiveWorksheet();
const firstRow = sheet.getRange("1:1");

// Set the vertical alignment formatting on the row.

firstRow.getFormat().setVerticalAlignment(ExcelScript.VerticalAlignment.t
op);
}

setWrapText(wrapText)
Specifies if Excel wraps the text in the object. A null value indicates that the entire
range doesn't have a uniform wrap setting

TypeScript

setWrapText(wrapText: boolean): void;

Parameters
wrapText boolean

Returns
void

Examples

TypeScript

/**
* This script turns on the text wrapping for a column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the E column in current worksheet.
const column = workbook.getActiveWorksheet().getRange("E:E");

// Set wrap text to true for the column.


column.getFormat().setWrapText(true);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our  Provide product feedback
contributor guide.
ExcelScript.RangeHyperlink interface
Reference
Package: ExcelScript

Represents the necessary strings to get/set a hyperlink (XHL) object.

Remarks

Examples

TypeScript

/**
* This script puts a link to a webpage in a cell.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first cell in the current worksheet.
const cell = workbook.getActiveWorksheet().getCell(0,0);

// Create a link to a webpage.


const sampleHyperlink : ExcelScript.RangeHyperlink = {
address:
"https://learn.microsoft.com/office/dev/scripts/resources/samples/table-of-
contents",
screenTip: "Sample: Create a workbook table of contents",
textToDisplay: "Learn how to make a workbook table of contents"
}

// Put the link in the cell and format the width to fit.
cell.setHyperlink(sampleHyperlink);
cell.getFormat().autofitColumns();
}

Properties
ノ Expand table

address Represents the URL target for the hyperlink.

documentReference Represents the document reference target for the hyperlink.

screenTip Represents the string displayed when hovering over the hyperlink.

textToDisplay Represents the string that is displayed in the top left most cell in the range.
Property Details

address
Represents the URL target for the hyperlink.

TypeScript

address?: string;

Property Value
string

documentReference
Represents the document reference target for the hyperlink.

TypeScript

documentReference?: string;

Property Value
string

Examples

TypeScript

/**
* This script creates a hyperlink in the current cell to a table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the selected cell.
const selectedCell = workbook.getActiveCell();

// Create a hyperlink from the current cell to a table named


"Resources".
const link : ExcelScript.RangeHyperlink = {
documentReference: "Resources",
screenTip: "Resources table",
textToDisplay: "Go to table"
} ;
selectedCell.setHyperlink(link)
}

screenTip
Represents the string displayed when hovering over the hyperlink.

TypeScript

screenTip?: string;

Property Value
string

textToDisplay
Represents the string that is displayed in the top left most cell in the range.

TypeScript

textToDisplay?: string;

Property Value
string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RangeSort interface
Reference
Package: ExcelScript

Manages sorting operations on Range objects.

Methods
ノ Expand table

apply(fields, matchCase, hasHeaders, orientation, method) Perform a sort operation.

Method Details

apply(fields, matchCase, hasHeaders, orientation,


method)
Perform a sort operation.

TypeScript

apply(
fields: SortField[],
matchCase?: boolean,
hasHeaders?: boolean,
orientation?: SortOrientation,
method?: SortMethod
): void;

Parameters
fields ExcelScript.SortField[]
The list of conditions to sort on.

matchCase boolean
Optional. Whether to have the casing impact string ordering.

hasHeaders boolean
Optional. Whether the range has a header.
orientation ExcelScript.SortOrientation
Optional. Whether the operation is sorting rows or columns.

method ExcelScript.SortMethod
Optional. The ordering method used for Chinese characters.

Returns
void

Examples

TypeScript

/**
* This script sorts the used range of the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range of the current worksheet.
const activeRange = workbook.getActiveWorksheet().getUsedRange();

// Sort the rows in ascending order based on the last column.


activeRange.getSort().apply(
[{
ascending: true,
key: activeRange.getColumnCount() - 1
}],
false, /* Don't match case. */
true, /* Treat the first row as a header row. */
ExcelScript.SortOrientation.rows
);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RangeView interface
Reference
Package: ExcelScript

RangeView represents a set of visible cells of the parent range.

Remarks

Examples

TypeScript

/**
* This script copies values and formatting from the
* visible range of a table in Sheet1 into Sheet2.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the filtered data from Sheet1.
const currentSheet = workbook.getWorksheet("Sheet1");
const table = currentSheet.getTables()[0];
const visibleTableRange: ExcelScript.RangeView =
table.getRange().getVisibleView();
const source =
currentSheet.getRanges(visibleTableRange.getCellAddresses().toString());

// Copy the data into the other sheet.


const otherSheet = workbook.getWorksheet("Sheet2");
const otherRangeCorner = otherSheet.getRange("A1");
otherRangeCorner.copyFrom(source, ExcelScript.RangeCopyType.all);
}

Methods
ノ Expand table

getCellAddresses() Represents the cell addresses of the RangeView .

getColumnCount() The number of visible columns.

getFormulas() Represents the formula in A1-style notation. If a cell has no


formula, its value is returned instead.

getFormulasLocal() Represents the formula in A1-style notation, in the user's


language and number-formatting locale. For example, the
English "=SUM(A1, 1.5)" formula would become "=SUMME(A1;
1,5)" in German. If a cell has no formula, its value is returned
instead.

getFormulasR1C1() Represents the formula in R1C1-style notation. If a cell has no


formula, its value is returned instead.

getIndex() Returns a value that represents the index of the RangeView .

getNumberFormat() Represents Excel's number format code for the given cell.

getRange() Gets the parent range associated with the current RangeView .

getRowCount() The number of visible rows.

getRows() Represents a collection of range views associated with the range.

getText() Text values of the specified range. The text value will not depend
on the cell width. The # sign substitution that happens in Excel
UI will not affect the text value returned by the API.

getValues() Represents the raw values of the specified range view. The data
returned could be of type string, number, or a boolean. Cells
that contain an error will return the error string.

getValueTypes() Represents the type of data of each cell.

setFormulas(formulas) Represents the formula in A1-style notation. If a cell has no


formula, its value is returned instead.

setFormulasLocal(formulas Represents the formula in A1-style notation, in the user's


Local) language and number-formatting locale. For example, the
English "=SUM(A1, 1.5)" formula would become "=SUMME(A1;
1,5)" in German. If a cell has no formula, its value is returned
instead.

set Represents the formula in R1C1-style notation. If a cell has no


FormulasR1C1(formulasR1C1) formula, its value is returned instead.

setNumberFormat(number Represents Excel's number format code for the given cell.
Format)

setValues(values) Represents the raw values of the specified range view. The data
returned could be of type string, number, or a boolean. Cells
that contain an error will return the error string.

Method Details

getCellAddresses()
Represents the cell addresses of the RangeView .

TypeScript

getCellAddresses(): string[][];

Returns
string[][]

Examples

TypeScript

/**
* This script copies values and formatting from the
* visible range of a table in Sheet1 into Sheet2.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the filtered data from Sheet1.
const currentSheet = workbook.getWorksheet("Sheet1");
const table = currentSheet.getTables()[0];
const visibleTableRange: ExcelScript.RangeView =
table.getRange().getVisibleView();
const source =
currentSheet.getRanges(visibleTableRange.getCellAddresses().toString());

// Copy the data into the other sheet.


const otherSheet = workbook.getWorksheet("Sheet2");
const otherRangeCorner = otherSheet.getRange("A1");
otherRangeCorner.copyFrom(source, ExcelScript.RangeCopyType.all);
}

getColumnCount()
The number of visible columns.

TypeScript

getColumnCount(): number;

Returns
number
getFormulas()
Represents the formula in A1-style notation. If a cell has no formula, its value is
returned instead.

TypeScript

getFormulas(): string[][];

Returns
string[][]

getFormulasLocal()
Represents the formula in A1-style notation, in the user's language and number-
formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become
"=SUMME(A1; 1,5)" in German. If a cell has no formula, its value is returned instead.

TypeScript

getFormulasLocal(): string[][];

Returns
string[][]

getFormulasR1C1()
Represents the formula in R1C1-style notation. If a cell has no formula, its value is
returned instead.

TypeScript

getFormulasR1C1(): string[][];

Returns
string[][]

getIndex()
Returns a value that represents the index of the RangeView .

TypeScript

getIndex(): number;

Returns
number

getNumberFormat()
Represents Excel's number format code for the given cell.

TypeScript

getNumberFormat(): string[][];

Returns
string[][]

getRange()
Gets the parent range associated with the current RangeView .

TypeScript

getRange(): Range;

Returns
ExcelScript.Range

getRowCount()
The number of visible rows.

TypeScript

getRowCount(): number;
Returns
number

getRows()
Represents a collection of range views associated with the range.

TypeScript

getRows(): RangeView[];

Returns
ExcelScript.RangeView[]

getText()
Text values of the specified range. The text value will not depend on the cell width.
The # sign substitution that happens in Excel UI will not affect the text value returned
by the API.

TypeScript

getText(): string[][];

Returns
string[][]

getValues()
Represents the raw values of the specified range view. The data returned could be of
type string, number, or a boolean. Cells that contain an error will return the error
string.

TypeScript

getValues(): (string | number | boolean)[][];

Returns
(string | number | boolean)[][]

getValueTypes()
Represents the type of data of each cell.

TypeScript

getValueTypes(): RangeValueType[][];

Returns
ExcelScript.RangeValueType[][]

setFormulas(formulas)
Represents the formula in A1-style notation. If a cell has no formula, its value is
returned instead.

TypeScript

setFormulas(formulas: string[][]): void;

Parameters
formulas string[][]

Returns
void

setFormulasLocal(formulasLocal)
Represents the formula in A1-style notation, in the user's language and number-
formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become
"=SUMME(A1; 1,5)" in German. If a cell has no formula, its value is returned instead.

TypeScript

setFormulasLocal(formulasLocal: string[][]): void;


Parameters
formulasLocal string[][]

Returns
void

setFormulasR1C1(formulasR1C1)
Represents the formula in R1C1-style notation. If a cell has no formula, its value is
returned instead.

TypeScript

setFormulasR1C1(formulasR1C1: string[][]): void;

Parameters
formulasR1C1 string[][]

Returns
void

setNumberFormat(numberFormat)
Represents Excel's number format code for the given cell.

TypeScript

setNumberFormat(numberFormat: string[][]): void;

Parameters
numberFormat string[][]

Returns
void

setValues(values)
Represents the raw values of the specified range view. The data returned could be of
type string, number, or a boolean. Cells that contain an error will return the error
string.

TypeScript

setValues(values: (string | number | boolean)[][]): void;

Parameters
values (string | number | boolean)[][]

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RemoveDuplicatesResult
interface
Reference
Package: ExcelScript

Represents the results from Range.removeDuplicates .

Remarks

Examples

TypeScript

/**
* This script removes duplicate rows from a range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range of the active worksheet.
const usedRange = workbook.getActiveWorksheet().getUsedRange();

// Remove any row that has a same value in the 0-indexed column as a
previous row.
const removedResults: ExcelScript.RemoveDuplicatesResult =
usedRange.removeDuplicates([0], true);

// Log the count of removed rows.


console.log(`Rows removed: ${removedResults.getRemoved()}.`);
}

Methods
ノ Expand table

getRemoved() Number of duplicated rows removed by the operation.

getUniqueRemaining() Number of remaining unique rows present in the resulting range.

Method Details

getRemoved()
Number of duplicated rows removed by the operation.

TypeScript

getRemoved(): number;

Returns
number

getUniqueRemaining()
Number of remaining unique rows present in the resulting range.

TypeScript

getUniqueRemaining(): number;

Returns
number

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ReplaceCriteria interface
Reference
Package: ExcelScript

Represents the replace criteria to be used.

Properties
ノ Expand table

complete Specifies if the match needs to be complete or partial. A complete match matches
Match the entire contents of the cell. A partial match matches a substring within the
content of the cell (e.g., cat partially matches caterpillar and scatter ). Default is
false (partial).

matchCase Specifies if the match is case-sensitive. Default is false (case-insensitive).

Property Details

completeMatch
Specifies if the match needs to be complete or partial. A complete match matches
the entire contents of the cell. A partial match matches a substring within the
content of the cell (e.g., cat partially matches caterpillar and scatter ). Default is
false (partial).

TypeScript

completeMatch?: boolean;

Property Value
boolean

Examples

TypeScript
/**
* This script normalizes the text in a column so that values don't
include both "OK" and "okay".
* It replaces "OK" and all the case-based variants with "okay".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range representing column D.
const currentSheet = workbook.getActiveWorksheet();
const column = currentSheet.getRange("D:D");

// Create a ReplaceCriteria object for the Range.replaceAll call.


const criteria: ExcelScript.ReplaceCriteria = {
completeMatch: true, /* Use a complete match to skip cells that
already say "okay". */
matchCase: false /* Ignore case when comparing strings. */
};

// Replace all instances of "ok" (case-insensitive) with "okay".


column.replaceAll("ok", "okay", criteria);
}

matchCase
Specifies if the match is case-sensitive. Default is false (case-insensitive).

TypeScript

matchCase?: boolean;

Property Value
boolean

Examples

TypeScript

/**
* This script replaces instances of "NA" with "North America",
* using the casing to ignore parts of words.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the currently used range.
const currentSheet = workbook.getActiveWorksheet();
const usedRange = currentSheet.getUsedRange();

// Create a ReplaceCriteria object for the Range.replaceAll call.


const criteria: ExcelScript.ReplaceCriteria = {
completeMatch: false,
matchCase: true /* Match with "NA market", not "navigate" */
}

// Replace all instances of "NA" (case-sensitive) with "North America".


usedRange.replaceAll("NA", "North America", criteria);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.RowColumnPivotHierarchy
interface
Reference
Package: ExcelScript

Represents the Excel RowColumnPivotHierarchy.

Remarks

Examples

TypeScript

/**
* This sample sorts the rows of a PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get an existing PivotTable.
const pivotTable = workbook.getPivotTable("Farm Sales");

// Get the data hierarchy to use as the basis of the sort.


const valueFieldToSortOn: ExcelScript.DataPivotHierarchy =
pivotTable.getDataHierarchy("Sum of Crates Sold Wholesale");

// Get the row to sort.


const rowToSort: ExcelScript.RowColumnPivotHierarchy =
pivotTable.getRowHierarchy("Farm");

// Sort the "Farm" row's only field by the values in "Sum of Crates Sold
Wholesale".
rowToSort.getFields()[0].sortByValues(ExcelScript.SortBy.descending,
valueFieldToSortOn);
}

Methods
ノ Expand table

getFields() Returns the PivotFields associated with the RowColumnPivotHierarchy.

getId() ID of the RowColumnPivotHierarchy.

getName() Name of the RowColumnPivotHierarchy.


getPivot Gets a PivotField by name. If the PivotField does not exist, then this method
Field(name) returns undefined .

getPosition() Position of the RowColumnPivotHierarchy.

setName(name) Name of the RowColumnPivotHierarchy.

set Position of the RowColumnPivotHierarchy.


Position(position)

setToDefault() Reset the RowColumnPivotHierarchy back to its default values.

Method Details

getFields()
Returns the PivotFields associated with the RowColumnPivotHierarchy.

TypeScript

getFields(): PivotField[];

Returns
ExcelScript.PivotField[]

getId()
ID of the RowColumnPivotHierarchy.

TypeScript

getId(): string;

Returns
string

getName()
Name of the RowColumnPivotHierarchy.
TypeScript

getName(): string;

Returns
string

getPivotField(name)
Gets a PivotField by name. If the PivotField does not exist, then this method returns
undefined .

TypeScript

getPivotField(name: string): PivotField | undefined;

Parameters
name string
Name of the PivotField to be retrieved.

Returns
ExcelScript.PivotField | undefined

getPosition()
Position of the RowColumnPivotHierarchy.

TypeScript

getPosition(): number;

Returns
number

setName(name)
Name of the RowColumnPivotHierarchy.
TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

setPosition(position)
Position of the RowColumnPivotHierarchy.

TypeScript

setPosition(position: number): void;

Parameters
position number

Returns
void

setToDefault()
Reset the RowColumnPivotHierarchy back to its default values.

TypeScript

setToDefault(): void;

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SearchCriteria interface
Reference
Package: ExcelScript

Represents the search criteria to be used.

Remarks

Examples

TypeScript

/**
* This script searches for the next instance of the text "TK" on the
current worksheet.
* It then selects that cell and removes "TK" and all formatting from the
cell.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range on the current worksheet.
let range = workbook.getActiveWorksheet().getUsedRange();

// Get the next cell that contains "TK".


let tkCell = range.find("TK", {
completeMatch: true, /* Don't match if the cell text only contains "TK"
as part of another string. */
matchCase: false,
searchDirection: ExcelScript.SearchDirection.forward /* Start at the
beginning of the range and go to later columns and rows. */
});

// Set focus on the found cell.


tkCell.select();

// Remove the "TK" text value from the cell, as well as any formatting
that may have been added.
tkCell.clear(ExcelScript.ClearApplyTo.all);
}

Properties
ノ Expand table
complete Specifies if the match needs to be complete or partial. A complete match matches
Match the entire contents of the cell. A partial match matches a substring within the
content of the cell (e.g., cat partially matches caterpillar and scatter ). Default is
false (partial).

match Specifies if the match is case-sensitive. Default is false (case-insensitive).


Case

search Specifies the search direction. Default is forward. See ExcelScript.SearchDirection .


Direction

Property Details

completeMatch
Specifies if the match needs to be complete or partial. A complete match matches
the entire contents of the cell. A partial match matches a substring within the
content of the cell (e.g., cat partially matches caterpillar and scatter ). Default is
false (partial).

TypeScript

completeMatch?: boolean;

Property Value
boolean

matchCase
Specifies if the match is case-sensitive. Default is false (case-insensitive).

TypeScript

matchCase?: boolean;

Property Value
boolean

searchDirection
Specifies the search direction. Default is forward. See ExcelScript.SearchDirection .

TypeScript

searchDirection?: SearchDirection;

Property Value
ExcelScript.SearchDirection

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Shape interface
Reference
Package: ExcelScript

Represents a generic shape object in the worksheet. A shape could be a geometric


shape, a line, a group of shapes, etc.

Remarks

Examples

TypeScript

/**
* This script creates a hexagon shape on the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const hexagon: ExcelScript.Shape =
currentSheet.addGeometricShape(ExcelScript.GeometricShapeType.hexagon);

// Set the hexagon size to 40x40 pixels.


hexagon.setHeight(40);
hexagon.setWidth(40);

// Position the hexagon at [100,100] pixels.


hexagon.setLeft(100);
hexagon.setTop(100);
}

Methods
ノ Expand table

copyTo(destinationSheet) Copies and pastes a Shape object. The pasted shape is copied to the
same pixel location as this shape.

delete() Removes the shape from the worksheet.

getAltTextDescription() Specifies the alternative description text for a Shape object.

getAltTextTitle() Specifies the alternative title text for a Shape object.


getAsImage(format) Converts the shape to an image and returns the image as a base64-
encoded string. The DPI is 96. The only supported formats are
ExcelScript.PictureFormat.BMP , ExcelScript.PictureFormat.PNG ,
ExcelScript.PictureFormat.JPEG , and
ExcelScript.PictureFormat.GIF .

getConnectionSiteCount() Returns the number of connection sites on this shape.

getFill() Returns the fill formatting of this shape.

getGeometricShape() Returns the geometric shape associated with the shape. An error will
be thrown if the shape type is not "GeometricShape".

getGeometricShapeType() Specifies the geometric shape type of this geometric shape. See
ExcelScript.GeometricShapeType for details. Returns null if the
shape type is not "GeometricShape".

getGroup() Returns the shape group associated with the shape. An error will be
thrown if the shape type is not "GroupShape".

getHeight() Specifies the height, in points, of the shape. Throws an


InvalidArgument exception when set with a negative value or zero as
an input.

getId() Specifies the shape identifier.

getImage() Returns the image associated with the shape. An error will be thrown
if the shape type is not "Image".

getImage Converts the shape to an image and returns the image as a base64-
AsBase64(format) encoded string. The DPI is 96. The only supported formats are
ExcelScript.PictureFormat.BMP , ExcelScript.PictureFormat.PNG ,
ExcelScript.PictureFormat.JPEG , and
ExcelScript.PictureFormat.GIF .

getLeft() The distance, in points, from the left side of the shape to the left side
of the worksheet. Throws an InvalidArgument exception when set
with a negative value as an input.

getLevel() Specifies the level of the specified shape. For example, a level of 0
means that the shape is not part of any groups, a level of 1 means
the shape is part of a top-level group, and a level of 2 means the
shape is part of a sub-group of the top level.

getLine() Returns the line associated with the shape. An error will be thrown if
the shape type is not "Line".

getLineFormat() Returns the line formatting of this shape.

getLockAspectRatio() Specifies if the aspect ratio of this shape is locked.


getName() Specifies the name of the shape.

getParentGroup() Specifies the parent group of this shape.

getPlacement() Represents how the object is attached to the cells below it.

getRotation() Specifies the rotation, in degrees, of the shape.

getTextFrame() Returns the text frame object of this shape.

getTop() The distance, in points, from the top edge of the shape to the top
edge of the worksheet. Throws an InvalidArgument exception when
set with a negative value as an input.

getType() Returns the type of this shape. See ExcelScript.ShapeType for details.

getVisible() Specifies if the shape is visible.

getWidth() Specifies the width, in points, of the shape. Throws an


InvalidArgument exception when set with a negative value or zero as
an input.

getZOrderPosition() Returns the position of the specified shape in the z-order, with 0
representing the bottom of the order stack.

incrementLeft(increment) Moves the shape horizontally by the specified number of points.

increment Rotates the shape clockwise around the z-axis by the specified
Rotation(increment) number of degrees. Use the rotation property to set the absolute
rotation of the shape.

incrementTop(increment) Moves the shape vertically by the specified number of points.

scaleHeight(scaleFactor, Scales the height of the shape by a specified factor. For images, you
scaleType, scaleFrom) can indicate whether you want to scale the shape relative to the
original or the current size. Shapes other than pictures are always
scaled relative to their current height.

scaleWidth(scaleFactor, Scales the width of the shape by a specified factor. For images, you
scaleType, scaleFrom) can indicate whether you want to scale the shape relative to the
original or the current size. Shapes other than pictures are always
scaled relative to their current width.

setAltTextDescription(alt Specifies the alternative description text for a Shape object.


TextDescription)

setAltTextTitle(altTextTitle) Specifies the alternative title text for a Shape object.

setGeometricShape Specifies the geometric shape type of this geometric shape. See
Type(geometricShape ExcelScript.GeometricShapeType for details. Returns null if the
Type) shape type is not "GeometricShape".
setHeight(height) Specifies the height, in points, of the shape. Throws an
InvalidArgument exception when set with a negative value or zero as
an input.

setLeft(left) The distance, in points, from the left side of the shape to the left side
of the worksheet. Throws an InvalidArgument exception when set
with a negative value as an input.

setLockAspectRatio(lock Specifies if the aspect ratio of this shape is locked.


AspectRatio)

setName(name) Specifies the name of the shape.

setPlacement(placement) Represents how the object is attached to the cells below it.

setRotation(rotation) Specifies the rotation, in degrees, of the shape.

setTop(top) The distance, in points, from the top edge of the shape to the top
edge of the worksheet. Throws an InvalidArgument exception when
set with a negative value as an input.

setVisible(visible) Specifies if the shape is visible.

setWidth(width) Specifies the width, in points, of the shape. Throws an


InvalidArgument exception when set with a negative value or zero as
an input.

setZOrder(position) Moves the specified shape up or down the collection's z-order, which
shifts it in front of or behind other shapes.

Method Details

copyTo(destinationSheet)
Copies and pastes a Shape object. The pasted shape is copied to the same pixel
location as this shape.

TypeScript

copyTo(destinationSheet?: Worksheet | string): Shape;

Parameters
destinationSheet ExcelScript.Worksheet | string
The sheet to which the shape object will be pasted. The default value is the copied
shape's worksheet.
Returns
ExcelScript.Shape

delete()
Removes the shape from the worksheet.

TypeScript

delete(): void;

Returns
void

Examples

TypeScript

/**
* This script deletes all the shapes on the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the collection of shapes on the currently selected worksheet.
const shapes = workbook.getActiveWorksheet().getShapes();

// Remove each shape.


shapes.forEach(shape =>{
shape.delete();
});
}

getAltTextDescription()
Specifies the alternative description text for a Shape object.

TypeScript

getAltTextDescription(): string;

Returns
string
getAltTextTitle()
Specifies the alternative title text for a Shape object.

TypeScript

getAltTextTitle(): string;

Returns
string

getAsImage(format)

2 Warning

This API is now deprecated.

Use getImageAsBase64 instead.

Converts the shape to an image and returns the image as a base64-encoded string.
The DPI is 96. The only supported formats are ExcelScript.PictureFormat.BMP ,
ExcelScript.PictureFormat.PNG , ExcelScript.PictureFormat.JPEG , and

ExcelScript.PictureFormat.GIF .

TypeScript

getAsImage(format: PictureFormat): string;

Parameters
format ExcelScript.PictureFormat
Specifies the format of the image.

Returns
string

Examples
TypeScript

/**
* This script creates a star shape with the value from cell A1.
* It then returns the image as a base64-encoded string.
* This string would be used as part of a Power Automate flow to add the
image elsewhere.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the value of A1 from the worksheet named Sheet1.
const sheet = workbook.getWorksheet("Sheet1");
const value = sheet.getRange("A1").getValue();

// Create a Shape object that looks like a 5-pointed star.


const star =
sheet.addGeometricShape(ExcelScript.GeometricShapeType.star5);

// Set the text of star and make sure the shape fits the text.
const textFrame = star.getTextFrame();
textFrame.getTextRange().setText(value.toString());

textFrame.setAutoSizeSetting(ExcelScript.ShapeAutoSize.autoSizeShapeToFit
Text);

// Return the shape as a PNG image represented by a base64-encoded


string.
return star.getAsImage(ExcelScript.PictureFormat.png);
}

getConnectionSiteCount()
Returns the number of connection sites on this shape.

TypeScript

getConnectionSiteCount(): number;

Returns
number

getFill()
Returns the fill formatting of this shape.

TypeScript
getFill(): ShapeFill;

Returns
ExcelScript.ShapeFill

getGeometricShape()
Returns the geometric shape associated with the shape. An error will be thrown if the
shape type is not "GeometricShape".

TypeScript

getGeometricShape(): GeometricShape;

Returns
ExcelScript.GeometricShape

getGeometricShapeType()
Specifies the geometric shape type of this geometric shape. See
ExcelScript.GeometricShapeType for details. Returns null if the shape type is not

"GeometricShape".

TypeScript

getGeometricShapeType(): GeometricShapeType;

Returns
ExcelScript.GeometricShapeType

getGroup()
Returns the shape group associated with the shape. An error will be thrown if the
shape type is not "GroupShape".

TypeScript
getGroup(): ShapeGroup;

Returns
ExcelScript.ShapeGroup

getHeight()
Specifies the height, in points, of the shape. Throws an InvalidArgument exception
when set with a negative value or zero as an input.

TypeScript

getHeight(): number;

Returns
number

getId()
Specifies the shape identifier.

TypeScript

getId(): string;

Returns
string

getImage()
Returns the image associated with the shape. An error will be thrown if the shape
type is not "Image".

TypeScript

getImage(): Image;
Returns
ExcelScript.Image

Examples

TypeScript

/**
* This script transfers an image from one worksheet to another.
*/
function main(workbook: ExcelScript.Workbook)
{
// Get the worksheet with the image on it.
let firstWorksheet = workbook.getWorksheet("FirstSheet");

// Get the first image from the worksheet.


// If a script added the image, you could add a name to make it easier
to find.
let image: ExcelScript.Image;
firstWorksheet.getShapes().forEach((shape, index) => {
if (shape.getType() === ExcelScript.ShapeType.image) {
image = shape.getImage();
return;
}
});

// Copy the image to another worksheet.


image.getShape().copyTo("SecondSheet");
}

getImageAsBase64(format)
Converts the shape to an image and returns the image as a base64-encoded string.
The DPI is 96. The only supported formats are ExcelScript.PictureFormat.BMP ,
ExcelScript.PictureFormat.PNG , ExcelScript.PictureFormat.JPEG , and

ExcelScript.PictureFormat.GIF .

TypeScript

getImageAsBase64(format: PictureFormat): string;

Parameters
format ExcelScript.PictureFormat
Specifies the format of the image.
Returns
string

getLeft()
The distance, in points, from the left side of the shape to the left side of the
worksheet. Throws an InvalidArgument exception when set with a negative value as
an input.

TypeScript

getLeft(): number;

Returns
number

getLevel()
Specifies the level of the specified shape. For example, a level of 0 means that the
shape is not part of any groups, a level of 1 means the shape is part of a top-level
group, and a level of 2 means the shape is part of a sub-group of the top level.

TypeScript

getLevel(): number;

Returns
number

getLine()
Returns the line associated with the shape. An error will be thrown if the shape type
is not "Line".

TypeScript

getLine(): Line;
Returns
ExcelScript.Line

Examples

TypeScript

/**
* This script adds a line that goes from cell B2 to cell F4 on the
current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
const sheet = workbook.getActiveWorksheet();

// Get the ranges for the two cells.


const b2Range = sheet.getRange("B2");
const f4Range = sheet.getRange("F4");

// Add a straight line that connects the top-left corners of both


cells.
const newShape = sheet.addLine(
b2Range.getLeft(),
b2Range.getTop(),
f4Range.getLeft(),
f4Range.getTop(),
ExcelScript.ConnectorType.straight);

// Add an open arrowhead to the end of the line, such that it points at
F4.
const line = newShape.getLine();
line.setEndArrowheadStyle(ExcelScript.ArrowheadStyle.open);
}

getLineFormat()
Returns the line formatting of this shape.

TypeScript

getLineFormat(): ShapeLineFormat;

Returns
ExcelScript.ShapeLineFormat
getLockAspectRatio()
Specifies if the aspect ratio of this shape is locked.

TypeScript

getLockAspectRatio(): boolean;

Returns
boolean

getName()
Specifies the name of the shape.

TypeScript

getName(): string;

Returns
string

getParentGroup()
Specifies the parent group of this shape.

TypeScript

getParentGroup(): Shape;

Returns
ExcelScript.Shape

getPlacement()
Represents how the object is attached to the cells below it.

TypeScript
getPlacement(): Placement;

Returns
ExcelScript.Placement

getRotation()
Specifies the rotation, in degrees, of the shape.

TypeScript

getRotation(): number;

Returns
number

getTextFrame()
Returns the text frame object of this shape.

TypeScript

getTextFrame(): TextFrame;

Returns
ExcelScript.TextFrame

Examples

TypeScript

/**
* This script creates a star shape with the value from cell A1.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the value of A1 from the worksheet named Sheet1.
const sheet = workbook.getWorksheet("Sheet1");
const value = sheet.getRange("A1").getValue();
// Create a Shape object that looks like a 5-pointed star.
const star =
sheet.addGeometricShape(ExcelScript.GeometricShapeType.star5);

// Set the text of star and make sure the shape fits the text.
const textFrame = star.getTextFrame();
textFrame.getTextRange().setText(value.toString());

textFrame.setAutoSizeSetting(ExcelScript.ShapeAutoSize.autoSizeShapeToFit
Text);
}

getTop()
The distance, in points, from the top edge of the shape to the top edge of the
worksheet. Throws an InvalidArgument exception when set with a negative value as
an input.

TypeScript

getTop(): number;

Returns
number

getType()
Returns the type of this shape. See ExcelScript.ShapeType for details.

TypeScript

getType(): ShapeType;

Returns
ExcelScript.ShapeType

getVisible()
Specifies if the shape is visible.

TypeScript
getVisible(): boolean;

Returns
boolean

getWidth()
Specifies the width, in points, of the shape. Throws an InvalidArgument exception
when set with a negative value or zero as an input.

TypeScript

getWidth(): number;

Returns
number

getZOrderPosition()
Returns the position of the specified shape in the z-order, with 0 representing the
bottom of the order stack.

TypeScript

getZOrderPosition(): number;

Returns
number

incrementLeft(increment)
Moves the shape horizontally by the specified number of points.

TypeScript

incrementLeft(increment: number): void;


Parameters
increment number
The increment, in points, the shape will be horizontally moved. A positive value
moves the shape to the right and a negative value moves it to the left. If the sheet is
right-to-left oriented, this is reversed: positive values will move the shape to the left
and negative values will move it to the right.

Returns
void

incrementRotation(increment)
Rotates the shape clockwise around the z-axis by the specified number of degrees.
Use the rotation property to set the absolute rotation of the shape.

TypeScript

incrementRotation(increment: number): void;

Parameters
increment number
How many degrees the shape will be rotated. A positive value rotates the shape
clockwise and a negative value rotates it counterclockwise.

Returns
void

incrementTop(increment)
Moves the shape vertically by the specified number of points.

TypeScript

incrementTop(increment: number): void;

Parameters
increment number
The increment, in points, the shape will be vertically moved. A positive value moves
the shape down and a negative value moves it up.

Returns
void

scaleHeight(scaleFactor, scaleType, scaleFrom)


Scales the height of the shape by a specified factor. For images, you can indicate
whether you want to scale the shape relative to the original or the current size.
Shapes other than pictures are always scaled relative to their current height.

TypeScript

scaleHeight(
scaleFactor: number,
scaleType: ShapeScaleType,
scaleFrom?: ShapeScaleFrom
): void;

Parameters
scaleFactor number
Specifies the ratio between the height of the shape after you resize it and the current
or original height.

scaleType ExcelScript.ShapeScaleType
Specifies whether the shape is scaled relative to its original or current size. The
original size scaling option only works for images.

scaleFrom ExcelScript.ShapeScaleFrom
Optional. Specifies which part of the shape retains its position when the shape is
scaled. If omitted, it represents the shape's upper left corner retains its position.

Returns
void

scaleWidth(scaleFactor, scaleType, scaleFrom)


Scales the width of the shape by a specified factor. For images, you can indicate
whether you want to scale the shape relative to the original or the current size.
Shapes other than pictures are always scaled relative to their current width.

TypeScript

scaleWidth(
scaleFactor: number,
scaleType: ShapeScaleType,
scaleFrom?: ShapeScaleFrom
): void;

Parameters
scaleFactor number
Specifies the ratio between the width of the shape after you resize it and the current
or original width.

scaleType ExcelScript.ShapeScaleType
Specifies whether the shape is scaled relative to its original or current size. The
original size scaling option only works for images.

scaleFrom ExcelScript.ShapeScaleFrom
Optional. Specifies which part of the shape retains its position when the shape is
scaled. If omitted, it represents the shape's upper left corner retains its position.

Returns
void

setAltTextDescription(altTextDescription)
Specifies the alternative description text for a Shape object.

TypeScript

setAltTextDescription(altTextDescription: string): void;

Parameters
altTextDescription string
Returns
void

setAltTextTitle(altTextTitle)
Specifies the alternative title text for a Shape object.

TypeScript

setAltTextTitle(altTextTitle: string): void;

Parameters
altTextTitle string

Returns
void

setGeometricShapeType(geometricShapeType)
Specifies the geometric shape type of this geometric shape. See
ExcelScript.GeometricShapeType for details. Returns null if the shape type is not

"GeometricShape".

TypeScript

setGeometricShapeType(geometricShapeType: GeometricShapeType): void;

Parameters
geometricShapeType ExcelScript.GeometricShapeType

Returns
void

setHeight(height)
Specifies the height, in points, of the shape. Throws an InvalidArgument exception
when set with a negative value or zero as an input.
TypeScript

setHeight(height: number): void;

Parameters
height number

Returns
void

setLeft(left)
The distance, in points, from the left side of the shape to the left side of the
worksheet. Throws an InvalidArgument exception when set with a negative value as
an input.

TypeScript

setLeft(left: number): void;

Parameters
left number

Returns
void

setLockAspectRatio(lockAspectRatio)
Specifies if the aspect ratio of this shape is locked.

TypeScript

setLockAspectRatio(lockAspectRatio: boolean): void;

Parameters
lockAspectRatio boolean
Returns
void

setName(name)
Specifies the name of the shape.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

Examples

TypeScript

/**
* This script creates a triangle shape on the current worksheet and
names it "TRI".
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const triangle: ExcelScript.Shape =

currentSheet.addGeometricShape(ExcelScript.GeometricShapeType.triangle);

triangle.setName("TRI");
}

setPlacement(placement)
Represents how the object is attached to the cells below it.

TypeScript

setPlacement(placement: Placement): void;


Parameters
placement ExcelScript.Placement

Returns
void

Examples

TypeScript

/**
* This script creates a diamond shape at cell C3.
* The shape moves and resizes as the grid underneath it changes.
*/
function main(workbook: ExcelScript.Workbook) {
// Get cell C3 in the current worksheet.
const sheet = workbook.getActiveWorksheet();
const cell = sheet.getRange("C3");

// Create a diamond that slightly overlaps the cell C3.


const diamond =
sheet.addGeometricShape(ExcelScript.GeometricShapeType.diamond);
// Set each dimension so that the shape extends 5 pixels beyond the
cell borders.
diamond.setLeft(cell.getLeft() - 5);
diamond.setTop(cell.getTop() - 5);
diamond.setHeight(cell.getHeight() + 10);
diamond.setWidth(cell.getWidth() + 10);

// Set the placement of the shape so that it resizes and moves with the
grid.
diamond.setPlacement(ExcelScript.Placement.twoCell);
}

setRotation(rotation)
Specifies the rotation, in degrees, of the shape.

TypeScript

setRotation(rotation: number): void;

Parameters
rotation number
Returns
void

setTop(top)
The distance, in points, from the top edge of the shape to the top edge of the
worksheet. Throws an InvalidArgument exception when set with a negative value as
an input.

TypeScript

setTop(top: number): void;

Parameters
top number

Returns
void

setVisible(visible)
Specifies if the shape is visible.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void

setWidth(width)
Specifies the width, in points, of the shape. Throws an InvalidArgument exception
when set with a negative value or zero as an input.
TypeScript

setWidth(width: number): void;

Parameters
width number

Returns
void

setZOrder(position)
Moves the specified shape up or down the collection's z-order, which shifts it in front
of or behind other shapes.

TypeScript

setZOrder(position: ShapeZOrder): void;

Parameters
position ExcelScript.ShapeZOrder
Where to move the shape in the z-order stack relative to the other shapes. See
ExcelScript.ShapeZOrder for details.

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeFill interface
Reference
Package: ExcelScript

Represents the fill formatting of a shape object.

Methods
ノ Expand table

clear() Clears the fill formatting of this shape.

getForegroundColor() Represents the shape fill foreground color in HTML color format,
in the form #RRGGBB (e.g., "FFA500") or as a named HTML color
(e.g., "orange")

getTransparency() Specifies the transparency percentage of the fill as a value from


0.0 (opaque) through 1.0 (clear). Returns null if the shape type
does not support transparency or the shape fill has inconsistent
transparency, such as with a gradient fill type.

getType() Returns the fill type of the shape. See ExcelScript.ShapeFillType


for details.

setForeground Represents the shape fill foreground color in HTML color format,
Color(foregroundColor) in the form #RRGGBB (e.g., "FFA500") or as a named HTML color
(e.g., "orange")

setSolidColor(color) Sets the fill formatting of the shape to a uniform color. This
changes the fill type to "Solid".

set Specifies the transparency percentage of the fill as a value from


Transparency(transparency) 0.0 (opaque) through 1.0 (clear). Returns null if the shape type
does not support transparency or the shape fill has inconsistent
transparency, such as with a gradient fill type.

Method Details

clear()
Clears the fill formatting of this shape.

TypeScript
clear(): void;

Returns
void

getForegroundColor()
Represents the shape fill foreground color in HTML color format, in the form
#RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange")

TypeScript

getForegroundColor(): string;

Returns
string

getTransparency()
Specifies the transparency percentage of the fill as a value from 0.0 (opaque)
through 1.0 (clear). Returns null if the shape type does not support transparency or
the shape fill has inconsistent transparency, such as with a gradient fill type.

TypeScript

getTransparency(): number;

Returns
number

getType()
Returns the fill type of the shape. See ExcelScript.ShapeFillType for details.

TypeScript

getType(): ShapeFillType;
Returns
ExcelScript.ShapeFillType

setForegroundColor(foregroundColor)
Represents the shape fill foreground color in HTML color format, in the form
#RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange")

TypeScript

setForegroundColor(foregroundColor: string): void;

Parameters
foregroundColor string

Returns
void

setSolidColor(color)
Sets the fill formatting of the shape to a uniform color. This changes the fill type to
"Solid".

TypeScript

setSolidColor(color: string): void;

Parameters
color string
A string that represents the fill color in HTML color format, in the form #RRGGBB
(e.g., "FFA500") or as a named HTML color (e.g., "orange").

Returns
void

setTransparency(transparency)
Specifies the transparency percentage of the fill as a value from 0.0 (opaque)
through 1.0 (clear). Returns null if the shape type does not support transparency or
the shape fill has inconsistent transparency, such as with a gradient fill type.

TypeScript

setTransparency(transparency: number): void;

Parameters
transparency number

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeFont interface
Reference
Package: ExcelScript

Represents the font attributes, such as font name, font size, and color, for a shape's
TextRange object.

Remarks

Examples

TypeScript

/**
* This sample sets the font of a shape to be bold.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first shape in the current worksheet.
const sheet = workbook.getActiveWorksheet();
const shape = sheet.getShapes()[0];

// Get the text font from the shape.


const text: ExcelScript.TextRange = shape.getTextFrame().getTextRange();
const shapeTextFont: ExcelScript.ShapeFont = text.getFont();

// Set the font to be bold.


shapeTextFont.setBold(true);
}

Methods
ノ Expand table

getBold() Represents the bold status of font. Returns null if the TextRange includes
both bold and non-bold text fragments.

getColor() HTML color code representation of the text color (e.g., "#FF0000"
represents red). Returns null if the TextRange includes text fragments
with different colors.

getItalic() Represents the italic status of font. Returns null if the TextRange includes
both italic and non-italic text fragments.
getName() Represents font name (e.g., "Calibri"). If the text is a Complex Script or East
Asian language, this is the corresponding font name; otherwise it is the
Latin font name.

getSize() Represents font size in points (e.g., 11). Returns null if the TextRange
includes text fragments with different font sizes.

getUnderline() Type of underline applied to the font. Returns null if the TextRange
includes text fragments with different underline styles. See
ExcelScript.ShapeFontUnderlineStyle for details.

setBold(bold) Represents the bold status of font. Returns null if the TextRange includes
both bold and non-bold text fragments.

setColor(color) HTML color code representation of the text color (e.g., "#FF0000"
represents red). Returns null if the TextRange includes text fragments
with different colors.

setItalic(italic) Represents the italic status of font. Returns null if the TextRange includes
both italic and non-italic text fragments.

setName(name) Represents font name (e.g., "Calibri"). If the text is a Complex Script or East
Asian language, this is the corresponding font name; otherwise it is the
Latin font name.

setSize(size) Represents font size in points (e.g., 11). Returns null if the TextRange
includes text fragments with different font sizes.

set Type of underline applied to the font. Returns null if the TextRange
Underline(underline) includes text fragments with different underline styles. See
ExcelScript.ShapeFontUnderlineStyle for details.

Method Details

getBold()
Represents the bold status of font. Returns null if the TextRange includes both bold
and non-bold text fragments.

TypeScript

getBold(): boolean;

Returns
boolean
getColor()
HTML color code representation of the text color (e.g., "#FF0000" represents red).
Returns null if the TextRange includes text fragments with different colors.

TypeScript

getColor(): string;

Returns
string

getItalic()
Represents the italic status of font. Returns null if the TextRange includes both italic
and non-italic text fragments.

TypeScript

getItalic(): boolean;

Returns
boolean

getName()
Represents font name (e.g., "Calibri"). If the text is a Complex Script or East Asian
language, this is the corresponding font name; otherwise it is the Latin font name.

TypeScript

getName(): string;

Returns
string

getSize()
Represents font size in points (e.g., 11). Returns null if the TextRange includes text
fragments with different font sizes.

TypeScript

getSize(): number;

Returns
number

getUnderline()
Type of underline applied to the font. Returns null if the TextRange includes text
fragments with different underline styles. See ExcelScript.ShapeFontUnderlineStyle
for details.

TypeScript

getUnderline(): ShapeFontUnderlineStyle;

Returns
ExcelScript.ShapeFontUnderlineStyle

setBold(bold)
Represents the bold status of font. Returns null if the TextRange includes both bold
and non-bold text fragments.

TypeScript

setBold(bold: boolean): void;

Parameters
bold boolean

Returns
void
setColor(color)
HTML color code representation of the text color (e.g., "#FF0000" represents red).
Returns null if the TextRange includes text fragments with different colors.

TypeScript

setColor(color: string): void;

Parameters
color string

Returns
void

setItalic(italic)
Represents the italic status of font. Returns null if the TextRange includes both italic
and non-italic text fragments.

TypeScript

setItalic(italic: boolean): void;

Parameters
italic boolean

Returns
void

setName(name)
Represents font name (e.g., "Calibri"). If the text is a Complex Script or East Asian
language, this is the corresponding font name; otherwise it is the Latin font name.

TypeScript
setName(name: string): void;

Parameters
name string

Returns
void

setSize(size)
Represents font size in points (e.g., 11). Returns null if the TextRange includes text
fragments with different font sizes.

TypeScript

setSize(size: number): void;

Parameters
size number

Returns
void

setUnderline(underline)
Type of underline applied to the font. Returns null if the TextRange includes text
fragments with different underline styles. See ExcelScript.ShapeFontUnderlineStyle
for details.

TypeScript

setUnderline(underline: ShapeFontUnderlineStyle): void;

Parameters
underline ExcelScript.ShapeFontUnderlineStyle
Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeGroup interface
Reference
Package: ExcelScript

Represents a shape group inside a worksheet. To get the corresponding Shape object,
use ShapeGroup.shape .

Methods
ノ Expand table

getGroup Returns the Shape object associated with the group.


Shape()

getId() Specifies the shape identifier.

getShape(key) Gets a shape using its name or ID. If the shape object does not exist, then this
method returns undefined .

getShapes() Returns the collection of Shape objects.

ungroup() Ungroups any grouped shapes in the specified shape group.

Method Details

getGroupShape()
Returns the Shape object associated with the group.

TypeScript

getGroupShape(): Shape;

Returns
ExcelScript.Shape

getId()
Specifies the shape identifier.
TypeScript

getId(): string;

Returns
string

getShape(key)
Gets a shape using its name or ID. If the shape object does not exist, then this
method returns undefined .

TypeScript

getShape(key: string): Shape | undefined;

Parameters
key string
The name or ID of the shape to be retrieved.

Returns
ExcelScript.Shape | undefined

getShapes()
Returns the collection of Shape objects.

TypeScript

getShapes(): Shape[];

Returns
ExcelScript.Shape[]

ungroup()
Ungroups any grouped shapes in the specified shape group.
TypeScript

ungroup(): void;

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.ShapeLineFormat interface
Reference
Package: ExcelScript

Represents the line formatting for the shape object. For images and geometric shapes,
line formatting represents the border of the shape.

Methods
ノ Expand table

getColor() Represents the line color in HTML color format, in the form
#RRGGBB (e.g., "FFA500") or as a named HTML color (e.g.,
"orange").

getDashStyle() Represents the line style of the shape. Returns null when the line
is not visible or there are inconsistent dash styles. See
ExcelScript.ShapeLineDashStyle for details.

getStyle() Represents the line style of the shape. Returns null when the line
is not visible or there are inconsistent styles. See
ExcelScript.ShapeLineStyle for details.

getTransparency() Represents the degree of transparency of the specified line as a


value from 0.0 (opaque) through 1.0 (clear). Returns null when the
shape has inconsistent transparencies.

getVisible() Specifies if the line formatting of a shape element is visible. Returns


null when the shape has inconsistent visibilities.

getWeight() Represents the weight of the line, in points. Returns null when the
line is not visible or there are inconsistent line weights.

setColor(color) Represents the line color in HTML color format, in the form
#RRGGBB (e.g., "FFA500") or as a named HTML color (e.g.,
"orange").

setDashStyle(dashStyle) Represents the line style of the shape. Returns null when the line
is not visible or there are inconsistent dash styles. See
ExcelScript.ShapeLineDashStyle for details.

setStyle(style) Represents the line style of the shape. Returns null when the line
is not visible or there are inconsistent styles. See
ExcelScript.ShapeLineStyle for details.
set Represents the degree of transparency of the specified line as a
Transparency(transparency) value from 0.0 (opaque) through 1.0 (clear). Returns null when the
shape has inconsistent transparencies.

setVisible(visible) Specifies if the line formatting of a shape element is visible. Returns


null when the shape has inconsistent visibilities.

setWeight(weight) Represents the weight of the line, in points. Returns null when the
line is not visible or there are inconsistent line weights.

Method Details

getColor()
Represents the line color in HTML color format, in the form #RRGGBB (e.g., "FFA500")
or as a named HTML color (e.g., "orange").

TypeScript

getColor(): string;

Returns
string

getDashStyle()
Represents the line style of the shape. Returns null when the line is not visible or
there are inconsistent dash styles. See ExcelScript.ShapeLineDashStyle for details.

TypeScript

getDashStyle(): ShapeLineDashStyle;

Returns
ExcelScript.ShapeLineDashStyle

getStyle()
Represents the line style of the shape. Returns null when the line is not visible or
there are inconsistent styles. See ExcelScript.ShapeLineStyle for details.

TypeScript

getStyle(): ShapeLineStyle;

Returns
ExcelScript.ShapeLineStyle

getTransparency()
Represents the degree of transparency of the specified line as a value from 0.0
(opaque) through 1.0 (clear). Returns null when the shape has inconsistent
transparencies.

TypeScript

getTransparency(): number;

Returns
number

getVisible()
Specifies if the line formatting of a shape element is visible. Returns null when the
shape has inconsistent visibilities.

TypeScript

getVisible(): boolean;

Returns
boolean

getWeight()
Represents the weight of the line, in points. Returns null when the line is not visible
or there are inconsistent line weights.

TypeScript

getWeight(): number;

Returns
number

setColor(color)
Represents the line color in HTML color format, in the form #RRGGBB (e.g., "FFA500")
or as a named HTML color (e.g., "orange").

TypeScript

setColor(color: string): void;

Parameters
color string

Returns
void

setDashStyle(dashStyle)
Represents the line style of the shape. Returns null when the line is not visible or
there are inconsistent dash styles. See ExcelScript.ShapeLineDashStyle for details.

TypeScript

setDashStyle(dashStyle: ShapeLineDashStyle): void;

Parameters
dashStyle ExcelScript.ShapeLineDashStyle
Returns
void

setStyle(style)
Represents the line style of the shape. Returns null when the line is not visible or
there are inconsistent styles. See ExcelScript.ShapeLineStyle for details.

TypeScript

setStyle(style: ShapeLineStyle): void;

Parameters
style ExcelScript.ShapeLineStyle

Returns
void

setTransparency(transparency)
Represents the degree of transparency of the specified line as a value from 0.0
(opaque) through 1.0 (clear). Returns null when the shape has inconsistent
transparencies.

TypeScript

setTransparency(transparency: number): void;

Parameters
transparency number

Returns
void

setVisible(visible)
Specifies if the line formatting of a shape element is visible. Returns null when the
shape has inconsistent visibilities.

TypeScript

setVisible(visible: boolean): void;

Parameters
visible boolean

Returns
void

setWeight(weight)
Represents the weight of the line, in points. Returns null when the line is not visible
or there are inconsistent line weights.

TypeScript

setWeight(weight: number): void;

Parameters
weight number

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.
ExcelScript.ShowAsRule interface
Reference
Package: ExcelScript

Remarks

Examples

TypeScript

/**
* The script changes the display for "Crates Sold at Farm".
* The field shows each value's difference
* from the value of the "Lemon" in the same row.
* If the row has no value for "Lemon", the field shows "#N/A".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Pivot".
const farmPivot = workbook.getPivotTable("Farm Pivot");

// Get the data hierarchy "Sum of Crates Sold at Farm".


const farmSales = farmPivot.getDataHierarchy("Sum of Crates Sold at
Farm");

// Get the row hierarchy "Type".


const typeField = farmPivot.getRowHierarchy("Type").getFields()[0];

// Change the data hierarchy to show each value as the difference


// from the value of the "Lemon" in that row.
const rule: ExcelScript.ShowAsRule = {
calculation: ExcelScript.ShowAsCalculation.differenceFrom,
baseField: typeField,
baseItem: typeField.getPivotItem("Lemon")
}
farmSales.setShowAs(rule);

// Set the name of the field to match the new behavior.


farmSales.setName("Difference from Lemons of Crates Sold at Farm");
}

Properties
ノ Expand table
baseField The PivotField to base the ShowAs calculation on, if applicable according to the
ShowAsCalculation type, else null .

baseItem The item to base the ShowAs calculation on, if applicable according to the
ShowAsCalculation type, else null .

calculation The ShowAs calculation to use for the PivotField. See ExcelScript.ShowAsCalculation
for details.

Property Details

baseField
The PivotField to base the ShowAs calculation on, if applicable according to the
ShowAsCalculation type, else null .

TypeScript

baseField?: PivotField;

Property Value
ExcelScript.PivotField

baseItem
The item to base the ShowAs calculation on, if applicable according to the
ShowAsCalculation type, else null .

TypeScript

baseItem?: PivotItem;

Property Value
ExcelScript.PivotItem

calculation
The ShowAs calculation to use for the PivotField. See ExcelScript.ShowAsCalculation
for details.
TypeScript

calculation: ShowAsCalculation;

Property Value
ExcelScript.ShowAsCalculation

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Slicer interface
Reference
Package: ExcelScript

Represents a Slicer object in the workbook.

Remarks

Examples

TypeScript

/**
* This script adds a slicer for an existing PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Pivot".
const farmPivot = workbook.getPivotTable("Farm Pivot");

// Create the slicer.


// Note that this assumes "Type" is already added as a hierarchy to the
PivotTable.
const fruitSlicer: ExcelScript.Slicer = workbook.addSlicer(
farmPivot, /* The table or PivotTale to be sliced. */
farmPivot.getHierarchy("Type").getFields()[0] /* What source field to
use as the slicer options. */
);

// Select the items to display.


fruitSlicer.selectItems(["Lemon", "Lime"]);

// Set the left margin of the slicer.


fruitSlicer.setLeft(400);
}

Methods
ノ Expand table

clearFilters() Clears all the filters currently applied on the slicer.

delete() Deletes the slicer.

getCaption() Represents the caption of the slicer.


getHeight() Represents the height, in points, of the slicer. Throws an InvalidArgument
exception when set with a negative value or zero as an input.

getId() Represents the unique ID of the slicer.

getIsFilter Value is true if all filters currently applied on the slicer are cleared.
Cleared()

getLeft() Represents the distance, in points, from the left side of the slicer to the left of
the worksheet. Throws an InvalidArgument error when set with a negative
value as an input.

getName() Represents the name of the slicer.

getSelected Returns an array of selected items' keys.


Items()

getSlicer Gets a slicer item using its key or name. If the slicer item doesn't exist, then
Item(key) this method returns undefined .

getSlicerItems() Represents the collection of slicer items that are part of the slicer.

getSortBy() Represents the sort order of the items in the slicer. Possible values are:
"DataSourceOrder", "Ascending", "Descending".

getStyle() Constant value that represents the slicer style. Possible values are:
"SlicerStyleLight1" through "SlicerStyleLight6", "TableStyleOther1" through
"TableStyleOther2", "SlicerStyleDark1" through "SlicerStyleDark6". A custom
user-defined style present in the workbook can also be specified.

getTop() Represents the distance, in points, from the top edge of the slicer to the top
of the worksheet. Throws an InvalidArgument error when set with a negative
value as an input.

getWidth() Represents the width, in points, of the slicer. Throws an InvalidArgument error
when set with a negative value or zero as an input.

getWorksheet() Represents the worksheet containing the slicer.

select Selects slicer items based on their keys. The previous selections are cleared.
Items(items) All items will be selected by default if the array is empty.

set Represents the caption of the slicer.


Caption(caption)

set Represents the height, in points, of the slicer. Throws an InvalidArgument


Height(height) exception when set with a negative value or zero as an input.

setLeft(left) Represents the distance, in points, from the left side of the slicer to the left of
the worksheet. Throws an InvalidArgument error when set with a negative
value as an input.
setName(name) Represents the name of the slicer.

setSortBy(sortBy) Represents the sort order of the items in the slicer. Possible values are:
"DataSourceOrder", "Ascending", "Descending".

setStyle(style) Constant value that represents the slicer style. Possible values are:
"SlicerStyleLight1" through "SlicerStyleLight6", "TableStyleOther1" through
"TableStyleOther2", "SlicerStyleDark1" through "SlicerStyleDark6". A custom
user-defined style present in the workbook can also be specified.

setTop(top) Represents the distance, in points, from the top edge of the slicer to the top
of the worksheet. Throws an InvalidArgument error when set with a negative
value as an input.

setWidth(width) Represents the width, in points, of the slicer. Throws an InvalidArgument error
when set with a negative value or zero as an input.

Method Details

clearFilters()
Clears all the filters currently applied on the slicer.

TypeScript

clearFilters(): void;

Returns
void

delete()
Deletes the slicer.

TypeScript

delete(): void;

Returns
void
getCaption()
Represents the caption of the slicer.

TypeScript

getCaption(): string;

Returns
string

getHeight()
Represents the height, in points, of the slicer. Throws an InvalidArgument exception
when set with a negative value or zero as an input.

TypeScript

getHeight(): number;

Returns
number

getId()
Represents the unique ID of the slicer.

TypeScript

getId(): string;

Returns
string

getIsFilterCleared()
Value is true if all filters currently applied on the slicer are cleared.
TypeScript

getIsFilterCleared(): boolean;

Returns
boolean

getLeft()
Represents the distance, in points, from the left side of the slicer to the left of the
worksheet. Throws an InvalidArgument error when set with a negative value as an
input.

TypeScript

getLeft(): number;

Returns
number

getName()
Represents the name of the slicer.

TypeScript

getName(): string;

Returns
string

getSelectedItems()
Returns an array of selected items' keys.

TypeScript

getSelectedItems(): string[];
Returns
string[]

getSlicerItem(key)
Gets a slicer item using its key or name. If the slicer item doesn't exist, then this
method returns undefined .

TypeScript

getSlicerItem(key: string): SlicerItem | undefined;

Parameters
key string
Key or name of the slicer to be retrieved.

Returns
ExcelScript.SlicerItem | undefined

getSlicerItems()
Represents the collection of slicer items that are part of the slicer.

TypeScript

getSlicerItems(): SlicerItem[];

Returns
ExcelScript.SlicerItem[]

getSortBy()
Represents the sort order of the items in the slicer. Possible values are:
"DataSourceOrder", "Ascending", "Descending".

TypeScript

getSortBy(): SlicerSortType;
Returns
ExcelScript.SlicerSortType

getStyle()
Constant value that represents the slicer style. Possible values are: "SlicerStyleLight1"
through "SlicerStyleLight6", "TableStyleOther1" through "TableStyleOther2",
"SlicerStyleDark1" through "SlicerStyleDark6". A custom user-defined style present in
the workbook can also be specified.

TypeScript

getStyle(): string;

Returns
string

getTop()
Represents the distance, in points, from the top edge of the slicer to the top of the
worksheet. Throws an InvalidArgument error when set with a negative value as an
input.

TypeScript

getTop(): number;

Returns
number

getWidth()
Represents the width, in points, of the slicer. Throws an InvalidArgument error when
set with a negative value or zero as an input.

TypeScript

getWidth(): number;
Returns
number

getWorksheet()
Represents the worksheet containing the slicer.

TypeScript

getWorksheet(): Worksheet;

Returns
ExcelScript.Worksheet

selectItems(items)
Selects slicer items based on their keys. The previous selections are cleared. All items
will be selected by default if the array is empty.

TypeScript

selectItems(items?: string[]): void;

Parameters
items string[]
Optional. The specified slicer item names to be selected.

Returns
void

setCaption(caption)
Represents the caption of the slicer.

TypeScript

setCaption(caption: string): void;


Parameters
caption string

Returns
void

setHeight(height)
Represents the height, in points, of the slicer. Throws an InvalidArgument exception
when set with a negative value or zero as an input.

TypeScript

setHeight(height: number): void;

Parameters
height number

Returns
void

setLeft(left)
Represents the distance, in points, from the left side of the slicer to the left of the
worksheet. Throws an InvalidArgument error when set with a negative value as an
input.

TypeScript

setLeft(left: number): void;

Parameters
left number

Returns
void
setName(name)
Represents the name of the slicer.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

setSortBy(sortBy)
Represents the sort order of the items in the slicer. Possible values are:
"DataSourceOrder", "Ascending", "Descending".

TypeScript

setSortBy(sortBy: SlicerSortType): void;

Parameters
sortBy ExcelScript.SlicerSortType

Returns
void

setStyle(style)
Constant value that represents the slicer style. Possible values are: "SlicerStyleLight1"
through "SlicerStyleLight6", "TableStyleOther1" through "TableStyleOther2",
"SlicerStyleDark1" through "SlicerStyleDark6". A custom user-defined style present in
the workbook can also be specified.

TypeScript
setStyle(style: string): void;

Parameters
style string

Returns
void

setTop(top)
Represents the distance, in points, from the top edge of the slicer to the top of the
worksheet. Throws an InvalidArgument error when set with a negative value as an
input.

TypeScript

setTop(top: number): void;

Parameters
top number

Returns
void

setWidth(width)
Represents the width, in points, of the slicer. Throws an InvalidArgument error when
set with a negative value or zero as an input.

TypeScript

setWidth(width: number): void;

Parameters
width number
Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SlicerItem interface
Reference
Package: ExcelScript

Represents a slicer item in a slicer.

Methods
ノ Expand table

getHasData() Value is true if the slicer item has data.

getIsSelected() Value is true if the slicer item is selected. Setting this value will not clear the
selected state of other slicer items. By default, if the slicer item is the only one
selected, when it is deselected, all items will be selected.

getKey() Represents the unique value representing the slicer item.

getName() Represents the title displayed in the Excel UI.

setIsSelected(is Value is true if the slicer item is selected. Setting this value will not clear the
Selected) selected state of other slicer items. By default, if the slicer item is the only one
selected, when it is deselected, all items will be selected.

Method Details

getHasData()
Value is true if the slicer item has data.

TypeScript

getHasData(): boolean;

Returns
boolean

getIsSelected()
Value is true if the slicer item is selected. Setting this value will not clear the selected
state of other slicer items. By default, if the slicer item is the only one selected, when
it is deselected, all items will be selected.

TypeScript

getIsSelected(): boolean;

Returns
boolean

getKey()
Represents the unique value representing the slicer item.

TypeScript

getKey(): string;

Returns
string

getName()
Represents the title displayed in the Excel UI.

TypeScript

getName(): string;

Returns
string

setIsSelected(isSelected)
Value is true if the slicer item is selected. Setting this value will not clear the selected
state of other slicer items. By default, if the slicer item is the only one selected, when
it is deselected, all items will be selected.
TypeScript

setIsSelected(isSelected: boolean): void;

Parameters
isSelected boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SlicerStyle interface
Reference
Package: ExcelScript

Represents a slicer style, which defines style elements by region of the slicer.

Methods
ノ Expand table

delete() Deletes the slicer style.

duplicate() Creates a duplicate of this slicer style with copies of all the style elements.

getName() Specifies the name of the slicer style.

getReadOnly() Specifies if this SlicerStyle object is read-only.

setName(name) Specifies the name of the slicer style.

Method Details

delete()
Deletes the slicer style.

TypeScript

delete(): void;

Returns
void

duplicate()
Creates a duplicate of this slicer style with copies of all the style elements.

TypeScript
duplicate(): SlicerStyle;

Returns
ExcelScript.SlicerStyle

getName()
Specifies the name of the slicer style.

TypeScript

getName(): string;

Returns
string

getReadOnly()
Specifies if this SlicerStyle object is read-only.

TypeScript

getReadOnly(): boolean;

Returns
boolean

setName(name)
Specifies the name of the slicer style.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.SortField interface
Reference
Package: ExcelScript

Represents a condition in a sorting operation.

Properties
ノ Expand table

ascending Specifies if the sorting is done in an ascending fashion.

color Specifies the color that is the target of the condition if the sorting is on font or cell
color.

data Represents additional sorting options for this field.


Option

icon Specifies the icon that is the target of the condition, if the sorting is on the cell's
icon.

key Specifies the column (or row, depending on the sort orientation) that the condition
is on. Represented as an offset from the first column (or row).

sortOn Specifies the type of sorting of this condition.

subField Specifies the subfield that is the target property name of a rich value to sort on.

Property Details

ascending
Specifies if the sorting is done in an ascending fashion.

TypeScript

ascending?: boolean;

Property Value
boolean
color
Specifies the color that is the target of the condition if the sorting is on font or cell
color.

TypeScript

color?: string;

Property Value
string

Examples

TypeScript

/**
* This script sorts a range based on the color of the cells.
* It brings all red cells to the top of the range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the range (A1:D8) to sort from the current worksheet.
const worksheet = workbook.getActiveWorksheet();
const rangeToSort = worksheet.getRange("A1:D8");

// Create a SortField for color sorting.


// This sorts the rows based on the fill color of each row's cell in
the first column.
let colorSort: ExcelScript.SortField = {
ascending: true,
color: "FF0000", /* red */
key: 0,
sortOn: ExcelScript.SortOn.cellColor
};

// Apply the SortField to the range.


rangeToSort.getSort().apply([colorSort]);
}

dataOption
Represents additional sorting options for this field.

TypeScript
dataOption?: SortDataOption;

Property Value
ExcelScript.SortDataOption

Examples

TypeScript

/**
* This script sorts a table based on the values in column 1.
* If the text of a column-1 value can be treated as a number,
* it will be sorted in numerical order, rather than Unicode order
* (so 123 will come before 12.3).
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const table = currentSheet.getTables()[0];

// Create the sorting parameters.


const countSortField: ExcelScript.SortField = {
key: 1,
ascending: true,
dataOption: ExcelScript.SortDataOption.textAsNumber
};

// Apply the sort to the table.


const sort = table.getSort();
sort.apply([countSortField]);
}

icon
Specifies the icon that is the target of the condition, if the sorting is on the cell's
icon.

TypeScript

icon?: Icon;

Property Value
ExcelScript.Icon
key
Specifies the column (or row, depending on the sort orientation) that the condition is
on. Represented as an offset from the first column (or row).

TypeScript

key: number;

Property Value
number

Examples

TypeScript

/**
* This script sorts the used range of the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range of the current worksheet.
const activeRange = workbook.getActiveWorksheet().getUsedRange();

// Sort the rows in ascending order based on the last column.


activeRange.getSort().apply(
[{
ascending: true,
key: activeRange.getColumnCount() - 1
}],
false, /* Don't match case. */
true, /* Treat the first row as a header rows. */
ExcelScript.SortOrientation.rows
);
}

sortOn
Specifies the type of sorting of this condition.

TypeScript

sortOn?: SortOn;
Property Value
ExcelScript.SortOn

subField
Specifies the subfield that is the target property name of a rich value to sort on.

TypeScript

subField?: string;

Property Value
string

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Subtotals interface
Reference
Package: ExcelScript

Subtotals for the Pivot Field.

Properties
ノ Expand table

automatic If Automatic is set to true , then all other values will be ignored when setting
the Subtotals .

average Average

count Count

countNumbers CountNumbers

max Max

min Min

product Product

standard StandardDeviation
Deviation

standard StandardDeviationP
DeviationP

sum Sum

variance Variance

varianceP VarianceP

Property Details

automatic
If Automatic is set to true , then all other values will be ignored when setting the
Subtotals .
TypeScript

automatic?: boolean;

Property Value
boolean

average
Average

TypeScript

average?: boolean;

Property Value
boolean

count
Count

TypeScript

count?: boolean;

Property Value
boolean

countNumbers
CountNumbers

TypeScript

countNumbers?: boolean;
Property Value
boolean

max
Max

TypeScript

max?: boolean;

Property Value
boolean

min
Min

TypeScript

min?: boolean;

Property Value
boolean

product
Product

TypeScript

product?: boolean;

Property Value
boolean

standardDeviation
StandardDeviation

TypeScript

standardDeviation?: boolean;

Property Value
boolean

standardDeviationP
StandardDeviationP

TypeScript

standardDeviationP?: boolean;

Property Value
boolean

sum
Sum

TypeScript

sum?: boolean;

Property Value
boolean

variance
Variance

TypeScript

variance?: boolean;
Property Value
boolean

varianceP
VarianceP

TypeScript

varianceP?: boolean;

Property Value
boolean

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Table interface
Reference
Package: ExcelScript

Represents an Excel table.

Remarks

Examples

TypeScript

/**
* This script creates a table from the current sheet's used range.
* It then adds a total row to the table with the SUM of the last column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the used range of the current worksheet.
const sheet = workbook.getActiveWorksheet();
const range = sheet.getUsedRange();

// Create a table that has headers from that range.


const table = sheet.addTable(range, true);

// Have the table display the SUM for the last column.
table.setShowTotals(true);
const lastColumn = table.getColumn(table.getColumns().length);
lastColumn.getTotalRowRange().setFormula(`=SUBTOTAL(109,
[${lastColumn.getName()}])`);
}

Methods
ノ Expand table

addColumn(index, Adds a new column to the table.


values, name)

addRow(index, values) Adds one row to the table.

addRows(index, Adds one or more rows to the table.


values)

clearFilters() Clears all the filters currently applied on the table.


convertToRange() Converts the table into a normal range of cells. All data is preserved.

delete() Deletes the table.

deleteRowsAt(index, Delete a specified number of rows at a given index.


count)

getAutoFilter() Represents the AutoFilter object of the table.

getColumn(key) Gets a column object by name or ID. If the column doesn't exist, then
this method returns undefined .

getColumnById(key) Gets a column object by ID. If the column does not exist, will return
undefined.

getColumn Gets a column object by Name. If the column does not exist, will return
ByName(key) undefined.

getColumns() Represents a collection of all the columns in the table.

getHeaderRowRange() Gets the range object associated with the header row of the table.

getHighlightFirst Specifies if the first column contains special formatting.


Column()

getHighlightLast Specifies if the last column contains special formatting.


Column()

getId() Returns a value that uniquely identifies the table in a given workbook.
The value of the identifier remains the same even when the table is
renamed.

getLegacyId() Returns a numeric ID.

getName() Name of the table.

getPredefinedTable Constant value that represents the table style. Possible values are:
Style() "TableStyleLight1" through "TableStyleLight21", "TableStyleMedium1"
through "TableStyleMedium28", "TableStyleDark1" through
"TableStyleDark11". A custom user-defined style present in the
workbook can also be specified.

getRange() Gets the range object associated with the entire table.

getRangeBetween Gets the range object associated with the data body of the table.
HeaderAndTotal()

getRowCount() Gets the number of rows in the table.

getShowBanded Specifies if the columns show banded formatting in which odd columns
Columns() are highlighted differently from even ones, to make reading the table
easier.
getShowBandedRows() Specifies if the rows show banded formatting in which odd rows are
highlighted differently from even ones, to make reading the table easier.

getShowFilterButton() Specifies if the filter buttons are visible at the top of each column
header. Setting this is only allowed if the table contains a header row.

getShowHeaders() Specifies if the header row is visible. This value can be set to show or
remove the header row.

getShowTotals() Specifies if the total row is visible. This value can be set to show or
remove the total row.

getSort() Represents the sorting for the table.

getTotalRowRange() Gets the range object associated with the totals row of the table.

getWorksheet() The worksheet containing the current table.

reapplyFilters() Reapplies all the filters currently on the table.

resize(newRange) Resize the table to the new range. The new range must overlap with the
original table range and the headers (or the top of the table) must be in
the same row.

setHighlightFirst Specifies if the first column contains special formatting.


Column(highlightFirst
Column)

setHighlightLast Specifies if the last column contains special formatting.


Column(highlightLast
Column)

setName(name) Name of the table.

setPredefinedTable Constant value that represents the table style. Possible values are:
Style(predefinedTable "TableStyleLight1" through "TableStyleLight21", "TableStyleMedium1"
Style) through "TableStyleMedium28", "TableStyleDark1" through
"TableStyleDark11". A custom user-defined style present in the
workbook can also be specified.

setShowBanded Specifies if the columns show banded formatting in which odd columns
Columns(showBanded are highlighted differently from even ones, to make reading the table
Columns) easier.

setShowBanded Specifies if the rows show banded formatting in which odd rows are
Rows(showBanded highlighted differently from even ones, to make reading the table easier.
Rows)

setShowFilter Specifies if the filter buttons are visible at the top of each column
Button(showFilter header. Setting this is only allowed if the table contains a header row.
Button)
setShowHeaders(show Specifies if the header row is visible. This value can be set to show or
Headers) remove the header row.

setShowTotals(show Specifies if the total row is visible. This value can be set to show or
Totals) remove the total row.

Method Details

addColumn(index, values, name)


Adds a new column to the table.

TypeScript

addColumn(
index?: number,
values?: (boolean | string | number)[],
name?: string
): TableColumn;

Parameters
index number
Optional. Specifies the relative position of the new column. If null or -1, the addition
happens at the end. Columns with a higher index will be shifted to the side. Zero-
indexed.

values (boolean | string | number)[]


Optional. A 1-dimensional array of unformatted values of the table column.

name string
Optional. Specifies the name of the new column. If null, the default name will be
used.

Returns
ExcelScript.TableColumn

Examples

TypeScript
/**
* This script adds a new column to a table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the workbook.
const table = workbook.getTables()[0];

// Append an empty column to the table with the header "Total".


table.addColumn(-1, null, "Total");
}

addRow(index, values)
Adds one row to the table.

TypeScript

addRow(index?: number, values?: (boolean | string | number)[]): void;

Parameters
index number
Optional. Specifies the relative position of the new row. If null or -1, the addition
happens at the end. Any rows below the inserted row are shifted downwards. Zero-
indexed.

values (boolean | string | number)[]


Optional. A 1-dimensional array of unformatted values of the table row.

Returns
void

Examples

TypeScript

/**
* This script adds a row to an existing table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the current worksheet.
const selectedSheet = workbook.getActiveWorksheet();
const table = selectedSheet.getTables()[0];
// Initialize the data to be added as a table row.
// Note that length of the array must match the number of columns in
the table.
let rowData = ["Carrots", "Vegetable", 750];

// Add a row to the end of the table.


table.addRow(-1, rowData);
}

addRows(index, values)
Adds one or more rows to the table.

TypeScript

addRows(index?: number, values?: (boolean | string | number)[][]): void;

Parameters
index number
Optional. Specifies the relative position of the new row. If null or -1, the addition
happens at the end. Any rows below the inserted row are shifted downwards. Zero-
indexed.

values (boolean | string | number)[][]


Optional. A 2-dimensional array of unformatted values of the table row.

Returns
void

Examples

TypeScript

/**
* This script adds multiple rows to an existing table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the current worksheet.
const selectedSheet = workbook.getActiveWorksheet();
const table = selectedSheet.getTables()[0];

// Initialize the data to be added as table rows.


// Note that length of the array must match the number of columns in
the table.
let rowData = [["Apples", "Fruit", 5000],
["Celery", "Vegetable", 600],
["Onions", "Vegetable", 1500]];

// Add the rows to the end of the table.


table.addRows(-1, rowData);
}

clearFilters()
Clears all the filters currently applied on the table.

TypeScript

clearFilters(): void;

Returns
void

Examples

TypeScript

/**
* This script clears the filters from all tables in the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get all the tables in the workbook.
const tables = workbook.getTables();

// Remove any active filters from each table.


tables.forEach((table) => {
table.clearFilters();
});
}

convertToRange()
Converts the table into a normal range of cells. All data is preserved.

TypeScript
convertToRange(): Range;

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script converts a table to a range and removes the formatting.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the current worksheet.
const selectedSheet = workbook.getActiveWorksheet();
const table = selectedSheet.getTables()[0];

// Convert the table to a range.


const formerTable = table.convertToRange();

// Remove the formatting from the table


formerTable.clear(ExcelScript.ClearApplyTo.formats);
}

delete()
Deletes the table.

TypeScript

delete(): void;

Returns
void

Examples

TypeScript

/**
* This script deletes a table.
* This removes all associated data and formatting.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the table named "Inventory".
const table = workbook.getTable("Inventory");

// Delete the table.


table.delete();
}

deleteRowsAt(index, count)
Delete a specified number of rows at a given index.

TypeScript

deleteRowsAt(index: number, count?: number): void;

Parameters
index number
The index value of the row to be deleted. Caution: the index of the row may have
moved from the time you determined the value to use for removal.

count number
Number of rows to delete. By default, a single row will be deleted. Note: Deleting
more than 1000 rows at the same time could result in a Power Automate timeout.

Returns
void

getAutoFilter()
Represents the AutoFilter object of the table.

TypeScript

getAutoFilter(): AutoFilter;

Returns
ExcelScript.AutoFilter
getColumn(key)
Gets a column object by name or ID. If the column doesn't exist, then this method
returns undefined .

TypeScript

getColumn(key: number | string): TableColumn | undefined;

Parameters
key number | string
Column name or ID.

Returns
ExcelScript.TableColumn | undefined

Examples

TypeScript

/**
* This script adjusts the indentation of a specific table column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the current worksheet.
const selectedSheet = workbook.getActiveWorksheet();
const table = selectedSheet.getTables()[0];

// Get the data range of the second column.


const secondColumn = table.getColumn(2);
const data = secondColumn.getRangeBetweenHeaderAndTotal();

// Add an indentation of 1 character space to the data range.


data.getFormat().adjustIndent(1);
}

getColumnById(key)
Gets a column object by ID. If the column does not exist, will return undefined.

TypeScript
getColumnById(key: number): TableColumn | undefined;

Parameters
key number
Column ID.

Returns
ExcelScript.TableColumn | undefined

getColumnByName(key)
Gets a column object by Name. If the column does not exist, will return undefined.

TypeScript

getColumnByName(key: string): TableColumn | undefined;

Parameters
key string
Column Name.

Returns
ExcelScript.TableColumn | undefined

Examples

TypeScript

/**
* This script removes a specific column from a table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the table named "Inventory".
const table = workbook.getTable("Inventory");

// If it exists, remove the column named "Category".


let categoryColumn = table.getColumnByName("Category");
if (categoryColumn) {
categoryColumn.delete();
}
}

getColumns()
Represents a collection of all the columns in the table.

TypeScript

getColumns(): TableColumn[];

Returns
ExcelScript.TableColumn[]

Examples

TypeScript

/**
* This script adds a new column to a table.
* It then sets the formulas in the new column to be the product
* of the values in the two preceding columns.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the workbook.
const table = workbook.getTables()[0];

// Append an empty column to the table with the header "Total".


const totalColumn = table.addColumn(-1, null, "Total");

// Get the names of the two preceding columns.


const productColumnName1 = table.getColumns()[totalColumn.getIndex() -
1].getName();
const productColumnName2 = table.getColumns()[totalColumn.getIndex() -
2].getName();

// Set the formulas in the "Total" column to be the product of the two
preceding columns.
totalColumn.getRangeBetweenHeaderAndTotal().setFormula(
`=[@[${productColumnName1}]]*[@[${productColumnName2}]]`
);
}

getHeaderRowRange()
Gets the range object associated with the header row of the table.

TypeScript

getHeaderRowRange(): Range;

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script centers the text in a table's header row cells.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const table = currentSheet.getTables()[0];

// Get the header range.


const headerRange = table.getHeaderRowRange();

// Set the horizontal text alignment to `center`.

headerRange.getFormat().setHorizontalAlignment(ExcelScript.HorizontalAlig
nment.center);
}

getHighlightFirstColumn()
Specifies if the first column contains special formatting.

TypeScript

getHighlightFirstColumn(): boolean;

Returns
boolean

getHighlightLastColumn()
Specifies if the last column contains special formatting.

TypeScript

getHighlightLastColumn(): boolean;

Returns
boolean

getId()
Returns a value that uniquely identifies the table in a given workbook. The value of
the identifier remains the same even when the table is renamed.

TypeScript

getId(): string;

Returns
string

getLegacyId()
Returns a numeric ID.

TypeScript

getLegacyId(): string;

Returns
string

getName()
Name of the table.

TypeScript
getName(): string;

Returns
string

getPredefinedTableStyle()
Constant value that represents the table style. Possible values are: "TableStyleLight1"
through "TableStyleLight21", "TableStyleMedium1" through "TableStyleMedium28",
"TableStyleDark1" through "TableStyleDark11". A custom user-defined style present
in the workbook can also be specified.

TypeScript

getPredefinedTableStyle(): string;

Returns
string

getRange()
Gets the range object associated with the entire table.

TypeScript

getRange(): Range;

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script removes any extra formatting that's been applied to a
table.
* This leaves only the base table style effects.
* Any formatting outside of the table will be left as is.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
let worksheet = workbook.getActiveWorksheet();
let table = worksheet.getTables()[0];

// Get the range used by the table.


let range = table.getRange();

// Clear all the formatting that is not applied by the table and the
table style.
range.clear(ExcelScript.ClearApplyTo.formats);
}

getRangeBetweenHeaderAndTotal()
Gets the range object associated with the data body of the table.

TypeScript

getRangeBetweenHeaderAndTotal(): Range;

Returns
ExcelScript.Range

getRowCount()
Gets the number of rows in the table.

TypeScript

getRowCount(): number;

Returns
number

getShowBandedColumns()
Specifies if the columns show banded formatting in which odd columns are
highlighted differently from even ones, to make reading the table easier.
TypeScript

getShowBandedColumns(): boolean;

Returns
boolean

getShowBandedRows()
Specifies if the rows show banded formatting in which odd rows are highlighted
differently from even ones, to make reading the table easier.

TypeScript

getShowBandedRows(): boolean;

Returns
boolean

getShowFilterButton()
Specifies if the filter buttons are visible at the top of each column header. Setting this
is only allowed if the table contains a header row.

TypeScript

getShowFilterButton(): boolean;

Returns
boolean

getShowHeaders()
Specifies if the header row is visible. This value can be set to show or remove the
header row.

TypeScript
getShowHeaders(): boolean;

Returns
boolean

getShowTotals()
Specifies if the total row is visible. This value can be set to show or remove the total
row.

TypeScript

getShowTotals(): boolean;

Returns
boolean

getSort()
Represents the sorting for the table.

TypeScript

getSort(): TableSort;

Returns
ExcelScript.TableSort

getTotalRowRange()
Gets the range object associated with the totals row of the table.

TypeScript

getTotalRowRange(): Range;

Returns
ExcelScript.Range

getWorksheet()
The worksheet containing the current table.

TypeScript

getWorksheet(): Worksheet;

Returns
ExcelScript.Worksheet

reapplyFilters()
Reapplies all the filters currently on the table.

TypeScript

reapplyFilters(): void;

Returns
void

Examples

TypeScript

/**
* This script reapplies the filters on every table in the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get all the tables.
const tables = workbook.getTables();

// Iterate over every table.


tables.forEach((table) => {
// Reapply the filters to account for new table entries.
table.reapplyFilters();
});
}
resize(newRange)
Resize the table to the new range. The new range must overlap with the original
table range and the headers (or the top of the table) must be in the same row.

TypeScript

resize(newRange: Range | string): void;

Parameters
newRange ExcelScript.Range | string
The range object or range address that will be used to determine the new size of the
table.

Returns
void

setHighlightFirstColumn(highlightFirstColumn)
Specifies if the first column contains special formatting.

TypeScript

setHighlightFirstColumn(highlightFirstColumn: boolean): void;

Parameters
highlightFirstColumn boolean

Returns
void

setHighlightLastColumn(highlightLastColumn)
Specifies if the last column contains special formatting.

TypeScript
setHighlightLastColumn(highlightLastColumn: boolean): void;

Parameters
highlightLastColumn boolean

Returns
void

setName(name)
Name of the table.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

setPredefinedTableStyle(predefinedTableStyle)
Constant value that represents the table style. Possible values are: "TableStyleLight1"
through "TableStyleLight21", "TableStyleMedium1" through "TableStyleMedium28",
"TableStyleDark1" through "TableStyleDark11". A custom user-defined style present
in the workbook can also be specified.

TypeScript

setPredefinedTableStyle(predefinedTableStyle: string): void;

Parameters
predefinedTableStyle string
Returns
void

setShowBandedColumns(showBandedColumns)
Specifies if the columns show banded formatting in which odd columns are
highlighted differently from even ones, to make reading the table easier.

TypeScript

setShowBandedColumns(showBandedColumns: boolean): void;

Parameters
showBandedColumns boolean

Returns
void

setShowBandedRows(showBandedRows)
Specifies if the rows show banded formatting in which odd rows are highlighted
differently from even ones, to make reading the table easier.

TypeScript

setShowBandedRows(showBandedRows: boolean): void;

Parameters
showBandedRows boolean

Returns
void

Examples

TypeScript
/**
* This script sets all the tables in the workbook to have banded rows.
*/
function main(workbook: ExcelScript.Workbook) {
// Get all the tables.
const tables = workbook.getTables();

// For each table, set the banded row formatting to true.


tables.forEach((table) => {
table.setShowBandedRows(true);
});
}

setShowFilterButton(showFilterButton)
Specifies if the filter buttons are visible at the top of each column header. Setting this
is only allowed if the table contains a header row.

TypeScript

setShowFilterButton(showFilterButton: boolean): void;

Parameters
showFilterButton boolean

Returns
void

setShowHeaders(showHeaders)
Specifies if the header row is visible. This value can be set to show or remove the
header row.

TypeScript

setShowHeaders(showHeaders: boolean): void;

Parameters
showHeaders boolean
Returns
void

Examples

TypeScript

/**
* This script makes a table's headers not visible in the grid.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the table named "CoverageTable".
const coverageTable = workbook.getTable("CoverageTable");

// Make the header row not visible.


coverageTable.setShowHeaders(false);
}

setShowTotals(showTotals)
Specifies if the total row is visible. This value can be set to show or remove the total
row.

TypeScript

setShowTotals(showTotals: boolean): void;

Parameters
showTotals boolean

Returns
void

Examples

TypeScript

/**
* This script adds the Total Row to an existing table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the current worksheet.
const selectedSheet = workbook.getActiveWorksheet();
const table = selectedSheet.getTables()[0];

// Set the Total Row to show.


table.setShowTotals(true);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.TableColumn interface
Reference
Package: ExcelScript

Represents a column in a table.

Remarks

Examples

TypeScript

/**
* This script shows how to get the range of a table column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the workbook.
const table = workbook.getTables()[0];

// Get the range of the table column named "Type".


const typeColumn : ExcelScript.TableColumn = table.getColumn("Type");
const range = typeColumn.getRange();

// Do something with the range...


}

Methods
ノ Expand table

delete() Deletes the column from the table.

getFilter() Retrieves the filter applied to the column.

getHeaderRowRange() Gets the range object associated with the header row of the
column.

getId() Returns a unique key that identifies the column within the table.

getIndex() Returns the index number of the column within the columns
collection of the table. Zero-indexed.

getName() Specifies the name of the table column.


getRange() Gets the range object associated with the entire column.

getRangeBetweenHeader Gets the range object associated with the data body of the column.
AndTotal()

getTotalRowRange() Gets the range object associated with the totals row of the column.

setName(name) Specifies the name of the table column.

Method Details

delete()
Deletes the column from the table.

TypeScript

delete(): void;

Returns
void

Examples

TypeScript

/**
* This script removes a specific column from a table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the table named "Inventory".
const table = workbook.getTable("Inventory");

// If it exists, remove the column named "Category".


let categoryColumn = table.getColumnByName("Category");
if (categoryColumn) {
categoryColumn.delete();
}
}

getFilter()
Retrieves the filter applied to the column.
TypeScript

getFilter(): Filter;

Returns
ExcelScript.Filter

Examples

TypeScript

/**
* This script adds a table filter to only show the top 10% of values
* belonging to a particular column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table on the current worksheet.
const table = workbook.getActiveWorksheet().getTables()[0];

// Get the filter for the "PageViews" table column.


const pageViewFilter =
table.getColumnByName("PageViews").getFilter();

// Apply a filter to only show the rows with the top 10% of values in
this column.
pageViewFilter.applyTopPercentFilter(10);
}

getHeaderRowRange()
Gets the range object associated with the header row of the column.

TypeScript

getHeaderRowRange(): Range;

Returns
ExcelScript.Range

getId()
Returns a unique key that identifies the column within the table.
TypeScript

getId(): number;

Returns
number

getIndex()
Returns the index number of the column within the columns collection of the table.
Zero-indexed.

TypeScript

getIndex(): number;

Returns
number

getName()
Specifies the name of the table column.

TypeScript

getName(): string;

Returns
string

getRange()
Gets the range object associated with the entire column.

TypeScript

getRange(): Range;
Returns
ExcelScript.Range

getRangeBetweenHeaderAndTotal()
Gets the range object associated with the data body of the column.

TypeScript

getRangeBetweenHeaderAndTotal(): Range;

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script adds a new column to a table.
* It then sets the formulas in the new column to be the product
* of the values in the two preceding columns.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first table in the workbook.
const table = workbook.getTables()[0];

// Append an empty column to the table with the header "Total".


const totalColumn = table.addColumn(-1, null, "Total");

// Get the names of the two preceding columns.


const productColumnName1 = table.getColumns()[totalColumn.getIndex() -
1].getName();
const productColumnName2 = table.getColumns()[totalColumn.getIndex() -
2].getName();

// Set the formulas in the "Total" column to be the product of the two
preceding columns.
totalColumn.getRangeBetweenHeaderAndTotal().setFormula(
`=[@[${productColumnName1}]]*[@[${productColumnName2}]]`
);
}

getTotalRowRange()
Gets the range object associated with the totals row of the column.

TypeScript

getTotalRowRange(): Range;

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script logs the value in the total row of a table column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the table named "Cities".
const table = workbook.getTable("Cities");

// Get the total row from the "Population" column.


const column = table.getColumn("Population");
const totalRange = column.getTotalRowRange();

// Log the total value.


console.log(totalRange.getValue());
}

setName(name)
Specifies the name of the table column.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void
Examples

TypeScript

/**
* This script renames a column in an existing table.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the "Employee" table.
const employeeTable = workbook.getTable("Employee");

// Rename a column from "EmplID" to "Employee ID".


const idColumn = employeeTable.getColumnByName("EmplID");
idColumn.setName("Employee ID");
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.TableSort interface
Reference
Package: ExcelScript

Manages sorting operations on Table objects.

Methods
ノ Expand table

apply(fields, match Perform a sort operation.


Case, method)

clear() Clears the sorting that is currently on the table. While this doesn't modify
the table's ordering, it clears the state of the header buttons.

getFields() Specifies the current conditions used to last sort the table.

getMatchCase() Specifies if the casing impacts the last sort of the table.

getMethod() Represents the Chinese character ordering method last used to sort the
table.

reapply() Reapplies the current sorting parameters to the table.

Method Details

apply(fields, matchCase, method)


Perform a sort operation.

TypeScript

apply(
fields: SortField[],
matchCase?: boolean,
method?: SortMethod
): void;

Parameters
fields ExcelScript.SortField[]
The list of conditions to sort on.

matchCase boolean
Optional. Whether to have the casing impact string ordering.

method ExcelScript.SortMethod
Optional. The ordering method used for Chinese characters.

Returns
void

Examples

TypeScript

/**
* This sample creates a table from the current worksheet's used range,
then sorts it based on the first column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Create a table with the used cells.


let usedRange = selectedSheet.getUsedRange();
let newTable = selectedSheet.addTable(usedRange, true);

// Sort the table using the first column.


newTable.getSort().apply([{ key: 0, ascending: true }]);
}

clear()
Clears the sorting that is currently on the table. While this doesn't modify the table's
ordering, it clears the state of the header buttons.

TypeScript

clear(): void;

Returns
void
getFields()
Specifies the current conditions used to last sort the table.

TypeScript

getFields(): SortField[];

Returns
ExcelScript.SortField[]

getMatchCase()
Specifies if the casing impacts the last sort of the table.

TypeScript

getMatchCase(): boolean;

Returns
boolean

getMethod()
Represents the Chinese character ordering method last used to sort the table.

TypeScript

getMethod(): SortMethod;

Returns
ExcelScript.SortMethod

reapply()
Reapplies the current sorting parameters to the table.

TypeScript
reapply(): void;

Returns
void

Examples

TypeScript

/**
* This script reapplies all the current sorting criteria to existing
tables.
*/
function main(workbook: ExcelScript.Workbook) {
// Get all the tables.
const tables = workbook.getTables();

// For each table, reapply that table's current sorting parameters.


tables.forEach((table) => {
const sort: ExcelScript.TableSort = table.getSort();
sort.reapply();
});
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.TableStyle interface
Reference
Package: ExcelScript

Represents a table style, which defines the style elements by region of the table.

Methods
ノ Expand table

delete() Deletes the table style.

duplicate() Creates a duplicate of this table style with copies of all the style elements.

getName() Specifies the name of the table style.

getReadOnly() Specifies if this TableStyle object is read-only.

setName(name) Specifies the name of the table style.

Method Details

delete()
Deletes the table style.

TypeScript

delete(): void;

Returns
void

duplicate()
Creates a duplicate of this table style with copies of all the style elements.

TypeScript
duplicate(): TableStyle;

Returns
ExcelScript.TableStyle

getName()
Specifies the name of the table style.

TypeScript

getName(): string;

Returns
string

getReadOnly()
Specifies if this TableStyle object is read-only.

TypeScript

getReadOnly(): boolean;

Returns
boolean

setName(name)
Specifies the name of the table style.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.TextConditionalFormat
interface
Reference
Package: ExcelScript

Represents a specific text conditional format.

Remarks

Examples

TypeScript

/**
* This script adds conditional formatting to the first column in the
worksheet.
* This formatting gives the cells a green fill if they have text starting
with "Excel".
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first column in the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const firstColumn = currentSheet.getRange("A:A");

// Add conditional formatting based on the text in the cells.


const textConditionFormat: ExcelScript.TextConditionalFormat =

firstColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.containsT
ext).getTextComparison();

// Set the conditional format to provide a green fill.


textConditionFormat.getFormat().getFill().setColor("green");

// Apply the condition rule that the text begins with "Excel".
const textRule: ExcelScript.ConditionalTextComparisonRule = {
operator: ExcelScript.ConditionalTextOperator.beginsWith,
text: "Excel"
};
textConditionFormat.setRule(textRule);
}

Methods
ノ Expand table

getFormat() Returns a format object, encapsulating the conditional format's font, fill, borders,
and other properties.

getRule() The rule of the conditional format.

set The rule of the conditional format.


Rule(rule)

Method Details

getFormat()
Returns a format object, encapsulating the conditional format's font, fill, borders, and
other properties.

TypeScript

getFormat(): ConditionalRangeFormat;

Returns
ExcelScript.ConditionalRangeFormat

getRule()
The rule of the conditional format.

TypeScript

getRule(): ConditionalTextComparisonRule;

Returns
ExcelScript.ConditionalTextComparisonRule

setRule(rule)
The rule of the conditional format.

TypeScript
setRule(rule: ConditionalTextComparisonRule): void;

Parameters
rule ExcelScript.ConditionalTextComparisonRule

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.TextFrame interface
Reference
Package: ExcelScript

Represents the text frame of a shape object.

Remarks

Examples

TypeScript

/**
* This script creates a star shape with the value from cell A1.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the value of A1 from the worksheet named Sheet1.
const sheet = workbook.getWorksheet("Sheet1");
const value = sheet.getRange("A1").getValue();

// Create a Shape object that looks like a 5-pointed star.


const star =
sheet.addGeometricShape(ExcelScript.GeometricShapeType.star5);

// Set the text of star and make sure the shape fits the text.
const textFrame: ExcelScript.TextFrame = star.getTextFrame();
textFrame.getTextRange().setText(value.toString());

textFrame.setAutoSizeSetting(ExcelScript.ShapeAutoSize.autoSizeShapeToFitTex
t);
}

Methods
ノ Expand table

deleteText() Deletes all the text in the text frame.

getAutoSizeSetting() The automatic sizing settings for the text frame. A text frame can be
set to automatically fit the text to the text frame, to automatically fit
the text frame to the text, or not perform any automatic sizing.

getBottomMargin() Represents the bottom margin, in points, of the text frame.


getHasText() Specifies if the text frame contains text.

getHorizontalAlignment() Represents the horizontal alignment of the text frame. See


ExcelScript.ShapeTextHorizontalAlignment for details.

getHorizontalOverflow() Represents the horizontal overflow behavior of the text frame. See
ExcelScript.ShapeTextHorizontalOverflow for details.

getLeftMargin() Represents the left margin, in points, of the text frame.

getOrientation() Represents the angle to which the text is oriented for the text frame.
See ExcelScript.ShapeTextOrientation for details.

getReadingOrder() Represents the reading order of the text frame, either left-to-right
or right-to-left. See ExcelScript.ShapeTextReadingOrder for details.

getRightMargin() Represents the right margin, in points, of the text frame.

getTextRange() Represents the text that is attached to a shape in the text frame, and
properties and methods for manipulating the text. See
ExcelScript.TextRange for details.

getTopMargin() Represents the top margin, in points, of the text frame.

getVerticalAlignment() Represents the vertical alignment of the text frame. See


ExcelScript.ShapeTextVerticalAlignment for details.

getVerticalOverflow() Represents the vertical overflow behavior of the text frame. See
ExcelScript.ShapeTextVerticalOverflow for details.

setAutoSizeSetting(auto The automatic sizing settings for the text frame. A text frame can be
SizeSetting) set to automatically fit the text to the text frame, to automatically fit
the text frame to the text, or not perform any automatic sizing.

setBottomMargin(bottom Represents the bottom margin, in points, of the text frame.


Margin)

setHorizontal Represents the horizontal alignment of the text frame. See


Alignment(horizontal ExcelScript.ShapeTextHorizontalAlignment for details.
Alignment)

setHorizontal Represents the horizontal overflow behavior of the text frame. See
Overflow(horizontal ExcelScript.ShapeTextHorizontalOverflow for details.
Overflow)

setLeftMargin(leftMargin) Represents the left margin, in points, of the text frame.

setOrientation(orientation) Represents the angle to which the text is oriented for the text frame.
See ExcelScript.ShapeTextOrientation for details.

setReadingOrder(reading Represents the reading order of the text frame, either left-to-right
Order) or right-to-left. See ExcelScript.ShapeTextReadingOrder for details.
setRightMargin(right Represents the right margin, in points, of the text frame.
Margin)

setTopMargin(topMargin) Represents the top margin, in points, of the text frame.

setVertical Represents the vertical alignment of the text frame. See


Alignment(vertical ExcelScript.ShapeTextVerticalAlignment for details.
Alignment)

setVerticalOverflow(vertical Represents the vertical overflow behavior of the text frame. See
Overflow) ExcelScript.ShapeTextVerticalOverflow for details.

Method Details

deleteText()
Deletes all the text in the text frame.

TypeScript

deleteText(): void;

Returns
void

getAutoSizeSetting()
The automatic sizing settings for the text frame. A text frame can be set to
automatically fit the text to the text frame, to automatically fit the text frame to the
text, or not perform any automatic sizing.

TypeScript

getAutoSizeSetting(): ShapeAutoSize;

Returns
ExcelScript.ShapeAutoSize

getBottomMargin()
Represents the bottom margin, in points, of the text frame.

TypeScript

getBottomMargin(): number;

Returns
number

getHasText()
Specifies if the text frame contains text.

TypeScript

getHasText(): boolean;

Returns
boolean

getHorizontalAlignment()
Represents the horizontal alignment of the text frame. See
ExcelScript.ShapeTextHorizontalAlignment for details.

TypeScript

getHorizontalAlignment(): ShapeTextHorizontalAlignment;

Returns
ExcelScript.ShapeTextHorizontalAlignment

getHorizontalOverflow()
Represents the horizontal overflow behavior of the text frame. See
ExcelScript.ShapeTextHorizontalOverflow for details.

TypeScript
getHorizontalOverflow(): ShapeTextHorizontalOverflow;

Returns
ExcelScript.ShapeTextHorizontalOverflow

getLeftMargin()
Represents the left margin, in points, of the text frame.

TypeScript

getLeftMargin(): number;

Returns
number

getOrientation()
Represents the angle to which the text is oriented for the text frame. See
ExcelScript.ShapeTextOrientation for details.

TypeScript

getOrientation(): ShapeTextOrientation;

Returns
ExcelScript.ShapeTextOrientation

getReadingOrder()
Represents the reading order of the text frame, either left-to-right or right-to-left.
See ExcelScript.ShapeTextReadingOrder for details.

TypeScript

getReadingOrder(): ShapeTextReadingOrder;
Returns
ExcelScript.ShapeTextReadingOrder

getRightMargin()
Represents the right margin, in points, of the text frame.

TypeScript

getRightMargin(): number;

Returns
number

getTextRange()
Represents the text that is attached to a shape in the text frame, and properties and
methods for manipulating the text. See ExcelScript.TextRange for details.

TypeScript

getTextRange(): TextRange;

Returns
ExcelScript.TextRange

getTopMargin()
Represents the top margin, in points, of the text frame.

TypeScript

getTopMargin(): number;

Returns
number
getVerticalAlignment()
Represents the vertical alignment of the text frame. See
ExcelScript.ShapeTextVerticalAlignment for details.

TypeScript

getVerticalAlignment(): ShapeTextVerticalAlignment;

Returns
ExcelScript.ShapeTextVerticalAlignment

getVerticalOverflow()
Represents the vertical overflow behavior of the text frame. See
ExcelScript.ShapeTextVerticalOverflow for details.

TypeScript

getVerticalOverflow(): ShapeTextVerticalOverflow;

Returns
ExcelScript.ShapeTextVerticalOverflow

setAutoSizeSetting(autoSizeSetting)
The automatic sizing settings for the text frame. A text frame can be set to
automatically fit the text to the text frame, to automatically fit the text frame to the
text, or not perform any automatic sizing.

TypeScript

setAutoSizeSetting(autoSizeSetting: ShapeAutoSize): void;

Parameters
autoSizeSetting ExcelScript.ShapeAutoSize

Returns
void

setBottomMargin(bottomMargin)
Represents the bottom margin, in points, of the text frame.

TypeScript

setBottomMargin(bottomMargin: number): void;

Parameters
bottomMargin number

Returns
void

setHorizontalAlignment(horizontalAlignment)
Represents the horizontal alignment of the text frame. See
ExcelScript.ShapeTextHorizontalAlignment for details.

TypeScript

setHorizontalAlignment(
horizontalAlignment: ShapeTextHorizontalAlignment
): void;

Parameters
horizontalAlignment ExcelScript.ShapeTextHorizontalAlignment

Returns
void

setHorizontalOverflow(horizontalOverflow)
Represents the horizontal overflow behavior of the text frame. See
ExcelScript.ShapeTextHorizontalOverflow for details.
TypeScript

setHorizontalOverflow(
horizontalOverflow: ShapeTextHorizontalOverflow
): void;

Parameters
horizontalOverflow ExcelScript.ShapeTextHorizontalOverflow

Returns
void

setLeftMargin(leftMargin)
Represents the left margin, in points, of the text frame.

TypeScript

setLeftMargin(leftMargin: number): void;

Parameters
leftMargin number

Returns
void

setOrientation(orientation)
Represents the angle to which the text is oriented for the text frame. See
ExcelScript.ShapeTextOrientation for details.

TypeScript

setOrientation(orientation: ShapeTextOrientation): void;

Parameters
orientation ExcelScript.ShapeTextOrientation
Returns
void

setReadingOrder(readingOrder)
Represents the reading order of the text frame, either left-to-right or right-to-left.
See ExcelScript.ShapeTextReadingOrder for details.

TypeScript

setReadingOrder(readingOrder: ShapeTextReadingOrder): void;

Parameters
readingOrder ExcelScript.ShapeTextReadingOrder

Returns
void

setRightMargin(rightMargin)
Represents the right margin, in points, of the text frame.

TypeScript

setRightMargin(rightMargin: number): void;

Parameters
rightMargin number

Returns
void

setTopMargin(topMargin)
Represents the top margin, in points, of the text frame.

TypeScript
setTopMargin(topMargin: number): void;

Parameters
topMargin number

Returns
void

setVerticalAlignment(verticalAlignment)
Represents the vertical alignment of the text frame. See
ExcelScript.ShapeTextVerticalAlignment for details.

TypeScript

setVerticalAlignment(
verticalAlignment: ShapeTextVerticalAlignment
): void;

Parameters
verticalAlignment ExcelScript.ShapeTextVerticalAlignment

Returns
void

setVerticalOverflow(verticalOverflow)
Represents the vertical overflow behavior of the text frame. See
ExcelScript.ShapeTextVerticalOverflow for details.

TypeScript

setVerticalOverflow(verticalOverflow: ShapeTextVerticalOverflow): void;

Parameters
verticalOverflow ExcelScript.ShapeTextVerticalOverflow
Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.TextRange interface
Reference
Package: ExcelScript

Contains the text that is attached to a shape, in addition to properties and methods for
manipulating the text.

Remarks

Examples

TypeScript

/**
* This script adds text to a shape.
*/
function main(workbook: ExcelScript.Workbook) {
// Create a hexagon shape in the current worksheet.
const sheet = workbook.getActiveWorksheet();
const hexagon =
sheet.addGeometricShape(ExcelScript.GeometricShapeType.hexagon);

// Set the text of the shape.


const hexText: ExcelScript.TextRange =
hexagon.getTextFrame().getTextRange();
hexText.setText("Forest");
}

Methods
ノ Expand table

getFont() Returns a ShapeFont object that represents the font attributes for the
text range.

getSubstring(start, Returns a TextRange object for the substring in the given range.
length)

getText() Represents the plain text content of the text range.

setText(text) Represents the plain text content of the text range.


Method Details

getFont()
Returns a ShapeFont object that represents the font attributes for the text range.

TypeScript

getFont(): ShapeFont;

Returns
ExcelScript.ShapeFont

Examples

TypeScript

/**
* This sample sets the font of a shape to be bold.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first shape in the current worksheet.
const sheet = workbook.getActiveWorksheet();
const shape = sheet.getShapes()[0];

// Get the text font from the shape.


const text: ExcelScript.TextRange =
shape.getTextFrame().getTextRange();
const shapeTextFont: ExcelScript.ShapeFont = text.getFont();

// Set the font to be bold.


shapeTextFont.setBold(true);
}

getSubstring(start, length)
Returns a TextRange object for the substring in the given range.

TypeScript

getSubstring(start: number, length?: number): TextRange;


Parameters
start number
The zero-based index of the first character to get from the text range.

length number
Optional. The number of characters to be returned in the new text range. If length is
omitted, all the characters from start to the end of the text range's last paragraph
will be returned.

Returns
ExcelScript.TextRange

getText()
Represents the plain text content of the text range.

TypeScript

getText(): string;

Returns
string

Examples

TypeScript

/**
* This script writes all the text from the workbook's geometric shapes
in a new worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Create a new worksheet.
const shapeTextSheet = workbook.addWorksheet("ShapeText");
let shapeTextValues: string[][] = [];

// Get the text from every geometric shape in every worksheet.


workbook.getWorksheets().forEach((sheet) => {
sheet.getShapes().forEach((shape) => {
if (shape.getType() === ExcelScript.ShapeType.geometricShape)
shapeTextValues.push([
sheet.getName(),
shape.getGeometricShapeType().toString(),
shape.getTextFrame().getTextRange().getText()]);
});
});

// Add the text to the new worksheet.


const range = shapeTextSheet.getRangeByIndexes(
0,
0,
shapeTextValues.length,
shapeTextValues[0].length);
range.setValues(shapeTextValues);
}

setText(text)
Represents the plain text content of the text range.

TypeScript

setText(text: string): void;

Parameters
text string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
be found on GitHub, where you Select a link to provide feedback:
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.TimelineStyle interface
Reference
Package: ExcelScript

Represents a TimelineStyle , which defines style elements by region in the timeline.

Methods
ノ Expand table

delete() Deletes the table style.

duplicate() Creates a duplicate of this timeline style with copies of all the style elements.

getName() Specifies the name of the timeline style.

getReadOnly() Specifies if this TimelineStyle object is read-only.

setName(name) Specifies the name of the timeline style.

Method Details

delete()
Deletes the table style.

TypeScript

delete(): void;

Returns
void

duplicate()
Creates a duplicate of this timeline style with copies of all the style elements.

TypeScript
duplicate(): TimelineStyle;

Returns
ExcelScript.TimelineStyle

getName()
Specifies the name of the timeline style.

TypeScript

getName(): string;

Returns
string

getReadOnly()
Specifies if this TimelineStyle object is read-only.

TypeScript

getReadOnly(): boolean;

Returns
boolean

setName(name)
Specifies the name of the timeline style.

TypeScript

setName(name: string): void;

Parameters
name string

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.TopBottomConditional
Format interface
Reference
Package: ExcelScript

Represents a top/bottom conditional format.

Remarks

Examples

TypeScript

/**
* This sample applies conditional formatting to the currently used range in
the worksheet.
* The conditional formatting is a green fill for the top 10% of values.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get the used range in the worksheet.


let range = selectedSheet.getUsedRange();

// Set the fill color to green for the top 10% of values in the range.
let conditionalFormat =
range.addConditionalFormat(ExcelScript.ConditionalFormatType.topBottom)
conditionalFormat.getTopBottom().getFormat().getFill().setColor("green");
conditionalFormat.getTopBottom().setRule({
rank: 10, /* The percentage threshold. */
type: ExcelScript.ConditionalTopBottomCriterionType.topPercent /* The
type of the top/bottom condition. */
});
}

Methods
ノ Expand table

getFormat() Returns a format object, encapsulating the conditional format's font, fill, borders,
and other properties.
getRule() The criteria of the top/bottom conditional format.

set The criteria of the top/bottom conditional format.


Rule(rule)

Method Details

getFormat()
Returns a format object, encapsulating the conditional format's font, fill, borders, and
other properties.

TypeScript

getFormat(): ConditionalRangeFormat;

Returns
ExcelScript.ConditionalRangeFormat

getRule()
The criteria of the top/bottom conditional format.

TypeScript

getRule(): ConditionalTopBottomRule;

Returns
ExcelScript.ConditionalTopBottomRule

setRule(rule)
The criteria of the top/bottom conditional format.

TypeScript

setRule(rule: ConditionalTopBottomRule): void;


Parameters
rule ExcelScript.ConditionalTopBottomRule

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Workbook interface
Reference
Package: ExcelScript

Workbook is the top level object which contains related workbook objects such as
worksheets, tables, and ranges.

Remarks

Examples

TypeScript

/**
* This script adds a new worksheet to the workbook, then switches to it.
*/
function main(workbook: ExcelScript.Workbook) {
// Add a new worksheet with the default name.
let worksheet = workbook.addWorksheet();

// Switch focus to the new worksheet.


worksheet.activate();
}

Methods
ノ Expand table

addBinding(range, bindingType, Add a new binding to a particular Range.


id)

addBindingFromNamed Add a new binding based on a named item in the workbook. If


Item(name, bindingType, id) the named item references to multiple areas, the
InvalidReference error will be returned.

addBindingFrom Add a new binding based on the current selection. If the


Selection(bindingType, id) selection has multiple areas, the InvalidReference error will
be returned.

addComment(cellAddress, Creates a new comment with the given content on the given
content, contentType) cell. An InvalidArgument error is thrown if the provided range
is larger than one cell.
addCustomXmlPart(xml) Adds a new custom XML part to the workbook.

addNamedItem(name, reference, Adds a new name to the collection of the given scope.
comment)

addNamedItemFormula Adds a new name to the collection of the given scope using
Local(name, formula, comment) the user's locale for the formula.

addPivotTable(name, source, Add a PivotTable based on the specified source data and insert
destination) it at the top-left cell of the destination range.

addPivotTableStyle(name, make Creates a blank PivotTableStyle with the specified name.


UniqueName)

addPredefinedCellStyle(name) Adds a new style to the collection.

addSlicer(slicerSource, source Adds a new slicer to the workbook.


Field, slicerDestination)

addSlicerStyle(name, make Creates a blank slicer style with the specified name.
UniqueName)

addTable(address, hasHeaders) Creates a new table. The range object or source address
determines the worksheet under which the table will be
added. If the table cannot be added (e.g., because the address
is invalid, or the table would overlap with another table), an
error will be thrown.

addTableStyle(name, make Creates a blank TableStyle with the specified name.


UniqueName)

addTimelineStyle(name, make Creates a blank TimelineStyle with the specified name.


UniqueName)

addWorksheet(name) Adds a new worksheet to the workbook. The worksheet will be


added at the end of existing worksheets. If you wish to
activate the newly added worksheet, call .activate() on it.

breakAllLinksToLinked Breaks all the links to the linked workbooks. Once the links are
Workbooks() broken, any formulas referencing workbook links are removed
entirely and replaced with the most recently retrieved values.

getActiveCell() Gets the currently active cell from the workbook.

getActiveChart() Gets the currently active chart in the workbook. If there is no


active chart, then this method returns undefined .

getActiveSlicer() Gets the currently active slicer in the workbook. If there is no


active slicer, then this method returns undefined .

getActiveWorksheet() Gets the currently active worksheet in the workbook.


getApplication() Represents the Excel application instance that contains this
workbook.

getAutoSave() Specifies if the workbook is in AutoSave mode.

getBinding(id) Gets a binding object by ID. If the binding object does not
exist, then this method returns undefined .

getBindings() Represents a collection of bindings that are part of the


workbook.

getCalculationEngineVersion() Returns a number about the version of Excel Calculation


Engine.

getChartDataPointTrack() True if all charts in the workbook are tracking the actual data
points to which they are attached. False if the charts track the
index of the data points.

getComment(commentId) Gets a comment from the collection based on its ID. If the
comment object does not exist, then this method returns
undefined .

getCommentByCell(cellAddress) Gets the comment from the specified cell. If there is no


comment in the cell, an error is thrown.

getCommentByReplyId(replyId) Gets the comment to which the given reply is connected.

getComments() Represents a collection of comments associated with the


workbook.

getCustomXmlPart(id) Gets a custom XML part based on its ID. If the CustomXmlPart
does not exist, then this method returns undefined .

getCustomXmlPart Gets a new collection of custom XML parts whose namespaces


ByNamespace(namespaceUri) match the given namespace.

getCustomXmlParts() Represents the collection of custom XML parts contained by


this workbook.

getCustomXmlParts Gets a new collection of custom XML parts whose namespaces


ByNamespace(namespaceUri) match the given namespace.

getDefaultPivotTableStyle() Gets the default PivotTable style for the parent object's scope.

getDefaultSlicerStyle() Gets the default SlicerStyle for the parent object's scope.

getDefaultTableStyle() Gets the default table style for the parent object's scope.

getDefaultTimelineStyle() Gets the default timeline style for the parent object's scope.

getFirstWorksheet(visibleOnly) Gets the first worksheet in the collection.


getIsDirty() Specifies if changes have been made since the workbook was
last saved. You can set this property to true if you want to
close a modified workbook without either saving it or being
prompted to save it.

getLastWorksheet(visibleOnly) Gets the last worksheet in the collection.

getLinkedWorkbookByUrl(key) Gets information about a linked workbook by its URL. If the


workbook does not exist, then this method returns undefined .

getLinkedWorkbookRefresh Represents the update mode of the workbook links. The mode
Mode() is same for all of the workbook links present in the workbook.

getLinkedWorkbooks() Returns a collection of linked workbooks. In formulas, the


workbook links can be used to reference data (cell values and
names) outside of the current workbook.

getName() Gets the workbook name.

getNamedItem(name) Gets a NamedItem object using its name. If the object does not
exist, then this method returns undefined .

getNames() Represents a collection of workbook-scoped named items


(named ranges and constants).

getPivotTable(name) Gets a PivotTable by name. If the PivotTable does not exist,


then this method returns undefined .

getPivotTables() Represents a collection of PivotTables associated with the


workbook.

getPivotTableStyle(name) Gets a PivotTableStyle by name. If the PivotTableStyle does


not exist, then this method returns undefined .

getPivotTableStyles() Represents a collection of PivotTableStyles associated with the


workbook.

getPredefinedCellStyle(name) Gets a style by name. If the style object does not exist, then
this method returns undefined .

getPredefinedCellStyles() Represents a collection of styles associated with the


workbook.

getPreviouslySaved() Specifies if the workbook has ever been saved locally or


online.

getProperties() Gets the workbook properties.

getProtection() Returns the protection object for a workbook.

getQueries() Returns a collection of Power Query queries that are part of


the workbook.
getQuery(key) Gets a query from the collection based on its name.

getReadOnly() Returns true if the workbook is open in read-only mode.

getSelectedRange() Gets the currently selected single range from the workbook. If
there are multiple ranges selected, this method will throw an
error.

getSelectedRanges() Gets the currently selected one or more ranges from the
workbook. Unlike getSelectedRange() , this method returns a
RangeAreas object that represents all the selected ranges.

getSlicer(key) Gets a slicer using its name or ID. If the slicer doesn't exist,
then this method returns undefined .

getSlicers() Represents a collection of slicers associated with the


workbook.

getSlicerStyle(name) Gets a SlicerStyle by name. If the slicer style doesn't exist,


then this method returns undefined .

getSlicerStyles() Represents a collection of SlicerStyles associated with the


workbook.

getTable(key) Gets a table by name or ID. If the table doesn't exist, then this
method returns undefined .

getTables() Represents a collection of tables associated with the


workbook.

getTableStyle(name) Gets a TableStyle by name. If the table style does not exist,
then this method returns undefined .

getTableStyles() Represents a collection of TableStyles associated with the


workbook.

getTimelineStyle(name) Gets a TimelineStyle by name. If the timeline style doesn't


exist, then this method returns undefined .

getTimelineStyles() Represents a collection of TimelineStyles associated with the


workbook.

getUsePrecisionAsDisplayed() True if calculations in this workbook will be done using only


the precision of the numbers as they're displayed. Data will
permanently lose accuracy when switching this property from
false to true .

getWorksheet(key) Gets a worksheet object using its name or ID. If the worksheet
does not exist, then this method returns undefined .

getWorksheets() Represents a collection of worksheets associated with the


workbook.

refreshAllDataConnections() Refreshes all the Data Connections.

refreshAllLinksToLinked Makes a request to refresh all the workbook links.


Workbooks()

refreshAllPivotTables() Refreshes all the pivot tables in the collection.

setChartDataPointTrack(chart True if all charts in the workbook are tracking the actual data
DataPointTrack) points to which they are attached. False if the charts track the
index of the data points.

setDefaultPivotTableStyle(new Sets the default PivotTable style for use in the parent object's
DefaultStyle) scope.

setDefaultSlicerStyle(newDefault Sets the default slicer style for use in the parent object's
Style) scope.

setDefaultTableStyle(newDefault Sets the default table style for use in the parent object's scope.
Style)

setDefaultTimelineStyle(new Sets the default timeline style for use in the parent object's
DefaultStyle) scope.

setIsDirty(isDirty) Specifies if changes have been made since the workbook was
last saved. You can set this property to true if you want to
close a modified workbook without either saving it or being
prompted to save it.

setLinkedWorkbookRefresh Represents the update mode of the workbook links. The mode
Mode(linkedWorkbookRefresh is same for all of the workbook links present in the workbook.
Mode)

setUsePrecisionAsDisplayed(use True if calculations in this workbook will be done using only


PrecisionAsDisplayed) the precision of the numbers as they're displayed. Data will
permanently lose accuracy when switching this property from
false to true .

Method Details

addBinding(range, bindingType, id)


Add a new binding to a particular Range.

TypeScript

addBinding(
range: Range | string,
bindingType: BindingType,
id: string
): Binding;

Parameters
range ExcelScript.Range | string
Range to bind the binding to. May be a Range object or a string. If string, must
contain the full address, including the sheet name

bindingType ExcelScript.BindingType
Type of binding. See ExcelScript.BindingType .

id string
Name of the binding.

Returns
ExcelScript.Binding

addBindingFromNamedItem(name, bindingType, id)


Add a new binding based on a named item in the workbook. If the named item
references to multiple areas, the InvalidReference error will be returned.

TypeScript

addBindingFromNamedItem(
name: string,
bindingType: BindingType,
id: string
): Binding;

Parameters
name string
Name from which to create binding.

bindingType ExcelScript.BindingType
Type of binding. See ExcelScript.BindingType .

id string
Name of the binding.

Returns
ExcelScript.Binding

addBindingFromSelection(bindingType, id)
Add a new binding based on the current selection. If the selection has multiple areas,
the InvalidReference error will be returned.

TypeScript

addBindingFromSelection(bindingType: BindingType, id: string): Binding;

Parameters
bindingType ExcelScript.BindingType
Type of binding. See ExcelScript.BindingType .

id string
Name of the binding.

Returns
ExcelScript.Binding

addComment(cellAddress, content, contentType)


Creates a new comment with the given content on the given cell. An
InvalidArgument error is thrown if the provided range is larger than one cell.

TypeScript

addComment(
cellAddress: Range | string,
content: CommentRichContent | string,
contentType?: ContentType
): Comment;

Parameters
cellAddress ExcelScript.Range | string
The cell to which the comment is added. This can be a Range object or a string. If it's
a string, it must contain the full address, including the sheet name. An
InvalidArgument error is thrown if the provided range is larger than one cell.

content ExcelScript.CommentRichContent | string


The comment's content. This can be either a string or CommentRichContent object.
Strings are used for plain text. CommentRichContent objects allow for other comment
features, such as mentions.

contentType ExcelScript.ContentType
Optional. The type of content contained within the comment. The default value is
enum ContentType.Plain .

Returns
ExcelScript.Comment

addCustomXmlPart(xml)
Adds a new custom XML part to the workbook.

TypeScript

addCustomXmlPart(xml: string): CustomXmlPart;

Parameters
xml string
XML content. Must be a valid XML fragment.

Returns
ExcelScript.CustomXmlPart

addNamedItem(name, reference, comment)


Adds a new name to the collection of the given scope.

TypeScript
addNamedItem(
name: string,
reference: Range | string,
comment?: string
): NamedItem;

Parameters
name string
The name of the named item.

reference ExcelScript.Range | string


The formula or the range that the name will refer to.

comment string
Optional. The comment associated with the named item.

Returns
ExcelScript.NamedItem

Examples

TypeScript

/**
* This script creates a named formula and uses it in another part of the
workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Create a named item for a formula.
// This formula is the sum of the cells F2:F21 on Sheet1.
const namedItem: ExcelScript.NamedItem = workbook.addNamedItem(
"GrandTotal",
"=SUM(Sheet1!$F$2:$F$21)",
"The sum of table sums."
);

// Add this named formula to a new sheet in the workbook.


const otherSheet = workbook.addWorksheet();
otherSheet.getRange("A1").setFormula(namedItem.getFormula());

// Switch to the new worksheet.


otherSheet.activate();
}
addNamedItemFormulaLocal(name, formula, comment)
Adds a new name to the collection of the given scope using the user's locale for the
formula.

TypeScript

addNamedItemFormulaLocal(
name: string,
formula: string,
comment?: string
): NamedItem;

Parameters
name string
The name of the named item.

formula string
The formula in the user's locale that the name will refer to.

comment string
Optional. The comment associated with the named item.

Returns
ExcelScript.NamedItem

addPivotTable(name, source, destination)


Add a PivotTable based on the specified source data and insert it at the top-left cell
of the destination range.

TypeScript

addPivotTable(
name: string,
source: Range | string | Table,
destination: Range | string
): PivotTable;

Parameters
name string
The name of the new PivotTable.

source ExcelScript.Range | string | ExcelScript.Table


The source data for the new PivotTable, this can either be a range (or string address
including the worksheet name) or a table.

destination ExcelScript.Range | string


The cell in the upper-left corner of the PivotTable report's destination range (the
range on the worksheet where the resulting report will be placed).

Returns
ExcelScript.PivotTable

Examples

TypeScript

/**
* This script creates a PivotTable from an existing table and adds it to
an existing worksheet.
* This script assumes there is a table in the current worksheet with
columns named "Type" and "Sales".
* It also assumes there is a worksheet named "PivotSheet".
*/
function main(workbook: ExcelScript.Workbook) {
// Create a PivotTable based on a table in the current worksheet.
let sheet = workbook.getActiveWorksheet();
let table = sheet.getTables()[0];
let pivotTable = workbook.addPivotTable("My Pivot", table,
"PivotSheet!A1");

// Add fields to the PivotTable to show "Sales" per "Type".


pivotTable.addRowHierarchy(pivotTable.getHierarchy("Type"));
pivotTable.addDataHierarchy(pivotTable.getHierarchy("Sales"));
}

addPivotTableStyle(name, makeUniqueName)
Creates a blank PivotTableStyle with the specified name.

TypeScript
addPivotTableStyle(
name: string,
makeUniqueName?: boolean
): PivotTableStyle;

Parameters
name string
The unique name for the new PivotTable style. Will throw an InvalidArgument error if
the name is already in use.

makeUniqueName boolean
Optional. Defaults to false . If true , will append numbers to the name in order to
make it unique, if needed.

Returns
ExcelScript.PivotTableStyle

addPredefinedCellStyle(name)
Adds a new style to the collection.

TypeScript

addPredefinedCellStyle(name: string): void;

Parameters
name string
Name of the style to be added.

Returns
void

addSlicer(slicerSource, sourceField, slicerDestination)


Adds a new slicer to the workbook.

TypeScript
addSlicer(
slicerSource: string | PivotTable | Table,
sourceField: string | PivotField | number | TableColumn,
slicerDestination?: string | Worksheet
): Slicer;

Parameters
slicerSource string | ExcelScript.PivotTable | ExcelScript.Table
The data source that the new slicer will be based on. It can be a PivotTable object, a
Table object, or a string. When a PivotTable object is passed, the data source is the

source of the PivotTable object. When a Table object is passed, the data source is
the Table object. When a string is passed, it is interpreted as the name or ID of a
PivotTable or table.

sourceField string | ExcelScript.PivotField | number | ExcelScript.TableColumn


The field in the data source to filter by. It can be a PivotField object, a TableColumn
object, the ID of a PivotField or the name or ID of a TableColumn .

slicerDestination string | ExcelScript.Worksheet


Optional. The worksheet in which the new slicer will be created. It can be a
Worksheet object or the name or ID of a worksheet. This parameter can be omitted if

the slicer collection is retrieved from a worksheet.

Returns
ExcelScript.Slicer

Examples

TypeScript

/**
* This script adds a slicer for an existing PivotTable.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the PivotTable named "Farm Pivot".
const farmPivot = workbook.getPivotTable("Farm Pivot");

// Create the slicer.


// Note that this assumes "Type" is already added as a hierarchy to the
PivotTable.
const fruitSlicer: ExcelScript.Slicer = workbook.addSlicer(
farmPivot, /* The table or PivotTale to be sliced. */
farmPivot.getHierarchy("Type").getFields()[0] /* What source field to
use as the slicer options. */
);

// Select the items to display.


fruitSlicer.selectItems(["Lemon", "Lime"]);

// Set the left margin of the slicer.


fruitSlicer.setLeft(400);
}

addSlicerStyle(name, makeUniqueName)
Creates a blank slicer style with the specified name.

TypeScript

addSlicerStyle(name: string, makeUniqueName?: boolean): SlicerStyle;

Parameters
name string
The unique name for the new slicer style. Will throw an InvalidArgument exception if
the name is already in use.

makeUniqueName boolean
Optional. Defaults to false . If true , will append numbers to the name in order to
make it unique, if needed.

Returns
ExcelScript.SlicerStyle

addTable(address, hasHeaders)
Creates a new table. The range object or source address determines the worksheet
under which the table will be added. If the table cannot be added (e.g., because the
address is invalid, or the table would overlap with another table), an error will be
thrown.

TypeScript
addTable(address: Range | string, hasHeaders: boolean): Table;

Parameters
address ExcelScript.Range | string
A Range object, or a string address or name of the range representing the data
source. If the address does not contain a sheet name, the currently-active sheet is
used.

hasHeaders boolean
A boolean value that indicates whether the data being imported has column labels. If
the source does not contain headers (i.e., when this property set to false ), Excel will
automatically generate a header and shift the data down by one row.

Returns
ExcelScript.Table

Examples

TypeScript

/**
* This sample converts the information in the first worksheet
* into a table with headers.
*/
function main(workbook: ExcelScript.Workbook) {
// This assumes there is one contiguous range in the first worksheet.
const dataRange = workbook.getFirstWorksheet().getUsedRange();

// Add a table at the workbook level.


workbook.addTable(dataRange.getAddress(), true);
}

addTableStyle(name, makeUniqueName)
Creates a blank TableStyle with the specified name.

TypeScript

addTableStyle(name: string, makeUniqueName?: boolean): TableStyle;


Parameters
name string
The unique name for the new table style. Will throw an InvalidArgument error if the
name is already in use.

makeUniqueName boolean
Optional. Defaults to false . If true , will append numbers to the name in order to
make it unique, if needed.

Returns
ExcelScript.TableStyle

addTimelineStyle(name, makeUniqueName)
Creates a blank TimelineStyle with the specified name.

TypeScript

addTimelineStyle(name: string, makeUniqueName?: boolean): TimelineStyle;

Parameters
name string
The unique name for the new timeline style. Will throw an InvalidArgument error if
the name is already in use.

makeUniqueName boolean
Optional. Defaults to false . If true , will append numbers to the name in order to
make it unique, if needed.

Returns
ExcelScript.TimelineStyle

addWorksheet(name)
Adds a new worksheet to the workbook. The worksheet will be added at the end of
existing worksheets. If you wish to activate the newly added worksheet, call
.activate() on it.
TypeScript

addWorksheet(name?: string): Worksheet;

Parameters
name string
Optional. The name of the worksheet to be added. If specified, the name should be
unique. If not specified, Excel determines the name of the new worksheet.

Returns
ExcelScript.Worksheet

Examples

TypeScript

/**
* This script adds a new worksheet named "Data" to the workbook.
* If a worksheet with that name already exists, the script logs a note.
*/
function main(workbook: ExcelScript.Workbook) {
// Check if the "Data" worksheet already exists.
if (workbook.getWorksheet("Data")) {
console.log("The Data worksheet is already in the workbook.");
} else {
// Add a new worksheet.
let worksheet = workbook.addWorksheet("Data");
}
}

breakAllLinksToLinkedWorkbooks()
Breaks all the links to the linked workbooks. Once the links are broken, any formulas
referencing workbook links are removed entirely and replaced with the most recently
retrieved values.

TypeScript

breakAllLinksToLinkedWorkbooks(): void;

Returns
void

getActiveCell()
Gets the currently active cell from the workbook.

TypeScript

getActiveCell(): Range;

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This script logs the value of the current active cell.
* If multiple cells are selected, the top-leftmost cell will be logged.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current active cell in the workbook.
let cell = workbook.getActiveCell();
console.log(`The current cell's value is ${cell.getValue()}`);
}

getActiveChart()
Gets the currently active chart in the workbook. If there is no active chart, then this
method returns undefined .

TypeScript

getActiveChart(): Chart;

Returns
ExcelScript.Chart

getActiveSlicer()
Gets the currently active slicer in the workbook. If there is no active slicer, then this
method returns undefined .

TypeScript

getActiveSlicer(): Slicer;

Returns
ExcelScript.Slicer

getActiveWorksheet()
Gets the currently active worksheet in the workbook.

TypeScript

getActiveWorksheet(): Worksheet;

Returns
ExcelScript.Worksheet

getApplication()
Represents the Excel application instance that contains this workbook.

TypeScript

getApplication(): Application;

Returns
ExcelScript.Application

getAutoSave()
Specifies if the workbook is in AutoSave mode.

TypeScript
getAutoSave(): boolean;

Returns
boolean

getBinding(id)
Gets a binding object by ID. If the binding object does not exist, then this method
returns undefined .

TypeScript

getBinding(id: string): Binding | undefined;

Parameters
id string
ID of the binding object to be retrieved.

Returns
ExcelScript.Binding | undefined

getBindings()
Represents a collection of bindings that are part of the workbook.

TypeScript

getBindings(): Binding[];

Returns
ExcelScript.Binding[]

getCalculationEngineVersion()
Returns a number about the version of Excel Calculation Engine.
TypeScript

getCalculationEngineVersion(): number;

Returns
number

getChartDataPointTrack()
True if all charts in the workbook are tracking the actual data points to which they
are attached. False if the charts track the index of the data points.

TypeScript

getChartDataPointTrack(): boolean;

Returns
boolean

getComment(commentId)
Gets a comment from the collection based on its ID. If the comment object does not
exist, then this method returns undefined .

TypeScript

getComment(commentId: string): Comment | undefined;

Parameters
commentId string
The identifier for the comment.

Returns
ExcelScript.Comment | undefined

getCommentByCell(cellAddress)
Gets the comment from the specified cell. If there is no comment in the cell, an error
is thrown.

TypeScript

getCommentByCell(cellAddress: Range | string): Comment;

Parameters
cellAddress ExcelScript.Range | string
The cell which the comment is on. This can be a Range object or a string. If it's a
string, it must contain the full address, including the sheet name. An
InvalidArgument error is thrown if the provided range is larger than one cell.

Returns
ExcelScript.Comment

getCommentByReplyId(replyId)
Gets the comment to which the given reply is connected.

TypeScript

getCommentByReplyId(replyId: string): Comment;

Parameters
replyId string
The identifier of comment reply.

Returns
ExcelScript.Comment

getComments()
Represents a collection of comments associated with the workbook.

TypeScript
getComments(): Comment[];

Returns
ExcelScript.Comment[]

getCustomXmlPart(id)
Gets a custom XML part based on its ID. If the CustomXmlPart does not exist, then
this method returns undefined .

TypeScript

getCustomXmlPart(id: string): CustomXmlPart | undefined;

Parameters
id string
ID of the object to be retrieved.

Returns
ExcelScript.CustomXmlPart | undefined

getCustomXmlPartByNamespace(namespaceUri)

2 Warning

This API is now deprecated.

Use getCustomXmlPartsByNamespace instead.

Gets a new collection of custom XML parts whose namespaces match the given
namespace.

TypeScript

getCustomXmlPartByNamespace(namespaceUri: string): CustomXmlPart[];


Parameters
namespaceUri string
This must be a fully qualified schema URI; for example,
"http://schemas.contoso.com/review/1.0".

Returns
ExcelScript.CustomXmlPart[]

getCustomXmlParts()
Represents the collection of custom XML parts contained by this workbook.

TypeScript

getCustomXmlParts(): CustomXmlPart[];

Returns
ExcelScript.CustomXmlPart[]

getCustomXmlPartsByNamespace(namespaceUri)
Gets a new collection of custom XML parts whose namespaces match the given
namespace.

TypeScript

getCustomXmlPartsByNamespace(namespaceUri: string): CustomXmlPart[];

Parameters
namespaceUri string
This must be a fully qualified schema URI; for example,
"http://schemas.contoso.com/review/1.0".

Returns
ExcelScript.CustomXmlPart[]
getDefaultPivotTableStyle()
Gets the default PivotTable style for the parent object's scope.

TypeScript

getDefaultPivotTableStyle(): PivotTableStyle;

Returns
ExcelScript.PivotTableStyle

getDefaultSlicerStyle()
Gets the default SlicerStyle for the parent object's scope.

TypeScript

getDefaultSlicerStyle(): SlicerStyle;

Returns
ExcelScript.SlicerStyle

getDefaultTableStyle()
Gets the default table style for the parent object's scope.

TypeScript

getDefaultTableStyle(): TableStyle;

Returns
ExcelScript.TableStyle

getDefaultTimelineStyle()
Gets the default timeline style for the parent object's scope.

TypeScript
getDefaultTimelineStyle(): TimelineStyle;

Returns
ExcelScript.TimelineStyle

getFirstWorksheet(visibleOnly)
Gets the first worksheet in the collection.

TypeScript

getFirstWorksheet(visibleOnly?: boolean): Worksheet;

Parameters
visibleOnly boolean
Optional. If true , considers only visible worksheets, skipping over any hidden ones.

Returns
ExcelScript.Worksheet

getIsDirty()
Specifies if changes have been made since the workbook was last saved. You can set
this property to true if you want to close a modified workbook without either saving
it or being prompted to save it.

TypeScript

getIsDirty(): boolean;

Returns
boolean

getLastWorksheet(visibleOnly)
Gets the last worksheet in the collection.
TypeScript

getLastWorksheet(visibleOnly?: boolean): Worksheet;

Parameters
visibleOnly boolean
Optional. If true , considers only visible worksheets, skipping over any hidden ones.

Returns
ExcelScript.Worksheet

getLinkedWorkbookByUrl(key)
Gets information about a linked workbook by its URL. If the workbook does not exist,
then this method returns undefined .

TypeScript

getLinkedWorkbookByUrl(key: string): LinkedWorkbook | undefined;

Parameters
key string
The URL of the linked workbook.

Returns
ExcelScript.LinkedWorkbook | undefined

getLinkedWorkbookRefreshMode()
Represents the update mode of the workbook links. The mode is same for all of the
workbook links present in the workbook.

TypeScript

getLinkedWorkbookRefreshMode(): WorkbookLinksRefreshMode;
Returns
ExcelScript.WorkbookLinksRefreshMode

Examples

TypeScript

/**
* This script refreshes all the links to external workbooks,
* if the linked workbook refresh mode is set to manual.
* To learn about linked workbooks, see
https://support.microsoft.com/office/c98d1803-dd75-4668-ac6a-
d7cca2a9b95f.
*/
function main(workbook: ExcelScript.Workbook) {
// Check the refresh mode.
if (workbook.getLinkedWorkbookRefreshMode() ===
ExcelScript.WorkbookLinksRefreshMode.manual) {
console.log("Refreshing workbook links");

// Trigger a refresh of linked workbook content.


workbook.refreshAllLinksToLinkedWorkbooks();
}

getLinkedWorkbooks()
Returns a collection of linked workbooks. In formulas, the workbook links can be
used to reference data (cell values and names) outside of the current workbook.

TypeScript

getLinkedWorkbooks(): LinkedWorkbook[];

Returns
ExcelScript.LinkedWorkbook[]

Examples

TypeScript

/**
* This script removes all links to other workbooks.
*/
function main(workbook: ExcelScript.Workbook) {
// Get all the linked workbook references.
const externalWorkbooks: ExcelScript.LinkedWorkbook[] =
workbook.getLinkedWorkbooks();
console.log(`There are ${externalWorkbooks.length} other workbooks
linked to from this workbook.`);

// Remove all the links to those workbooks.


// This changes the value of cells with workbook links to
"#CONNECT!".
externalWorkbooks.forEach((workbookLink) => {
workbookLink.breakLinks();
});
}

getName()
Gets the workbook name.

TypeScript

getName(): string;

Returns
string

Examples

TypeScript

/**
* This script logs the name of the workbook without the ".xlsx"
extension.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the workbook's name.
let name = workbook.getName();

// Remove the file extension.


name = name.substring(0, name.lastIndexOf(".xlsx"));

// Display the name in the console.


console.log(name);
}

getNamedItem(name)
Gets a NamedItem object using its name. If the object does not exist, then this
method returns undefined .

TypeScript

getNamedItem(name: string): NamedItem | undefined;

Parameters
name string
Nameditem name.

Returns
ExcelScript.NamedItem | undefined

getNames()
Represents a collection of workbook-scoped named items (named ranges and
constants).

TypeScript

getNames(): NamedItem[];

Returns
ExcelScript.NamedItem[]

Examples

TypeScript

/**
* This script looks for every named range with "Review" in the name
* and marks the range with a yellow fill.
*/
function main(workbook: ExcelScript.Workbook) {
// Look at every named item in the workbook.
workbook.getNames().forEach((namedItem) => {
// Find names containing "Review".
if (namedItem.getName().includes("Review")) {
// Only change the fill color if the named item is a range (not a
formula).
let itemType: ExcelScript.NamedItemType = namedItem.getType();
if (itemType === ExcelScript.NamedItemType.range) {
// Set the range's fill color to yellow.
namedItem.getRange().getFormat().getFill().setColor("yellow");
}
}
});
}

getPivotTable(name)
Gets a PivotTable by name. If the PivotTable does not exist, then this method returns
undefined .

TypeScript

getPivotTable(name: string): PivotTable | undefined;

Parameters
name string
Name of the PivotTable to be retrieved.

Returns
ExcelScript.PivotTable | undefined

getPivotTables()
Represents a collection of PivotTables associated with the workbook.

TypeScript

getPivotTables(): PivotTable[];

Returns
ExcelScript.PivotTable[]

getPivotTableStyle(name)
Gets a PivotTableStyle by name. If the PivotTableStyle does not exist, then this
method returns undefined .

TypeScript

getPivotTableStyle(name: string): PivotTableStyle | undefined;

Parameters
name string
Name of the PivotTable style to be retrieved.

Returns
ExcelScript.PivotTableStyle | undefined

getPivotTableStyles()
Represents a collection of PivotTableStyles associated with the workbook.

TypeScript

getPivotTableStyles(): PivotTableStyle[];

Returns
ExcelScript.PivotTableStyle[]

getPredefinedCellStyle(name)
Gets a style by name. If the style object does not exist, then this method returns
undefined .

TypeScript

getPredefinedCellStyle(name: string): PredefinedCellStyle | undefined;

Parameters
name string
Name of the style to be retrieved.
Returns
ExcelScript.PredefinedCellStyle | undefined

getPredefinedCellStyles()
Represents a collection of styles associated with the workbook.

TypeScript

getPredefinedCellStyles(): PredefinedCellStyle[];

Returns
ExcelScript.PredefinedCellStyle[]

getPreviouslySaved()
Specifies if the workbook has ever been saved locally or online.

TypeScript

getPreviouslySaved(): boolean;

Returns
boolean

getProperties()
Gets the workbook properties.

TypeScript

getProperties(): DocumentProperties;

Returns
ExcelScript.DocumentProperties

getProtection()
Returns the protection object for a workbook.

TypeScript

getProtection(): WorkbookProtection;

Returns
ExcelScript.WorkbookProtection

Examples

TypeScript

/**
* This script protects the workbook with a password, if it isn't already
protected.
* The password is provided by the user through a prompt.
*/
function main(workbook: ExcelScript.Workbook, password?: string) {
// Get the workbook-level protection object.
const protection = workbook.getProtection();

// Check if the workbook is already protected.


if (!protection.getProtected()) {
// Protect the workbook with the given password.
// If the optional password was omitted,
// no password will be needed to unprotect the workbook.
protection.protect(password);
}
}

getQueries()
Returns a collection of Power Query queries that are part of the workbook.

TypeScript

getQueries(): Query[];

Returns
ExcelScript.Query[]
getQuery(key)
Gets a query from the collection based on its name.

TypeScript

getQuery(key: string): Query;

Parameters
key string
The name of the query case-insensitive.

Returns
ExcelScript.Query

getReadOnly()
Returns true if the workbook is open in read-only mode.

TypeScript

getReadOnly(): boolean;

Returns
boolean

getSelectedRange()
Gets the currently selected single range from the workbook. If there are multiple
ranges selected, this method will throw an error.

TypeScript

getSelectedRange(): Range;

Returns
ExcelScript.Range
getSelectedRanges()
Gets the currently selected one or more ranges from the workbook. Unlike
getSelectedRange() , this method returns a RangeAreas object that represents all the

selected ranges.

TypeScript

getSelectedRanges(): RangeAreas;

Returns
ExcelScript.RangeAreas

getSlicer(key)
Gets a slicer using its name or ID. If the slicer doesn't exist, then this method returns
undefined .

TypeScript

getSlicer(key: string): Slicer | undefined;

Parameters
key string
Name or ID of the slicer to be retrieved.

Returns
ExcelScript.Slicer | undefined

getSlicers()
Represents a collection of slicers associated with the workbook.

TypeScript

getSlicers(): Slicer[];

Returns
ExcelScript.Slicer[]

getSlicerStyle(name)
Gets a SlicerStyle by name. If the slicer style doesn't exist, then this method returns
undefined .

TypeScript

getSlicerStyle(name: string): SlicerStyle | undefined;

Parameters
name string
Name of the slicer style to be retrieved.

Returns
ExcelScript.SlicerStyle | undefined

getSlicerStyles()
Represents a collection of SlicerStyles associated with the workbook.

TypeScript

getSlicerStyles(): SlicerStyle[];

Returns
ExcelScript.SlicerStyle[]

getTable(key)
Gets a table by name or ID. If the table doesn't exist, then this method returns
undefined .

TypeScript

getTable(key: string): Table | undefined;


Parameters
key string
Name or ID of the table to be retrieved.

Returns
ExcelScript.Table | undefined

getTables()
Represents a collection of tables associated with the workbook.

TypeScript

getTables(): Table[];

Returns
ExcelScript.Table[]

getTableStyle(name)
Gets a TableStyle by name. If the table style does not exist, then this method
returns undefined .

TypeScript

getTableStyle(name: string): TableStyle | undefined;

Parameters
name string
Name of the table style to be retrieved.

Returns
ExcelScript.TableStyle | undefined

getTableStyles()
Represents a collection of TableStyles associated with the workbook.
TypeScript

getTableStyles(): TableStyle[];

Returns
ExcelScript.TableStyle[]

getTimelineStyle(name)
Gets a TimelineStyle by name. If the timeline style doesn't exist, then this method
returns undefined .

TypeScript

getTimelineStyle(name: string): TimelineStyle | undefined;

Parameters
name string
Name of the timeline style to be retrieved.

Returns
ExcelScript.TimelineStyle | undefined

getTimelineStyles()
Represents a collection of TimelineStyles associated with the workbook.

TypeScript

getTimelineStyles(): TimelineStyle[];

Returns
ExcelScript.TimelineStyle[]

getUsePrecisionAsDisplayed()
True if calculations in this workbook will be done using only the precision of the
numbers as they're displayed. Data will permanently lose accuracy when switching
this property from false to true .

TypeScript

getUsePrecisionAsDisplayed(): boolean;

Returns
boolean

getWorksheet(key)
Gets a worksheet object using its name or ID. If the worksheet does not exist, then
this method returns undefined .

TypeScript

getWorksheet(key: string): Worksheet | undefined;

Parameters
key string
The name or ID of the worksheet.

Returns
ExcelScript.Worksheet | undefined

Examples

TypeScript

/**
* This script switches the active view to a worksheet named "Data", if
it exists.
*/
function main(workbook: ExcelScript.Workbook) {
// Check if the "Data" worksheet exists.
let dataWorksheet = workbook.getWorksheet("Data");
if (dataWorksheet) {
// Switch to the "Data" worksheet.
dataWorksheet.activate();
} else {
console.log(`No worksheet named "Data" in this workbook.`);
}
}

getWorksheets()
Represents a collection of worksheets associated with the workbook.

TypeScript

getWorksheets(): Worksheet[];

Returns
ExcelScript.Worksheet[]

Examples

TypeScript

/**
* This script logs the names of all the worksheets in the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get all the worksheets in the workbook.
let sheets = workbook.getWorksheets();

// Get a list of all the worksheet names.


let names = sheets.map ((sheet) => sheet.getName());

// Write in the console all the worksheet names and the total count.
console.log(names);
console.log(`Total worksheets inside of this workbook:
${sheets.length}`);
}

refreshAllDataConnections()
Refreshes all the Data Connections.

TypeScript

refreshAllDataConnections(): void;
Returns
void

refreshAllLinksToLinkedWorkbooks()
Makes a request to refresh all the workbook links.

TypeScript

refreshAllLinksToLinkedWorkbooks(): void;

Returns
void

refreshAllPivotTables()
Refreshes all the pivot tables in the collection.

TypeScript

refreshAllPivotTables(): void;

Returns
void

setChartDataPointTrack(chartDataPointTrack)
True if all charts in the workbook are tracking the actual data points to which they
are attached. False if the charts track the index of the data points.

TypeScript

setChartDataPointTrack(chartDataPointTrack: boolean): void;

Parameters
chartDataPointTrack boolean
Returns
void

setDefaultPivotTableStyle(newDefaultStyle)
Sets the default PivotTable style for use in the parent object's scope.

TypeScript

setDefaultPivotTableStyle(
newDefaultStyle: PivotTableStyle | string
): void;

Parameters
newDefaultStyle ExcelScript.PivotTableStyle | string
The PivotTableStyle object, or name of the PivotTableStyle object, that should be
the new default.

Returns
void

setDefaultSlicerStyle(newDefaultStyle)
Sets the default slicer style for use in the parent object's scope.

TypeScript

setDefaultSlicerStyle(newDefaultStyle: SlicerStyle | string): void;

Parameters
newDefaultStyle ExcelScript.SlicerStyle | string
The SlicerStyle object, or name of the SlicerStyle object, that should be the new
default.

Returns
void
setDefaultTableStyle(newDefaultStyle)
Sets the default table style for use in the parent object's scope.

TypeScript

setDefaultTableStyle(newDefaultStyle: TableStyle | string): void;

Parameters
newDefaultStyle ExcelScript.TableStyle | string
The TableStyle object, or name of the TableStyle object, that should be the new
default.

Returns
void

setDefaultTimelineStyle(newDefaultStyle)
Sets the default timeline style for use in the parent object's scope.

TypeScript

setDefaultTimelineStyle(newDefaultStyle: TimelineStyle | string): void;

Parameters
newDefaultStyle ExcelScript.TimelineStyle | string
The TimelineStyle object, or name of the TimelineStyle object, that should be the
new default.

Returns
void

setIsDirty(isDirty)
Specifies if changes have been made since the workbook was last saved. You can set
this property to true if you want to close a modified workbook without either saving
it or being prompted to save it.
TypeScript

setIsDirty(isDirty: boolean): void;

Parameters
isDirty boolean

Returns
void

setLinkedWorkbookRefreshMode(linkedWorkbook
RefreshMode)
Represents the update mode of the workbook links. The mode is same for all of the
workbook links present in the workbook.

TypeScript

setLinkedWorkbookRefreshMode(
linkedWorkbookRefreshMode: WorkbookLinksRefreshMode
): void;

Parameters
linkedWorkbookRefreshMode ExcelScript.WorkbookLinksRefreshMode

Returns
void

setUsePrecisionAsDisplayed(usePrecisionAsDisplayed)
True if calculations in this workbook will be done using only the precision of the
numbers as they're displayed. Data will permanently lose accuracy when switching
this property from false to true .

TypeScript

setUsePrecisionAsDisplayed(usePrecisionAsDisplayed: boolean): void;


Parameters
usePrecisionAsDisplayed boolean

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.WorkbookProtection
interface
Reference
Package: ExcelScript

Represents the protection of a workbook object.

Methods
ノ Expand table

getProtected() Specifies if the workbook is protected.

protect(password) Protects the workbook. Fails if the workbook has been protected.

unprotect(password) Unprotects the workbook.

Method Details

getProtected()
Specifies if the workbook is protected.

TypeScript

getProtected(): boolean;

Returns
boolean

Examples

TypeScript

/**
* This script protects the workbook with a default password, if there is
not already protection.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the workbook-level protection object.
const protection = workbook.getProtection();

// Check if the workbook is already protected.


if (!protection.getProtected()) {
// Apply a default password.
protection.protect("1234");
}
}

protect(password)
Protects the workbook. Fails if the workbook has been protected.

TypeScript

protect(password?: string): void;

Parameters
password string
Workbook protection password.

Returns
void

Examples

TypeScript

/**
* This script protects the workbook using a password given in a user
prompt.
*/
function main(workbook: ExcelScript.Workbook, password?: string) {
// Get the workbook-level protection object.
const protection = workbook.getProtection();

// Protect the workbook with the given password.


// If the optional password was omitted,
// no password will be needed to unprotect the workbook.
protection.protect(password);
}
unprotect(password)
Unprotects the workbook.

TypeScript

unprotect(password?: string): void;

Parameters
password string
Workbook protection password.

Returns
void

Examples

TypeScript

/**
* This script removes protection from the workbook using a password
given in a user prompt.
*/
function main(workbook: ExcelScript.Workbook, password?: string) {
// Get the workbook-level protection object.
const protection = workbook.getProtection();

// Unprotect the workbook with the given password.


protection.unprotect(password);
}

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.WorkbookRangeAreas
interface
Reference
Package: ExcelScript

Represents a collection of one or more rectangular ranges in multiple worksheets.

Remarks

Examples

TypeScript

/**
* This script finds the direct precedents of the active cell.
* It changes the font and color of those precedent cells.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the active cell.
const selected = workbook.getActiveCell();

// Get the cells that are direct precedents of the current cell.
const precedents : ExcelScript.WorkbookRangeAreas =
selected.getDirectPrecedents();

// Set the font to bold and the fill color to orange for all the precedent
cells.
precedents.getRanges().forEach(range => {
range.getFormat().getFill().setColor("orange");
range.getFormat().getFont().setBold(true);
});
}

Methods
ノ Expand table

getAddresses() Returns an array of addresses in A1-style. Address values contain the


worksheet name for each rectangular block of cells (e.g., "Sheet1!A1:B4,
Sheet1!D1:D4"). Read-only.

getAreas() Returns the RangeAreasCollection object. Each RangeAreas in the collection


represent one or more rectangle ranges in one worksheet.

getRangeAreas Returns the RangeAreas object based on worksheet name or ID in the


BySheet(key) collection. If the worksheet does not exist, then this method returns
undefined .

getRanges() Returns ranges that comprise this object in a RangeCollection object.

Method Details

getAddresses()
Returns an array of addresses in A1-style. Address values contain the worksheet
name for each rectangular block of cells (e.g., "Sheet1!A1:B4, Sheet1!D1:D4"). Read-
only.

TypeScript

getAddresses(): string[];

Returns
string[]

getAreas()
Returns the RangeAreasCollection object. Each RangeAreas in the collection
represent one or more rectangle ranges in one worksheet.

TypeScript

getAreas(): RangeAreas[];

Returns
ExcelScript.RangeAreas[]

getRangeAreasBySheet(key)
Returns the RangeAreas object based on worksheet name or ID in the collection. If
the worksheet does not exist, then this method returns undefined .
TypeScript

getRangeAreasBySheet(key: string): RangeAreas;

Parameters
key string
The name or ID of the worksheet.

Returns
ExcelScript.RangeAreas

getRanges()
Returns ranges that comprise this object in a RangeCollection object.

TypeScript

getRanges(): Range[];

Returns
ExcelScript.Range[]

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.Worksheet interface
Reference
Package: ExcelScript

An Excel worksheet is a grid of cells. It can contain data, tables, charts, etc.

Remarks

Examples

TypeScript

/**
* This script creates a new worksheet named "Plum" and sets its tab color
to purple.
*/
function main(workbook: ExcelScript.Workbook) {
const newSheet = workbook.addWorksheet("Plum")
newSheet.setTabColor("purple");
}

Methods
ノ Expand table

activate() Activate the worksheet in the Excel UI.

addChart(type, source Creates a new chart.


Data, seriesBy)

addComment(cellAddress, Creates a new comment with the given content on the given cell. An
content, contentType) InvalidArgument error is thrown if the provided range is larger than
one cell.

addGeometric Adds a geometric shape to the worksheet. Returns a Shape object


Shape(geometricShape that represents the new shape.
Type)

addGroup(values) Groups a subset of shapes in this collection's worksheet. Returns a


Shape object that represents the new group of shapes.

addHorizontalPage Adds a page break before the top-left cell of the range specified.
Break(pageBreakRange)
addImage(base64Image Creates an image from a base64-encoded string and adds it to the
String) worksheet. Returns the Shape object that represents the new image.

addLine(startLeft, startTop, Adds a line to worksheet. Returns a Shape object that represents the
endLeft, endTop, new line.
connectorType)

addNamedItem(name, Adds a new name to the collection of the given scope.


reference, comment)

addNamedItemFormula Adds a new name to the collection of the given scope using the
Local(name, formula, user's locale for the formula.
comment)

addNamedSheet Creates a new sheet view with the given name.


View(name)

addPivotTable(name, Add a PivotTable based on the specified source data and insert it at
source, destination) the top-left cell of the destination range.

addSlicer(slicerSource, Adds a new slicer to the workbook.


sourceField, slicer
Destination)

addTable(address, has Creates a new table. The range object or source address determines
Headers) the worksheet under which the table will be added. If the table
cannot be added (e.g., because the address is invalid, or the table
would overlap with another table), an error will be thrown.

addTextBox(text) Adds a text box to the worksheet with the provided text as the
content. Returns a Shape object that represents the new text box.

addVerticalPage Adds a page break before the top-left cell of the range specified.
Break(pageBreakRange)

addWorksheetCustom Adds a new custom property that maps to the provided key. This
Property(key, value) overwrites existing custom properties with that key.

calculate(markAllDirty) Calculates all cells on a worksheet.

copy(positionType, relative Copies a worksheet and places it at the specified position.


To)

delete() Deletes the worksheet from the workbook. Note that if the
worksheet's visibility is set to "VeryHidden", the delete operation will
fail with an InvalidOperation exception. You should first change its
visibility to hidden or visible before deleting it.

enterTemporaryNamed Creates and activates a new temporary sheet view. Temporary views
SheetView() are removed when closing the application, exiting the temporary
view with the exit method, or switching to another sheet view. The
temporary sheet view can also be accessed with the empty string
(""), if the temporary view exists.

exitActiveNamedSheet Exits the currently active sheet view.


View()

findAll(text, criteria) Finds all occurrences of the given string based on the criteria
specified and returns them as a RangeAreas object, comprising one
or more rectangular ranges.

getActiveNamedSheet Gets the worksheet's currently active sheet view.


View()

getAutoFilter() Represents the AutoFilter object of the worksheet.

getCell(row, column) Gets the Range object containing the single cell based on row and
column numbers. The cell can be outside the bounds of its parent
range, so long as it stays within the worksheet grid.

getChart(name) Gets a chart using its name. If there are multiple charts with the
same name, the first one will be returned. If the chart doesn't exist,
then this method returns undefined .

getCharts() Returns a collection of charts that are part of the worksheet.

getComment(commentId) Gets a comment from the collection based on its ID. If the comment
object does not exist, then this method returns undefined .

getCommentByCell(cell Gets the comment from the specified cell. If there is no comment in
Address) the cell, an error is thrown.

getCommentByReply Gets the comment to which the given reply is connected.


Id(replyId)

getComments() Returns a collection of all the Comments objects on the worksheet.

getCustomProperties() Gets a collection of worksheet-level custom properties.

getEnableCalculation() Determines if Excel should recalculate the worksheet when


necessary. True if Excel recalculates the worksheet when necessary.
False if Excel doesn't recalculate the sheet.

getFreezePanes() Gets an object that can be used to manipulate frozen panes on the
worksheet.

getHorizontalPageBreaks() Gets the horizontal page break collection for the worksheet. This
collection only contains manual page breaks.

getId() Returns a value that uniquely identifies the worksheet in a given


workbook. The value of the identifier remains the same even when
the worksheet is renamed or moved.
getName() The display name of the worksheet. The name must be fewer than
32 characters.

getNamedItem(name) Gets a NamedItem object using its name. If the object does not exist,
then this method returns undefined .

getNamedSheetView(key) Gets a sheet view using its name. If the sheet view object does not
exist, then this method returns undefined .

getNamedSheetViews() Returns a collection of sheet views that are present in the worksheet.

getNames() Collection of names scoped to the current worksheet.

getNext(visibleOnly) Gets the worksheet that follows this one. If there are no worksheets
following this one, then this method returns undefined .

getPageLayout() Gets the PageLayout object of the worksheet.

getPivotTable(name) Gets a PivotTable by name. If the PivotTable does not exist, then this
method returns undefined .

getPivotTables() Collection of PivotTables that are part of the worksheet.

getPosition() The zero-based position of the worksheet within the workbook.

getPrevious(visibleOnly) Gets the worksheet that precedes this one. If there are no previous
worksheets, then this method returns undefined .

getProtection() Returns the sheet protection object for a worksheet.

getRange(address) Gets the Range object, representing a single rectangular block of


cells, specified by the address or name.

getRangeByIndexes(start Gets the Range object beginning at a particular row index and
Row, startColumn, row column index, and spanning a certain number of rows and columns.
Count, columnCount)

getRanges(address) Gets the RangeAreas object, representing one or more blocks of


rectangular ranges, specified by the address or name.

getShape(key) Gets a shape using its name or ID. If the shape object does not exist,
then this method returns undefined .

getShapes() Returns the collection of all the Shape objects on the worksheet.

getShowGridlines() Specifies if gridlines are visible to the user.

getShowHeadings() Specifies if headings are visible to the user.

getSlicer(key) Gets a slicer using its name or ID. If the slicer doesn't exist, then this
method returns undefined .
getSlicers() Returns a collection of slicers that are part of the worksheet.

getStandardHeight() Returns the standard (default) height of all the rows in the
worksheet, in points.

getStandardWidth() Specifies the standard (default) width of all the columns in the
worksheet. One unit of column width is equal to the width of one
character in the Normal style. For proportional fonts, the width of
the character 0 (zero) is used.

getTabColor() The tab color of the worksheet. When retrieving the tab color, if the
worksheet is invisible, the value will be null . If the worksheet is
visible but the tab color is set to auto, an empty string will be
returned. Otherwise, the property will be set to a color, in the form
#RRGGBB (e.g., "FFA500"). When setting the color, use an empty-
string to set an "auto" color, or a real color otherwise.

getTabId() Returns a value representing this worksheet that can be read by


Open Office XML. This is an integer value, which is different from
worksheet.id (which returns a globally unique identifier) and
worksheet.name (which returns a value such as "Sheet1").

getTable(key) Gets a table by name or ID. If the table doesn't exist, then this
method returns undefined .

getTables() Collection of tables that are part of the worksheet.

getUsedRange(values
Only)

getVerticalPageBreaks() Gets the vertical page break collection for the worksheet. This
collection only contains manual page breaks.

getVisibility() The visibility of the worksheet.

getWorksheetCustom Gets a custom property object by its key, which is case-insensitive. If


Property(key) the custom property doesn't exist, then this method returns
undefined .

refreshAllPivotTables() Refreshes all the pivot tables in the collection.

removeAllHorizontalPage Resets all manual page breaks in the collection.


Breaks()

removeAllVerticalPage Resets all manual page breaks in the collection.


Breaks()

replaceAll(text, Finds and replaces the given string based on the criteria specified
replacement, criteria) within the current worksheet.

setEnable Determines if Excel should recalculate the worksheet when


Calculation(enable necessary. True if Excel recalculates the worksheet when necessary.
Calculation) False if Excel doesn't recalculate the sheet.

setName(name) The display name of the worksheet. The name must be fewer than
32 characters.

setPosition(position) The zero-based position of the worksheet within the workbook.

setShowGridlines(show Specifies if gridlines are visible to the user.


Gridlines)

setShowHeadings(show Specifies if headings are visible to the user.


Headings)

setStandard Specifies the standard (default) width of all the columns in the
Width(standardWidth) worksheet. One unit of column width is equal to the width of one
character in the Normal style. For proportional fonts, the width of
the character 0 (zero) is used.

setTabColor(tabColor) The tab color of the worksheet. When retrieving the tab color, if the
worksheet is invisible, the value will be null . If the worksheet is
visible but the tab color is set to auto, an empty string will be
returned. Otherwise, the property will be set to a color, in the form
#RRGGBB (e.g., "FFA500"). When setting the color, use an empty-
string to set an "auto" color, or a real color otherwise.

setVisibility(visibility) The visibility of the worksheet.

showOutlineLevels(row Shows row or column groups by their outline levels. Outlines groups
Levels, columnLevels) and summarizes a list of data in the worksheet. The rowLevels and
columnLevels parameters specify how many levels of the outline will
be displayed. The acceptable argument range is between 0 and 8. A
value of 0 does not change the current display. A value greater than
the current number of levels displays all the levels.

Method Details

activate()
Activate the worksheet in the Excel UI.

TypeScript

activate(): void;

Returns
void
Examples

TypeScript

/**
* This script switches the active view to a worksheet named "Data", if
it exists.
*/
function main(workbook: ExcelScript.Workbook) {
// Check if the "Data" worksheet exists.
let dataWorksheet = workbook.getWorksheet("Data");
if (dataWorksheet) {
// Switch to the "Data" worksheet.
dataWorksheet.activate();
} else {
console.log(`No worksheet named "Data" in this workbook.`);
}
}

addChart(type, sourceData, seriesBy)


Creates a new chart.

TypeScript

addChart(
type: ChartType,
sourceData: Range,
seriesBy?: ChartSeriesBy
): Chart;

Parameters
type ExcelScript.ChartType
Represents the type of a chart. See ExcelScript.ChartType for details.

sourceData ExcelScript.Range
The Range object corresponding to the source data.

seriesBy ExcelScript.ChartSeriesBy
Optional. Specifies the way columns or rows are used as data series on the chart. See
ExcelScript.ChartSeriesBy for details.

Returns
ExcelScript.Chart

Examples

TypeScript

/**
* This sample creates a column-clustered chart based on the current
worksheet's data.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get the data range.


let range = selectedSheet.getUsedRange();

// Insert a chart using the data on the current worksheet.


let chart =
selectedSheet.addChart(ExcelScript.ChartType.columnClustered, range);

// Name the chart for easy access in other scripts.


chart.setName("ColumnChart");
}

addComment(cellAddress, content, contentType)


Creates a new comment with the given content on the given cell. An
InvalidArgument error is thrown if the provided range is larger than one cell.

TypeScript

addComment(
cellAddress: Range | string,
content: CommentRichContent | string,
contentType?: ContentType
): Comment;

Parameters
cellAddress ExcelScript.Range | string
The cell to which the comment is added. This can be a Range object or a string. If it's
a string, it must contain the full address, including the sheet name. An
InvalidArgument error is thrown if the provided range is larger than one cell.
content ExcelScript.CommentRichContent | string
The comment's content. This can be either a string or CommentRichContent object.
Strings are used for plain text. CommentRichContent objects allow for other comment
features, such as mentions.

contentType ExcelScript.ContentType
Optional. The type of content contained within the comment. The default value is
enum ContentType.Plain .

Returns
ExcelScript.Comment

addGeometricShape(geometricShapeType)
Adds a geometric shape to the worksheet. Returns a Shape object that represents
the new shape.

TypeScript

addGeometricShape(geometricShapeType: GeometricShapeType): Shape;

Parameters
geometricShapeType ExcelScript.GeometricShapeType
Represents the type of the geometric shape. See ExcelScript.GeometricShapeType for
details.

Returns
ExcelScript.Shape

Examples

TypeScript

/**
* This script creates a hexagon shape on the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const hexagon: ExcelScript.Shape =
currentSheet.addGeometricShape(ExcelScript.GeometricShapeType.hexagon);

// Set the hexagon size to 40x40 pixels.


hexagon.setHeight(40);
hexagon.setWidth(40);

// Position the hexagon at [100,100] pixels.


hexagon.setLeft(100);
hexagon.setTop(100);
}

addGroup(values)
Groups a subset of shapes in this collection's worksheet. Returns a Shape object that
represents the new group of shapes.

TypeScript

addGroup(values: Array<string | Shape>): Shape;

Parameters
values Array<string | ExcelScript.Shape>
An array of shape IDs or shape objects.

Returns
ExcelScript.Shape

addHorizontalPageBreak(pageBreakRange)
Adds a page break before the top-left cell of the range specified.

TypeScript

addHorizontalPageBreak(pageBreakRange: Range | string): PageBreak;

Parameters
pageBreakRange ExcelScript.Range | string
The range immediately after the page break to be added.
Returns
ExcelScript.PageBreak

addImage(base64ImageString)
Creates an image from a base64-encoded string and adds it to the worksheet.
Returns the Shape object that represents the new image.

TypeScript

addImage(base64ImageString: string): Shape;

Parameters
base64ImageString string
A base64-encoded string representing an image in either JPEG or PNG format.

Returns
ExcelScript.Shape

Examples

TypeScript

/**
* This sample copies an image from a URL.
* This could be used to copy photos that a colleague stored in a shared
folder to a related workbook.
*/
async function main(workbook: ExcelScript.Workbook) {
// Fetch the image from a URL.
const link = "https://raw.githubusercontent.com/OfficeDev/office-
scripts-docs/master/docs/images/git-octocat.png";
const response = await fetch(link);

// Store the response as an ArrayBuffer, since it is a raw image file.


const data = await response.arrayBuffer();

// Convert the image data into a base64-encoded string.


const image = convertToBase64(data);

// Add the image to the current worksheet.


workbook.getActiveWorksheet().addImage(image);
}
/**
* Converts an ArrayBuffer containing a .png image into a base64-encoded
string.
*/
function convertToBase64(input: ArrayBuffer) {
const uInt8Array = new Uint8Array(input);
const count = uInt8Array.length;

// Allocate the necessary space up front.


const charCodeArray = new Array<string>(count)

// Convert every entry in the array to a character.


for (let i = count; i >= 0; i--) {
charCodeArray[i] = String.fromCharCode(uInt8Array[i]);
}

// Convert the characters to base64.


const base64 = btoa(charCodeArray.join(''));
return base64;
}

addLine(startLeft, startTop, endLeft, endTop, connector


Type)
Adds a line to worksheet. Returns a Shape object that represents the new line.

TypeScript

addLine(
startLeft: number,
startTop: number,
endLeft: number,
endTop: number,
connectorType?: ConnectorType
): Shape;

Parameters
startLeft number
The distance, in points, from the start of the line to the left side of the worksheet.

startTop number
The distance, in points, from the start of the line to the top of the worksheet.

endLeft number
The distance, in points, from the end of the line to the left of the worksheet.
endTop number
The distance, in points, from the end of the line to the top of the worksheet.

connectorType ExcelScript.ConnectorType
Represents the connector type. See ExcelScript.ConnectorType for details.

Returns
ExcelScript.Shape

addNamedItem(name, reference, comment)


Adds a new name to the collection of the given scope.

TypeScript

addNamedItem(
name: string,
reference: Range | string,
comment?: string
): NamedItem;

Parameters
name string
The name of the named item.

reference ExcelScript.Range | string


The formula or the range that the name will refer to.

comment string
Optional. The comment associated with the named item.

Returns
ExcelScript.NamedItem

addNamedItemFormulaLocal(name, formula, comment)


Adds a new name to the collection of the given scope using the user's locale for the
formula.
TypeScript

addNamedItemFormulaLocal(
name: string,
formula: string,
comment?: string
): NamedItem;

Parameters
name string
The name of the named item.

formula string
The formula in the user's locale that the name will refer to.

comment string
Optional. The comment associated with the named item.

Returns
ExcelScript.NamedItem

addNamedSheetView(name)
Creates a new sheet view with the given name.

TypeScript

addNamedSheetView(name: string): NamedSheetView;

Parameters
name string
The name of the sheet view to be created. Throws an error when the provided name
already exists, is empty, or is a name reserved by the worksheet.

Returns
ExcelScript.NamedSheetView

addPivotTable(name, source, destination)


Add a PivotTable based on the specified source data and insert it at the top-left cell
of the destination range.

TypeScript

addPivotTable(
name: string,
source: Range | string | Table,
destination: Range | string
): PivotTable;

Parameters
name string
The name of the new PivotTable.

source ExcelScript.Range | string | ExcelScript.Table


The source data for the new PivotTable, this can either be a range (or string address
including the worksheet name) or a table.

destination ExcelScript.Range | string


The cell in the upper-left corner of the PivotTable report's destination range (the
range on the worksheet where the resulting report will be placed).

Returns
ExcelScript.PivotTable

Examples

TypeScript

/**
* This script creates a PivotTable from an existing table and adds it to
a new worksheet.
* This script assumes there is a table in the current worksheet with
columns named "Type" and "Sales".
*/
function main(workbook: ExcelScript.Workbook) {
// Create a PivotTable based on a table in the current worksheet.
let sheet = workbook.getActiveWorksheet();
let table = sheet.getTables()[0];

// Add the PivotTable to a new worksheet.


let newSheet = workbook.addWorksheet("Pivot");
let pivotTable = newSheet.addPivotTable("My Pivot", table, "A1");
// Add fields to the PivotTable to show "Sales" per "Type".
pivotTable.addRowHierarchy(pivotTable.getHierarchy("Type"));
pivotTable.addDataHierarchy(pivotTable.getHierarchy("Sales"));

// Switch to the new worksheet.


newSheet.activate();
}

addSlicer(slicerSource, sourceField, slicerDestination)


Adds a new slicer to the workbook.

TypeScript

addSlicer(
slicerSource: string | PivotTable | Table,
sourceField: string | PivotField | number | TableColumn,
slicerDestination?: string | Worksheet
): Slicer;

Parameters
slicerSource string | ExcelScript.PivotTable | ExcelScript.Table
The data source that the new slicer will be based on. It can be a PivotTable object, a
Table object, or a string. When a PivotTable object is passed, the data source is the

source of the PivotTable object. When a Table object is passed, the data source is
the Table object. When a string is passed, it is interpreted as the name or ID of a
PivotTable or table.

sourceField string | ExcelScript.PivotField | number | ExcelScript.TableColumn


The field in the data source to filter by. It can be a PivotField object, a TableColumn
object, the ID of a PivotField or the name or ID of a TableColumn .

slicerDestination string | ExcelScript.Worksheet


Optional. The worksheet in which the new slicer will be created. It can be a
Worksheet object or the name or ID of a worksheet. This parameter can be omitted if

the slicer collection is retrieved from a worksheet.

Returns
ExcelScript.Slicer
Examples

TypeScript

/**
* This script adds a slicer for an existing PivotTable on the current
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first PivotTable from the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const pivot = currentSheet.getPivotTables()[0];

// Create the slicer.


// Note that this assumes "Type" is already added as a hierarchy to the
PivotTable.
const slicer = currentSheet.addSlicer(
pivot, /* The table or PivotTale to be sliced. */
pivot.getHierarchy("Type").getFields()[0] /* What source field to use
as the slicer options. */
);

// Select the items to display.


slicer.selectItems(["Lemon", "Lime"]);

// Set the left margin of the slicer.


slicer.setLeft(400);
}

addTable(address, hasHeaders)
Creates a new table. The range object or source address determines the worksheet
under which the table will be added. If the table cannot be added (e.g., because the
address is invalid, or the table would overlap with another table), an error will be
thrown.

TypeScript

addTable(address: Range | string, hasHeaders: boolean): Table;

Parameters
address ExcelScript.Range | string
A Range object, or a string address or name of the range representing the data
source. If the address does not contain a sheet name, the currently-active sheet is
used.
hasHeaders boolean
A boolean value that indicates whether the data being imported has column labels. If
the source does not contain headers (i.e., when this property set to false ), Excel will
automatically generate a header and shift the data down by one row.

Returns
ExcelScript.Table

Examples

TypeScript

/**
* This sample creates a table from the current worksheet's used range,
then sorts it based on the first column.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Create a table with the used cells.


let usedRange = selectedSheet.getUsedRange();
let newTable = selectedSheet.addTable(usedRange, true);

// Sort the table using the first column.


newTable.getSort().apply([{ key: 0, ascending: true }]);
}

addTextBox(text)
Adds a text box to the worksheet with the provided text as the content. Returns a
Shape object that represents the new text box.

TypeScript

addTextBox(text?: string): Shape;

Parameters
text string
Represents the text that will be shown in the created text box.
Returns
ExcelScript.Shape

addVerticalPageBreak(pageBreakRange)
Adds a page break before the top-left cell of the range specified.

TypeScript

addVerticalPageBreak(pageBreakRange: Range | string): PageBreak;

Parameters
pageBreakRange ExcelScript.Range | string
The range immediately after the page break to be added.

Returns
ExcelScript.PageBreak

addWorksheetCustomProperty(key, value)
Adds a new custom property that maps to the provided key. This overwrites existing
custom properties with that key.

TypeScript

addWorksheetCustomProperty(
key: string,
value: string
): WorksheetCustomProperty;

Parameters
key string
The key that identifies the custom property object. It is case-insensitive.The key is
limited to 255 characters (larger values will cause an InvalidArgument error to be
thrown.)

value string
The value of this custom property.
Returns
ExcelScript.WorksheetCustomProperty

calculate(markAllDirty)
Calculates all cells on a worksheet.

TypeScript

calculate(markAllDirty: boolean): void;

Parameters
markAllDirty boolean
True, to mark all as dirty.

Returns
void

copy(positionType, relativeTo)
Copies a worksheet and places it at the specified position.

TypeScript

copy(
positionType?: WorksheetPositionType,
relativeTo?: Worksheet
): Worksheet;

Parameters
positionType ExcelScript.WorksheetPositionType
The location in the workbook to place the newly created worksheet. The default
value is "None", which inserts the worksheet at the beginning of the worksheet.

relativeTo ExcelScript.Worksheet
The existing worksheet which determines the newly created worksheet's position.
This is only needed if positionType is "Before" or "After".
Returns
ExcelScript.Worksheet

Examples

TypeScript

/**
* This script duplicates a worksheet named "Template".
* The new worksheet is added after the template.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the worksheet named "Template".
let template = workbook.getWorksheet("Template");

// Copy the worksheet.


let newSheet = template.copy(
ExcelScript.WorksheetPositionType.after,
template
);

// Name the worksheet using the current date.


let date = new Date(Date.now());
newSheet.setName(`${date.toDateString()}`);
}

delete()
Deletes the worksheet from the workbook. Note that if the worksheet's visibility is
set to "VeryHidden", the delete operation will fail with an InvalidOperation
exception. You should first change its visibility to hidden or visible before deleting it.

TypeScript

delete(): void;

Returns
void

Examples

TypeScript
/**
* The following scripts removes the first worksheet in the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the first worksheet.
let sheet = workbook.getWorksheets()[0];

// Remove that worksheet from the workbook.


sheet.delete();
}

enterTemporaryNamedSheetView()
Creates and activates a new temporary sheet view. Temporary views are removed
when closing the application, exiting the temporary view with the exit method, or
switching to another sheet view. The temporary sheet view can also be accessed with
the empty string (""), if the temporary view exists.

TypeScript

enterTemporaryNamedSheetView(): NamedSheetView;

Returns
ExcelScript.NamedSheetView

exitActiveNamedSheetView()
Exits the currently active sheet view.

TypeScript

exitActiveNamedSheetView(): void;

Returns
void

findAll(text, criteria)
Finds all occurrences of the given string based on the criteria specified and returns
them as a RangeAreas object, comprising one or more rectangular ranges.
TypeScript

findAll(text: string, criteria: WorksheetSearchCriteria): RangeAreas;

Parameters
text string
The string to find.

criteria ExcelScript.WorksheetSearchCriteria
Additional search criteria, including whether the search needs to match the entire
cell or be case-sensitive.

Returns
ExcelScript.RangeAreas

Examples

TypeScript

/**
* This script searches through a worksheet and finds cells containing
"No".
* Those cells are filled with the color red.
* Use Range.find instead of Worksheet.findAll when you want to limit the
search to a specific range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current, active worksheet.
let worksheet = workbook.getActiveWorksheet();
let noCells = worksheet.findAll("No", { completeMatch: true });

// Set the fill color to red.


noCells.getFormat().getFill().setColor("red");
}

getActiveNamedSheetView()
Gets the worksheet's currently active sheet view.

TypeScript

getActiveNamedSheetView(): NamedSheetView;
Returns
ExcelScript.NamedSheetView

getAutoFilter()
Represents the AutoFilter object of the worksheet.

TypeScript

getAutoFilter(): AutoFilter;

Returns
ExcelScript.AutoFilter

Examples

TypeScript

/**
* This script creates an autoFilter on the worksheet that filters out
rows based on column values.
* The autoFilter filters to only include rows that have a value in
column D in the top 10 percentile
* (of column D values).
*/
function main(workbook: ExcelScript.Workbook) {
const currentSheet = workbook.getActiveWorksheet();
const dataRange = currentSheet.getUsedRange();

// Add a filter that will only show the rows with the top 10% of values
in column D
// (index 3, assuming the used range spans from at least A:D).
currentSheet.getAutoFilter().apply(dataRange, 3, {
criterion1: "10",
filterOn: ExcelScript.FilterOn.topPercent
});
}

getCell(row, column)
Gets the Range object containing the single cell based on row and column numbers.
The cell can be outside the bounds of its parent range, so long as it stays within the
worksheet grid.
TypeScript

getCell(row: number, column: number): Range;

Parameters
row number
The row number of the cell to be retrieved. Zero-indexed.

column number
The column number of the cell to be retrieved. Zero-indexed.

Returns
ExcelScript.Range

getChart(name)
Gets a chart using its name. If there are multiple charts with the same name, the first
one will be returned. If the chart doesn't exist, then this method returns undefined .

TypeScript

getChart(name: string): Chart | undefined;

Parameters
name string
Name of the chart to be retrieved.

Returns
ExcelScript.Chart | undefined

Examples

TypeScript

/**
* This sample moves an existing chart to a specific place on the
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get an existing chart named "ColumnChart".


let chart = selectedSheet.getChart("ColumnChart");

// Place the chart over the range "F1:L13".


chart.setPosition("F1", "L13");
}

getCharts()
Returns a collection of charts that are part of the worksheet.

TypeScript

getCharts(): Chart[];

Returns
ExcelScript.Chart[]

getComment(commentId)
Gets a comment from the collection based on its ID. If the comment object does not
exist, then this method returns undefined .

TypeScript

getComment(commentId: string): Comment | undefined;

Parameters
commentId string
The identifier for the comment.

Returns
ExcelScript.Comment | undefined

getCommentByCell(cellAddress)
Gets the comment from the specified cell. If there is no comment in the cell, an error
is thrown.

TypeScript

getCommentByCell(cellAddress: Range | string): Comment;

Parameters
cellAddress ExcelScript.Range | string
The cell which the comment is on. This can be a Range object or a string. If it's a
string, it must contain the full address, including the sheet name. An
InvalidArgument error is thrown if the provided range is larger than one cell.

Returns
ExcelScript.Comment

getCommentByReplyId(replyId)
Gets the comment to which the given reply is connected.

TypeScript

getCommentByReplyId(replyId: string): Comment;

Parameters
replyId string
The identifier of comment reply.

Returns
ExcelScript.Comment

getComments()
Returns a collection of all the Comments objects on the worksheet.

TypeScript
getComments(): Comment[];

Returns
ExcelScript.Comment[]

getCustomProperties()
Gets a collection of worksheet-level custom properties.

TypeScript

getCustomProperties(): WorksheetCustomProperty[];

Returns
ExcelScript.WorksheetCustomProperty[]

getEnableCalculation()
Determines if Excel should recalculate the worksheet when necessary. True if Excel
recalculates the worksheet when necessary. False if Excel doesn't recalculate the
sheet.

TypeScript

getEnableCalculation(): boolean;

Returns
boolean

getFreezePanes()
Gets an object that can be used to manipulate frozen panes on the worksheet.

TypeScript

getFreezePanes(): WorksheetFreezePanes;
Returns
ExcelScript.WorksheetFreezePanes

getHorizontalPageBreaks()
Gets the horizontal page break collection for the worksheet. This collection only
contains manual page breaks.

TypeScript

getHorizontalPageBreaks(): PageBreak[];

Returns
ExcelScript.PageBreak[]

getId()
Returns a value that uniquely identifies the worksheet in a given workbook. The value
of the identifier remains the same even when the worksheet is renamed or moved.

TypeScript

getId(): string;

Returns
string

getName()
The display name of the worksheet. The name must be fewer than 32 characters.

TypeScript

getName(): string;

Returns
string
Examples

TypeScript

/**
* This sample gets all the worksheet names in the workbook.
* It then logs those names to the console.
*/
function main(workbook: ExcelScript.Workbook) {
// Create an array to hold the worksheet names.
let worksheetNames = [];

// Iterate over the worksheet collection in the workbook.


for (let worksheet of workbook.getWorksheets()) {
worksheetNames.push(worksheet.getName());
}

// Log the array of worksheet names.


console.log(worksheetNames);
}

getNamedItem(name)
Gets a NamedItem object using its name. If the object does not exist, then this
method returns undefined .

TypeScript

getNamedItem(name: string): NamedItem | undefined;

Parameters
name string
Nameditem name.

Returns
ExcelScript.NamedItem | undefined

getNamedSheetView(key)
Gets a sheet view using its name. If the sheet view object does not exist, then this
method returns undefined .

TypeScript
getNamedSheetView(key: string): NamedSheetView | undefined;

Parameters
key string
The case-sensitive name of the sheet view. Use the empty string ("") to get the
temporary sheet view, if the temporary view exists.

Returns
ExcelScript.NamedSheetView | undefined

getNamedSheetViews()
Returns a collection of sheet views that are present in the worksheet.

TypeScript

getNamedSheetViews(): NamedSheetView[];

Returns
ExcelScript.NamedSheetView[]

getNames()
Collection of names scoped to the current worksheet.

TypeScript

getNames(): NamedItem[];

Returns
ExcelScript.NamedItem[]

getNext(visibleOnly)
Gets the worksheet that follows this one. If there are no worksheets following this
one, then this method returns undefined .
TypeScript

getNext(visibleOnly?: boolean): Worksheet;

Parameters
visibleOnly boolean
Optional. If true , considers only visible worksheets, skipping over any hidden ones.

Returns
ExcelScript.Worksheet

getPageLayout()
Gets the PageLayout object of the worksheet.

TypeScript

getPageLayout(): PageLayout;

Returns
ExcelScript.PageLayout

Examples

TypeScript

/**
* This script sets the printing orientation for the entire workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Go to each worksheet so the print settings are consistent.
workbook.getWorksheets().forEach((sheet) => {
const pageLayout = sheet.getPageLayout();

// Print every page with a landscape orientation.


pageLayout.setOrientation(ExcelScript.PageOrientation.landscape);
});
}

getPivotTable(name)
Gets a PivotTable by name. If the PivotTable does not exist, then this method returns
undefined .

TypeScript

getPivotTable(name: string): PivotTable | undefined;

Parameters
name string
Name of the PivotTable to be retrieved.

Returns
ExcelScript.PivotTable | undefined

getPivotTables()
Collection of PivotTables that are part of the worksheet.

TypeScript

getPivotTables(): PivotTable[];

Returns
ExcelScript.PivotTable[]

getPosition()
The zero-based position of the worksheet within the workbook.

TypeScript

getPosition(): number;

Returns
number

getPrevious(visibleOnly)
Gets the worksheet that precedes this one. If there are no previous worksheets, then
this method returns undefined .

TypeScript

getPrevious(visibleOnly?: boolean): Worksheet;

Parameters
visibleOnly boolean
Optional. If true , considers only visible worksheets, skipping over any hidden ones.

Returns
ExcelScript.Worksheet

getProtection()
Returns the sheet protection object for a worksheet.

TypeScript

getProtection(): WorksheetProtection;

Returns
ExcelScript.WorksheetProtection

Examples

TypeScript

/**
* This script protects cells from being selected on the current
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the protection settings for the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const sheetProtection = currentSheet.getProtection();

// Create a new WorksheetProtectionOptions object with the


selectionMode property set to `none`.
let protectionOptions : ExcelScript.WorksheetProtectionOptions = {
selectionMode: ExcelScript.ProtectionSelectionMode.none
}

// Apply the given protection options.


sheetProtection.protect(protectionOptions);
}

getRange(address)
Gets the Range object, representing a single rectangular block of cells, specified by
the address or name.

TypeScript

getRange(address?: string): Range;

Parameters
address string
Optional. The string representing the address or name of the range. For example,
"A1:B2". If not specified, the entire worksheet range is returned.

Returns
ExcelScript.Range

Examples

TypeScript

/**
* This sample reads the value of A1 and prints it to the console.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current worksheet.
let selectedSheet = workbook.getActiveWorksheet();

// Get the value of cell A1.


let range = selectedSheet.getRange("A1");

// Print the value of A1.


console.log(range.getValue());
}
getRangeByIndexes(startRow, startColumn, rowCount,
columnCount)
Gets the Range object beginning at a particular row index and column index, and
spanning a certain number of rows and columns.

TypeScript

getRangeByIndexes(
startRow: number,
startColumn: number,
rowCount: number,
columnCount: number
): Range;

Parameters
startRow number
Start row (zero-indexed).

startColumn number
Start column (zero-indexed).

rowCount number
Number of rows to include in the range.

columnCount number
Number of columns to include in the range.

Returns
ExcelScript.Range

getRanges(address)
Gets the RangeAreas object, representing one or more blocks of rectangular ranges,
specified by the address or name.

TypeScript

getRanges(address?: string): RangeAreas;


Parameters
address string
Optional. A string containing the comma-separated or semicolon-separated
addresses or names of the individual ranges. For example, "A1:B2, A5:B5" or "A1:B2;
A5:B5". If not specified, a RangeAreas object for the entire worksheet is returned.

Returns
ExcelScript.RangeAreas

getShape(key)
Gets a shape using its name or ID. If the shape object does not exist, then this
method returns undefined .

TypeScript

getShape(key: string): Shape | undefined;

Parameters
key string
The name or ID of the shape to be retrieved.

Returns
ExcelScript.Shape | undefined

getShapes()
Returns the collection of all the Shape objects on the worksheet.

TypeScript

getShapes(): Shape[];

Returns
ExcelScript.Shape[]
getShowGridlines()
Specifies if gridlines are visible to the user.

TypeScript

getShowGridlines(): boolean;

Returns
boolean

getShowHeadings()
Specifies if headings are visible to the user.

TypeScript

getShowHeadings(): boolean;

Returns
boolean

getSlicer(key)
Gets a slicer using its name or ID. If the slicer doesn't exist, then this method returns
undefined .

TypeScript

getSlicer(key: string): Slicer | undefined;

Parameters
key string
Name or ID of the slicer to be retrieved.

Returns
ExcelScript.Slicer | undefined
getSlicers()
Returns a collection of slicers that are part of the worksheet.

TypeScript

getSlicers(): Slicer[];

Returns
ExcelScript.Slicer[]

getStandardHeight()
Returns the standard (default) height of all the rows in the worksheet, in points.

TypeScript

getStandardHeight(): number;

Returns
number

getStandardWidth()
Specifies the standard (default) width of all the columns in the worksheet. One unit
of column width is equal to the width of one character in the Normal style. For
proportional fonts, the width of the character 0 (zero) is used.

TypeScript

getStandardWidth(): number;

Returns
number

getTabColor()
The tab color of the worksheet. When retrieving the tab color, if the worksheet is
invisible, the value will be null . If the worksheet is visible but the tab color is set to
auto, an empty string will be returned. Otherwise, the property will be set to a color,
in the form #RRGGBB (e.g., "FFA500"). When setting the color, use an empty-string to
set an "auto" color, or a real color otherwise.

TypeScript

getTabColor(): string;

Returns
string

getTabId()
Returns a value representing this worksheet that can be read by Open Office XML.
This is an integer value, which is different from worksheet.id (which returns a
globally unique identifier) and worksheet.name (which returns a value such as
"Sheet1").

TypeScript

getTabId(): number;

Returns
number

getTable(key)
Gets a table by name or ID. If the table doesn't exist, then this method returns
undefined .

TypeScript

getTable(key: string): Table | undefined;

Parameters
key string
Name or ID of the table to be retrieved.

Returns
ExcelScript.Table | undefined

getTables()
Collection of tables that are part of the worksheet.

TypeScript

getTables(): Table[];

Returns
ExcelScript.Table[]

getUsedRange(valuesOnly)
TypeScript

getUsedRange(valuesOnly?: boolean): Range;

Parameters
valuesOnly boolean
Optional. Considers only cells with values as used cells.

Returns
ExcelScript.Range

getVerticalPageBreaks()
Gets the vertical page break collection for the worksheet. This collection only
contains manual page breaks.

TypeScript

getVerticalPageBreaks(): PageBreak[];
Returns
ExcelScript.PageBreak[]

getVisibility()
The visibility of the worksheet.

TypeScript

getVisibility(): SheetVisibility;

Returns
ExcelScript.SheetVisibility

getWorksheetCustomProperty(key)
Gets a custom property object by its key, which is case-insensitive. If the custom
property doesn't exist, then this method returns undefined .

TypeScript

getWorksheetCustomProperty(
key: string
): WorksheetCustomProperty | undefined;

Parameters
key string
The key that identifies the custom property object. It is case-insensitive.

Returns
ExcelScript.WorksheetCustomProperty | undefined

refreshAllPivotTables()
Refreshes all the pivot tables in the collection.

TypeScript
refreshAllPivotTables(): void;

Returns
void

removeAllHorizontalPageBreaks()
Resets all manual page breaks in the collection.

TypeScript

removeAllHorizontalPageBreaks(): void;

Returns
void

removeAllVerticalPageBreaks()
Resets all manual page breaks in the collection.

TypeScript

removeAllVerticalPageBreaks(): void;

Returns
void

replaceAll(text, replacement, criteria)


Finds and replaces the given string based on the criteria specified within the current
worksheet.

TypeScript

replaceAll(
text: string,
replacement: string,
criteria: ReplaceCriteria
): number;

Parameters
text string
String to find.

replacement string
The string that replaces the original string.

criteria ExcelScript.ReplaceCriteria
Additional replacement criteria.

Returns
number

setEnableCalculation(enableCalculation)
Determines if Excel should recalculate the worksheet when necessary. True if Excel
recalculates the worksheet when necessary. False if Excel doesn't recalculate the
sheet.

TypeScript

setEnableCalculation(enableCalculation: boolean): void;

Parameters
enableCalculation boolean

Returns
void

setName(name)
The display name of the worksheet. The name must be fewer than 32 characters.

TypeScript
setName(name: string): void;

Parameters
name string

Returns
void

Examples

TypeScript

/**
* This sample renames a worksheet from "Sheet1" to "SALES".
*/
function main(workbook: ExcelScript.Workbook) {
// Get a worksheet named "Sheet1".
const sheet = workbook.getWorksheet('Sheet1');

// Set its name to SALES.


sheet.setName('SALES');
}

setPosition(position)
The zero-based position of the worksheet within the workbook.

TypeScript

setPosition(position: number): void;

Parameters
position number

Returns
void

Examples
TypeScript

/**
* This sample sets the worksheet named "SALES" as the first sheet in the
workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Get a worksheet named "SALES".
const sheet = workbook.getWorksheet('SALES');
// Position the worksheet at the beginning of the workbook.
sheet.setPosition(0);
}

setShowGridlines(showGridlines)
Specifies if gridlines are visible to the user.

TypeScript

setShowGridlines(showGridlines: boolean): void;

Parameters
showGridlines boolean

Returns
void

setShowHeadings(showHeadings)
Specifies if headings are visible to the user.

TypeScript

setShowHeadings(showHeadings: boolean): void;

Parameters
showHeadings boolean

Returns
void

setStandardWidth(standardWidth)
Specifies the standard (default) width of all the columns in the worksheet. One unit
of column width is equal to the width of one character in the Normal style. For
proportional fonts, the width of the character 0 (zero) is used.

TypeScript

setStandardWidth(standardWidth: number): void;

Parameters
standardWidth number

Returns
void

setTabColor(tabColor)
The tab color of the worksheet. When retrieving the tab color, if the worksheet is
invisible, the value will be null . If the worksheet is visible but the tab color is set to
auto, an empty string will be returned. Otherwise, the property will be set to a color,
in the form #RRGGBB (e.g., "FFA500"). When setting the color, use an empty-string to
set an "auto" color, or a real color otherwise.

TypeScript

setTabColor(tabColor: string): void;

Parameters
tabColor string

Returns
void

Examples
TypeScript

/**
* This script sets the tab color of every worksheet in the workbook to
red.
*/
function main(workbook: ExcelScript.Workbook) {
// Get all the worksheets in the workbook.
let sheets = workbook.getWorksheets();

// Set the tab color of each worksheet to a random color.


for (let sheet of sheets) {
// Set the color of the current worksheet's tab to red.
sheet.setTabColor("red");
}
}

setVisibility(visibility)
The visibility of the worksheet.

TypeScript

setVisibility(visibility: SheetVisibility): void;

Parameters
visibility ExcelScript.SheetVisibility

Returns
void

Examples

TypeScript

/**
* This script unhides all the worksheets in the workbook.
*/
function main(workbook: ExcelScript.Workbook) {
// Iterate over each worksheet.
workbook.getWorksheets().forEach((worksheet) => {
// Set the worksheet visibility to visible.
worksheet.setVisibility(ExcelScript.SheetVisibility.visible);
});
}

showOutlineLevels(rowLevels, columnLevels)
Shows row or column groups by their outline levels. Outlines groups and
summarizes a list of data in the worksheet. The rowLevels and columnLevels
parameters specify how many levels of the outline will be displayed. The acceptable
argument range is between 0 and 8. A value of 0 does not change the current
display. A value greater than the current number of levels displays all the levels.

TypeScript

showOutlineLevels(rowLevels: number, columnLevels: number): void;

Parameters
rowLevels number
The number of row levels of an outline to display.

columnLevels number
The number of column levels of an outline to display.

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.WorksheetCustomProperty
interface
Reference
Package: ExcelScript

Represents a worksheet-level custom property.

Methods
ノ Expand table

delete() Deletes the custom property.

getKey() Gets the key of the custom property. Custom property keys are case-insensitive.
The key is limited to 255 characters (larger values will cause an InvalidArgument
error to be thrown.)

getValue() Gets or sets the value of the custom property.

set Gets or sets the value of the custom property.


Value(value)

Method Details

delete()
Deletes the custom property.

TypeScript

delete(): void;

Returns
void

getKey()
Gets the key of the custom property. Custom property keys are case-insensitive. The
key is limited to 255 characters (larger values will cause an InvalidArgument error to
be thrown.)

TypeScript

getKey(): string;

Returns
string

getValue()
Gets or sets the value of the custom property.

TypeScript

getValue(): string;

Returns
string

setValue(value)
Gets or sets the value of the custom property.

TypeScript

setValue(value: string): void;

Parameters
value string

Returns
void
6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.WorksheetFreezePanes
interface
Reference
Package: ExcelScript

Methods
ノ Expand table

freezeAt(frozen Sets the frozen cells in the active worksheet view. The range provided
Range) corresponds to cells that will be frozen in the top- and left-most pane.

freeze Freeze the first column or columns of the worksheet in place.


Columns(count)

freeze Freeze the top row or rows of the worksheet in place.


Rows(count)

getLocation() Gets a range that describes the frozen cells in the active worksheet view. The
frozen range corresponds to cells that are frozen in the top- and left-most
pane. If there is no frozen pane, then this method returns undefined .

unfreeze() Removes all frozen panes in the worksheet.

Method Details

freezeAt(frozenRange)
Sets the frozen cells in the active worksheet view. The range provided corresponds to
cells that will be frozen in the top- and left-most pane.

TypeScript

freezeAt(frozenRange: Range | string): void;

Parameters
frozenRange ExcelScript.Range | string
A range that represents the cells to be frozen, or null to remove all frozen panes.
Returns
void

freezeColumns(count)
Freeze the first column or columns of the worksheet in place.

TypeScript

freezeColumns(count?: number): void;

Parameters
count number
Optional number of columns to freeze, or zero to unfreeze all columns

Returns
void

freezeRows(count)
Freeze the top row or rows of the worksheet in place.

TypeScript

freezeRows(count?: number): void;

Parameters
count number
Optional number of rows to freeze, or zero to unfreeze all rows

Returns
void

getLocation()
Gets a range that describes the frozen cells in the active worksheet view. The frozen
range corresponds to cells that are frozen in the top- and left-most pane. If there is
no frozen pane, then this method returns undefined .

TypeScript

getLocation(): Range;

Returns
ExcelScript.Range

unfreeze()
Removes all frozen panes in the worksheet.

TypeScript

unfreeze(): void;

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.WorksheetProtection
interface
Reference
Package: ExcelScript

Represents the protection of a worksheet object.

Remarks

Examples

TypeScript

/**
* This script pauses the protection of a worksheet by using the provided
password.
* This password could come from a Power Automate flow.
*/
function main(workbook: ExcelScript.Workbook, password: string) {
// Get the worksheet named "Sales".
const sheet = workbook.getWorksheet("Sales");
const protection: ExcelScript.WorksheetProtection = sheet.getProtection();

// Check if the provided password works.


if (protection.checkPassword(password)) {
protection.pauseProtection(password);

// Edit the worksheet...

protection.resumeProtection();
} else {
console.log("Incorrect password");
}
}

Methods
ノ Expand table

addAllowEdit Adds an AllowEditRange object to the worksheet. Worksheet protection


Range(title, range must be disabled or paused for this method to work properly. If
Address, options)
worksheet protection is enabled and not paused, then this method
throws an AccessDenied error and the add operation fails.

check Specifies if the password can be used to unlock worksheet protection.


Password(password) This method doesn't change the worksheet protection state. If a
password is entered but no password is required to unlock worksheet
protection, this method will return false.

getAllowEdit Gets the AllowEditRange object by its title.


Range(key)

getAllowEditRanges() Specifies the AllowEditRangeCollection object found in this worksheet.


This is a collection of AllowEditRange objects, which work with
worksheet protection properties. When worksheet protection is
enabled, an AllowEditRange object can be used to allow editing of a
specific range, while maintaining protection on the rest of the
worksheet.

getCanPause Specifies if protection can be paused for this worksheet.


Protection()

getIsPassword Specifies if the sheet is password protected.


Protected()

getIsPaused() Specifies if worksheet protection is paused.

getOptions() Specifies the protection options for the worksheet.

getProtected() Specifies if the worksheet is protected.

getSavedOptions() Specifies the protection options saved in the worksheet. This will return
the same WorksheetProtectionOptions object regardless of the
worksheet protection state.

pause Pauses worksheet protection for the given worksheet object for the user
Protection(password) in the current session. This method does nothing if worksheet
protection isn't enabled or is already paused. If the password is
incorrect, then this method throws an InvalidArgument error and fails to
pause protection. This method does not change the protection state if
worksheet protection is not enabled or already paused.

pauseProtectionForAll Pauses worksheet protection for all AllowEditRange objects found in


AllowEdit this worksheet that have the given password for the user in the current
Ranges(password) session. This method does nothing if worksheet protection isn't enabled
or is paused. If worksheet protection cannot be paused, this method
throws an UnsupportedOperation error and fails to pause protection for
the range. If the password does not match any AllowEditRange objects
in the collection, then this method throws a BadPassword error and fails
to pause protection for any range in the collection.
protect(options, Protects a worksheet. Fails if the worksheet has already been protected.
password)

resumeProtection() Resumes worksheet protection for the given worksheet object for the
user in a given session. Worksheet protection must be paused for this
method to work. If worksheet protection is not paused, then this
method will not change the protection state of the worksheet.

setPassword(password) Changes the password associated with the WorksheetProtection object.


Setting the password as an empty string ("") or as null will remove
password protection from the WorksheetProtection object. Worksheet
protection must be enabled and paused for this method to work
properly. If worksheet protection is disabled, this method throws an
InvalidOperation error and fails to change the password. If worksheet
protection is enabled and not paused, this method throws an
AccessDenied error and fails to change the password.

unprotect(password) Unprotects a worksheet.

update Change the worksheet protection options associated with the


Options(options) WorksheetProtection object. Worksheet protection must be disabled or
paused for this method to work properly. If worksheet protection is
enabled and not paused, this method throws an AccessDenied error and
fails to change the worksheet protection options.

Method Details

addAllowEditRange(title, rangeAddress, options)


Adds an AllowEditRange object to the worksheet. Worksheet protection must be
disabled or paused for this method to work properly. If worksheet protection is
enabled and not paused, then this method throws an AccessDenied error and the
add operation fails.

TypeScript

addAllowEditRange(
title: string,
rangeAddress: string,
options?: AllowEditRangeOptions
): void;

Parameters
title string
The title string of the AllowEditRange object to be added.

rangeAddress string
The range address of the AllowEditRange object to be added.

options ExcelScript.AllowEditRangeOptions
Additional options to be added to the AllowEditRange object, such as the password.

Returns
void

Examples

TypeScript

/**
* This script adds a password-protected, editable range
* to an otherwise protected worksheet.
*/
function main(workbook: ExcelScript.Workbook, password: string) {
// Get the protection object for the "Data" worksheet.
const dataSheet = workbook.getWorksheet("Data");
const sheetProtection = dataSheet.getProtection();

// Set the password needed to edit the range to be the user provided
string.
const editRangeProperties : ExcelScript.AllowEditRangeOptions = {
password: password
};

// Set range "D2:D6" to be editable if the password is provided.


sheetProtection.addAllowEditRange("Notes Section", "D2:D6",
editRangeProperties);

// Protect the worksheet.


sheetProtection.protect();
}

checkPassword(password)
Specifies if the password can be used to unlock worksheet protection. This method
doesn't change the worksheet protection state. If a password is entered but no
password is required to unlock worksheet protection, this method will return false.

TypeScript
checkPassword(password?: string): boolean;

Parameters
password string
The password to check against the protected worksheet.

Returns
boolean

getAllowEditRange(key)
Gets the AllowEditRange object by its title.

TypeScript

getAllowEditRange(key: string): AllowEditRange | undefined;

Parameters
key string
The title of the AllowEditRange .

Returns
ExcelScript.AllowEditRange | undefined

getAllowEditRanges()
Specifies the AllowEditRangeCollection object found in this worksheet. This is a
collection of AllowEditRange objects, which work with worksheet protection
properties. When worksheet protection is enabled, an AllowEditRange object can be
used to allow editing of a specific range, while maintaining protection on the rest of
the worksheet.

TypeScript

getAllowEditRanges(): AllowEditRange[];
Returns
ExcelScript.AllowEditRange[]

getCanPauseProtection()
Specifies if protection can be paused for this worksheet.

TypeScript

getCanPauseProtection(): boolean;

Returns
boolean

getIsPasswordProtected()
Specifies if the sheet is password protected.

TypeScript

getIsPasswordProtected(): boolean;

Returns
boolean

getIsPaused()
Specifies if worksheet protection is paused.

TypeScript

getIsPaused(): boolean;

Returns
boolean

getOptions()
Specifies the protection options for the worksheet.

TypeScript

getOptions(): WorksheetProtectionOptions;

Returns
ExcelScript.WorksheetProtectionOptions

getProtected()
Specifies if the worksheet is protected.

TypeScript

getProtected(): boolean;

Returns
boolean

getSavedOptions()
Specifies the protection options saved in the worksheet. This will return the same
WorksheetProtectionOptions object regardless of the worksheet protection state.

TypeScript

getSavedOptions(): WorksheetProtectionOptions;

Returns
ExcelScript.WorksheetProtectionOptions

pauseProtection(password)
Pauses worksheet protection for the given worksheet object for the user in the
current session. This method does nothing if worksheet protection isn't enabled or is
already paused. If the password is incorrect, then this method throws an
InvalidArgument error and fails to pause protection. This method does not change

the protection state if worksheet protection is not enabled or already paused.

TypeScript

pauseProtection(password?: string): void;

Parameters
password string
The password associated with the protected worksheet.

Returns
void

pauseProtectionForAllAllowEditRanges(password)
Pauses worksheet protection for all AllowEditRange objects found in this worksheet
that have the given password for the user in the current session. This method does
nothing if worksheet protection isn't enabled or is paused. If worksheet protection
cannot be paused, this method throws an UnsupportedOperation error and fails to
pause protection for the range. If the password does not match any AllowEditRange
objects in the collection, then this method throws a BadPassword error and fails to
pause protection for any range in the collection.

TypeScript

pauseProtectionForAllAllowEditRanges(password: string): void;

Parameters
password string
The password to pause protection on the AllowEditRange objects.

Returns
void

protect(options, password)
Protects a worksheet. Fails if the worksheet has already been protected.

TypeScript

protect(options?: WorksheetProtectionOptions, password?: string): void;

Parameters
options ExcelScript.WorksheetProtectionOptions
Optional. Sheet protection options.

password string
Optional. Sheet protection password.

Returns
void

Examples

TypeScript

/**
* This script protects cells from being selected on the current
worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the protection settings for the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const sheetProtection = currentSheet.getProtection();

// Create a new WorksheetProtectionOptions object with the


selectionMode property set to `none`.
let protectionOptions : ExcelScript.WorksheetProtectionOptions = {
selectionMode: ExcelScript.ProtectionSelectionMode.none
}

// Apply the given protection options.


sheetProtection.protect(protectionOptions);
}

resumeProtection()
Resumes worksheet protection for the given worksheet object for the user in a given
session. Worksheet protection must be paused for this method to work. If worksheet
protection is not paused, then this method will not change the protection state of
the worksheet.

TypeScript

resumeProtection(): void;

Returns
void

setPassword(password)
Changes the password associated with the WorksheetProtection object. Setting the
password as an empty string ("") or as null will remove password protection from
the WorksheetProtection object. Worksheet protection must be enabled and paused
for this method to work properly. If worksheet protection is disabled, this method
throws an InvalidOperation error and fails to change the password. If worksheet
protection is enabled and not paused, this method throws an AccessDenied error and
fails to change the password.

TypeScript

setPassword(password?: string): void;

Parameters
password string
The password associated with the WorksheetProtection object.

Returns
void

unprotect(password)
Unprotects a worksheet.

TypeScript

unprotect(password?: string): void;


Parameters
password string
Sheet protection password.

Returns
void

updateOptions(options)
Change the worksheet protection options associated with the WorksheetProtection
object. Worksheet protection must be disabled or paused for this method to work
properly. If worksheet protection is enabled and not paused, this method throws an
AccessDenied error and fails to change the worksheet protection options.

TypeScript

updateOptions(options: WorksheetProtectionOptions): void;

Parameters
options ExcelScript.WorksheetProtectionOptions
The options interface associated with the WorksheetProtection object.

Returns
void

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.WorksheetProtectionOptions
interface
Reference
Package: ExcelScript

Represents the options in sheet protection.

Remarks

Examples

TypeScript

/**
* This script protects cells from being selected on the current worksheet.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the protection settings for the current worksheet.
const currentSheet = workbook.getActiveWorksheet();
const sheetProtection = currentSheet.getProtection();

// Create a new WorksheetProtectionOptions object with the selectionMode


property set to `none`.
let protectionOptions : ExcelScript.WorksheetProtectionOptions = {
selectionMode: ExcelScript.ProtectionSelectionMode.none
}

// Apply the given protection options.


sheetProtection.protect(protectionOptions);
}

Properties
ノ Expand table

allowAutoFilter Represents the worksheet protection option allowing use of the AutoFilter
feature.

allowDelete Represents the worksheet protection option allowing deleting of columns.


Columns

allowDeleteRows Represents the worksheet protection option allowing deleting of rows.


allowEditObjects Represents the worksheet protection option allowing editing of objects.

allowEditScenarios Represents the worksheet protection option allowing editing of scenarios.

allowFormatCells Represents the worksheet protection option allowing formatting of cells.

allowFormat Represents the worksheet protection option allowing formatting of


Columns columns.

allowFormatRows Represents the worksheet protection option allowing formatting of rows.

allowInsertColumns Represents the worksheet protection option allowing inserting of columns.

allowInsert Represents the worksheet protection option allowing inserting of


Hyperlinks hyperlinks.

allowInsertRows Represents the worksheet protection option allowing inserting of rows.

allowPivotTables Represents the worksheet protection option allowing use of the PivotTable
feature.

allowSort Represents the worksheet protection option allowing use of the sort
feature.

selectionMode Represents the worksheet protection option of selection mode.

Property Details

allowAutoFilter
Represents the worksheet protection option allowing use of the AutoFilter feature.

TypeScript

allowAutoFilter?: boolean;

Property Value
boolean

allowDeleteColumns
Represents the worksheet protection option allowing deleting of columns.

TypeScript
allowDeleteColumns?: boolean;

Property Value
boolean

allowDeleteRows
Represents the worksheet protection option allowing deleting of rows.

TypeScript

allowDeleteRows?: boolean;

Property Value
boolean

allowEditObjects
Represents the worksheet protection option allowing editing of objects.

TypeScript

allowEditObjects?: boolean;

Property Value
boolean

allowEditScenarios
Represents the worksheet protection option allowing editing of scenarios.

TypeScript

allowEditScenarios?: boolean;

Property Value
boolean

allowFormatCells
Represents the worksheet protection option allowing formatting of cells.

TypeScript

allowFormatCells?: boolean;

Property Value
boolean

allowFormatColumns
Represents the worksheet protection option allowing formatting of columns.

TypeScript

allowFormatColumns?: boolean;

Property Value
boolean

allowFormatRows
Represents the worksheet protection option allowing formatting of rows.

TypeScript

allowFormatRows?: boolean;

Property Value
boolean

allowInsertColumns
Represents the worksheet protection option allowing inserting of columns.
TypeScript

allowInsertColumns?: boolean;

Property Value
boolean

allowInsertHyperlinks
Represents the worksheet protection option allowing inserting of hyperlinks.

TypeScript

allowInsertHyperlinks?: boolean;

Property Value
boolean

allowInsertRows
Represents the worksheet protection option allowing inserting of rows.

TypeScript

allowInsertRows?: boolean;

Property Value
boolean

allowPivotTables
Represents the worksheet protection option allowing use of the PivotTable feature.

TypeScript

allowPivotTables?: boolean;
Property Value
boolean

allowSort
Represents the worksheet protection option allowing use of the sort feature.

TypeScript

allowSort?: boolean;

Property Value
boolean

selectionMode
Represents the worksheet protection option of selection mode.

TypeScript

selectionMode?: ProtectionSelectionMode;

Property Value
ExcelScript.ProtectionSelectionMode

6 Collaborate with us on
GitHub Office Scripts feedback
The source for this content can Office Scripts is an open source project.
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
more information, see our
 Provide product feedback
contributor guide.
ExcelScript.WorksheetSearchCriteria
interface
Reference
Package: ExcelScript

Represents the worksheet search criteria to be used.

Remarks

Examples

TypeScript

/**
* This script searches through a worksheet and finds cells containing "No".
* Those cells are filled with the color red.
* Use Range.find instead of Worksheet.findAll when you want to limit the
search to a specific range.
*/
function main(workbook: ExcelScript.Workbook) {
// Get the current, active worksheet.
const worksheet = workbook.getActiveWorksheet();

// Get all the cells that exactly contain the string "No".
const searchCriteria: ExcelScript.WorksheetSearchCriteria = {
completeMatch: true,
matchCase: true
};
const noCells = worksheet.findAll("No", searchCriteria);

// Set the fill color to red.


noCells.getFormat().getFill().setColor("red");
}

Properties
ノ Expand table

complete Specifies if the match needs to be complete or partial. A complete match matches
Match the entire contents of the cell. A partial match matches a substring within the
content of the cell (e.g., cat partially matches caterpillar and scatter ). Default is
false (partial).
matchCase Specifies if the match is case-sensitive. Default is false (case-insensitive).

Property Details

completeMatch
Specifies if the match needs to be complete or partial. A complete match matches
the entire contents of the cell. A partial match matches a substring within the
content of the cell (e.g., cat partially matches caterpillar and scatter ). Default is
false (partial).

TypeScript

completeMatch?: boolean;

Property Value
boolean

matchCase
Specifies if the match is case-sensitive. Default is false (case-insensitive).

TypeScript

matchCase?: boolean;

Property Value
boolean

6 Collaborate with us on
GitHub Office Scripts feedback
Office Scripts is an open source project.
The source for this content can
Select a link to provide feedback:
be found on GitHub, where you
can also create and review
 Open a documentation issue
issues and pull requests. For
 Provide product feedback
more information, see our
contributor guide.

You might also like