Javascript API Office Scripts Office Scripts
Javascript API Office Scripts Office Scripts
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.
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 The interface used to construct optional fields of the AllowEditRange object.
EditRangeOptions
ExcelScript.Auto Represents the AutoFilter object. AutoFilter turns the values in Excel column
Filter into specific filters based on the cell contents.
ExcelScript.Chart Encapsulates the format properties for the overall chart area.
AreaFormat
ExcelScript.Chart Encapsulates the bin options for histogram charts and pareto charts.
BinOptions
ExcelScript.Chart Encapsulates the format properties for the chart data labels.
DataLabelFormat
ExcelScript.Chart This object represents the attributes for a chart's error bars.
ErrorBars
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 This object represents the attributes for a chart plot area.
PlotArea
ExcelScript.Chart This object represents the attributes for a chart trendline object.
Trendline
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 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 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. An object encapsulating a conditional format's range, format, rule, and other
Conditional properties.
Format
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. Provides information based on current system culture settings. This includes
CultureInfo the culture names, number formatting, and other culturally dependent
settings.
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. Defines the culturally appropriate format of displaying numbers. This is based
DatetimeFormat on current system culture settings.
Info
ExcelScript.HeaderFooter
ExcelScript.HeaderFooterGroup
ExcelScript.Line Represents a line inside a worksheet. To get the corresponding Shape object,
use Line.shape .
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 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.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.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.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.Shape Represents the font attributes, such as font name, font size, and color, for a
Font shape's TextRange object.
ExcelScript.ShowAsRule
ExcelScript.Slicer Represents a slicer style, which defines style elements by region of the slicer.
Style
ExcelScript.Table Represents a table style, which defines the style elements by region of the
Style table.
ExcelScript.Text Contains the text that is attached to a shape, in addition to properties and
Range methods for manipulating the text.
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. An Excel worksheet is a grid of cells. It can contain data, tables, charts, etc.
Worksheet
ExcelScript.WorksheetFreezePanes
Enums
ノ Expand table
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.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.ChartDisplayBlanksAs
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 Represents the dimensions when getting values from chart series.
SeriesDimension
ExcelScript.ChartSplitType
ExcelScript.ChartTickLabelAlignment
ExcelScript.ChartTrendlineType
ExcelScript.ChartType
ExcelScript.ChartUnderlineStyle
ExcelScript.ClearApplyTo
ExcelScript. Represents the criteria of the preset criteria conditional format type.
ConditionalFormat
PresetCriterion
ExcelScript.ConditionalFormatType
ExcelScript.ConditionalRangeBorderIndex
ExcelScript.ConditionalRangeBorderLineStyle
ExcelScript.ConditionalRangeFontUnderlineStyle
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.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.GroupOption
ExcelScript.HeaderFooterState
ExcelScript.HorizontalAlignment
ExcelScript.IconSet
ExcelScript.ImageFittingMode
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.NamedItemScope
ExcelScript.NamedItemType
ExcelScript.PageOrientation
ExcelScript.PaperType
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.RangeCopyType
ExcelScript.RangeUnderlineStyle
ExcelScript.RangeValueType
ExcelScript.ReadingOrder
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 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 where in the z-order a shape should be moved relative to other
ZOrder shapes.
ExcelScript.SheetVisibility
ExcelScript.SortDataOption
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
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
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];
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.
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();
// 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();
// 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();
// 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
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();
// 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).
fillSeries Populates the adjacent cells with data that follows a pattern in the copied cells.
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);
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);
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);
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();
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()}`);
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
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);
Fields
ノ Expand table
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
Fields
ノ Expand 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.ChartAxisDisplayUnit enum
Reference
Package: ExcelScript
Fields
ノ Expand table
none Default option. This will reset display unit to the axis, and set unit label
invisible.
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
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.ChartBinType enum
Reference
Package: ExcelScript
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
Fields
ノ Expand table
externalRange The data source type of the chart series is an external range.
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
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
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");
// 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();
// 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];
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
Fields
ノ Expand table
bubbleSizes The chart series axis for the bubble sizes in bubble charts.
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
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
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
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();
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];
// Clear all the formatting that is not applied by the table and the table
style.
range.clear(ExcelScript.ClearApplyTo.formats);
}
Fields
ノ Expand table
all
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
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");
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);
}
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
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
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
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();
// 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
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
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");
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
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");
// 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
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();
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();
// 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
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");
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
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");
firstColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.containsT
ext).getTextComparison();
// 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();
// 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);
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 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
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");
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
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();
/*
* 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
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.
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];
Fields
ノ Expand table
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);
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);
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");
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];
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();
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
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);
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);
Fields
ノ Expand 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
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.
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];
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");
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];
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();
// Add a blank first row and push existing data down a row.
let firstRow = currentSheet.getRange("1:1");
firstRow.insert(ExcelScript.InsertShiftDirection.down);
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);
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");
// 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
};
Fields
ノ Expand table
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
Fields
ノ Expand 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
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();
// 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.
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.
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();
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
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();
// 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
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
Fields
ノ Expand 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.PivotFilterTopBottom
Criterion enum
Reference
Package: ExcelScript
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
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");
// 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.
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");
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
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");
// Set the placement of the shape so that it resizes and moves with the
grid.
diamond.setPlacement(ExcelScript.Placement.twoCell);
}
Fields
ノ Expand table
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.
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
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();
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();
Fields
ノ Expand table
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
Fields
ノ Expand table
none No 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();
// 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);
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();
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.
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
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();
// 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
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
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();
// 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
autoSizeNone No autosizing.
Fields
ノ Expand table
noFill No 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
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
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
Fields
ノ Expand table
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.
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
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
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
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
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
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
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
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
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");
Fields
ノ Expand table
differenceFrom Difference from the specified Base field and Base item.
percentDifferenceFrom Difference from the specified Base field and Base item.
percentOf Percent of the specified Base field and Base item.
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.
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
Fields
ノ Expand table
dataSourceOrder Sort slicer items in the order provided by the data source.
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
Fields
ノ Expand 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.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];
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
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");
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
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");
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();
Fields
ノ Expand table
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);
Fields
ノ Expand table
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");
Fields
ノ Expand table
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.
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];
Fields
ノ Expand 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.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");
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
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");
Fields
ノ Expand table
automatic The workbook links are updated at a set interval determined by the Excel application.
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");
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
Methods
ノ Expand table
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
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
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
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
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
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
};
Properties
ノ Expand table
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
Methods
ノ Expand table
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.
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.
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
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
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);
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
TypeScript
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.
clearCriteria() Clears the filter criteria and sort state of the AutoFilter.
getCriteria() An array that holds all the filter criteria in the autofiltered range.
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 .
Method Details
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();
clearColumnCriteria(columnIndex)
Clears the column filter criteria of the AutoFilter.
TypeScript
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();
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
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 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.
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
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
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
Methods
ノ Expand table
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
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");
// 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);
getFormat() Returns a format object, encapsulating the conditional formats font, fill, borders,
and other properties.
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
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
Methods
ノ Expand table
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).
getChartType() Specifies the type of the chart. See ExcelScript.ChartType for details.
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.
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.
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.
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.
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).
setChartType(chartType) Specifies the type of the chart. See ExcelScript.ChartType for details.
setDisplayBlanks Specifies the way that blank cells are plotted on a chart.
As(displayBlanksAs)
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.
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.
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).
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
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");
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
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];
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();
// 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();
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
Parameters
categoryLabelLevel number
Returns
void
setChartType(chartType)
Specifies the type of the chart. See ExcelScript.ChartType for details.
TypeScript
Parameters
chartType ExcelScript.ChartType
Returns
void
setData(sourceData, seriesBy)
Resets the source data for the chart.
TypeScript
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
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
Parameters
left number
Returns
void
setName(name)
Specifies the name of a chart object.
TypeScript
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();
setPlotBy(plotBy)
Specifies the way columns or rows are used as data series on the chart.
TypeScript
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();
// 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
Parameters
plotVisibleOnly boolean
Returns
void
setPosition(startCell, endCell)
Positions the chart relative to cells on the worksheet.
TypeScript
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.
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();
setSeriesNameLevel(seriesNameLevel)
Specifies a chart series name level enumeration constant, referring to the level of the
source series names.
TypeScript
Parameters
seriesNameLevel number
Returns
void
setShowAllFieldButtons(showAllFieldButtons)
Specifies whether to display all field buttons on a PivotChart.
TypeScript
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
Parameters
showDataLabelsOverMaximum boolean
Returns
void
setStyle(style)
Specifies the chart style for the chart.
TypeScript
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
Parameters
top number
Returns
void
setWidth(width)
Specifies the width, in points, of the chart object.
TypeScript
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
Methods
ノ Expand table
getBorder() Represents the border format of chart area, which includes color,
linestyle, and weight.
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.
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
Parameters
colorScheme ExcelScript.ChartColorScheme
Returns
void
setRoundedCorners(roundedCorners)
Specifies if the chart area of the chart has rounded corners.
TypeScript
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
Methods
ノ Expand table
getChartAxis(type, group) Returns the specific axis identified by type and group.
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
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
Methods
ノ Expand table
getAlignment() Specifies the alignment for the specified axis tick label. See
ExcelScript.ChartTextHorizontalAlignment for detail.
getBaseTimeUnit() Specifies the base unit for the specified category axis.
getCustomDisplayUnit() Specifies the custom axis display unit value. To set this property,
please use the SetCustomDisplayUnit(double) method.
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 .
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 .
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.
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.
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.
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)
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 .
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 .
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.
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.
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
Returns
void
setBaseTimeUnit(baseTimeUnit)
Specifies the base unit for the specified category axis.
TypeScript
Parameters
baseTimeUnit ExcelScript.ChartAxisTimeUnit
Returns
void
setCategoryNames(sourceData)
Sets all the category names for the specified axis.
TypeScript
Parameters
sourceData ExcelScript.Range
The Range object corresponding to the source data.
Returns
void
setCategoryType(categoryType)
Specifies the category axis type.
TypeScript
Parameters
categoryType ExcelScript.ChartAxisCategoryType
Returns
void
setCustomDisplayUnit(value)
Sets the axis display unit to a custom value.
TypeScript
Parameters
value number
Custom value of the display unit.
Returns
void
setDisplayUnit(displayUnit)
Represents the axis display unit. See ExcelScript.ChartAxisDisplayUnit for details.
TypeScript
Parameters
displayUnit ExcelScript.ChartAxisDisplayUnit
Returns
void
setIsBetweenCategories(isBetweenCategories)
Specifies if the value axis crosses the category axis between categories.
TypeScript
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
Parameters
linkNumberFormat boolean
Returns
void
setLogBase(logBase)
Specifies the base of the logarithm when using logarithmic scales.
TypeScript
Parameters
logBase number
Returns
void
setMajorTickMark(majorTickMark)
Specifies the type of major tick mark for the specified axis. See
ExcelScript.ChartAxisTickMark for details.
TypeScript
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
Parameters
majorTimeUnitScale ExcelScript.ChartAxisTimeUnit
Returns
void
setMajorUnit(majorUnit)
Specifies the interval between two major tick marks.
TypeScript
Parameters
majorUnit number
Returns
void
setMaximum(maximum)
Specifies the maximum value on the value axis.
TypeScript
Parameters
maximum number
Returns
void
setMinimum(minimum)
Specifies the minimum value on the value axis.
TypeScript
Parameters
minimum number
Returns
void
setMinorTickMark(minorTickMark)
Specifies the type of minor tick mark for the specified axis. See
ExcelScript.ChartAxisTickMark for details.
TypeScript
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
Parameters
minorTimeUnitScale ExcelScript.ChartAxisTimeUnit
Returns
void
setMinorUnit(minorUnit)
Specifies the interval between two minor tick marks.
TypeScript
Parameters
minorUnit number
Returns
void
setMultiLevel(multiLevel)
Specifies if an axis is multilevel.
TypeScript
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
Parameters
offset number
Returns
void
setPosition(position)
Specifies the specified axis position where the other axis crosses. See
ExcelScript.ChartAxisPosition for details.
TypeScript
Parameters
position ExcelScript.ChartAxisPosition
Returns
void
setPositionAt(value)
Sets the specified axis position where the other axis crosses.
TypeScript
Parameters
value number
Custom value of the crossing point.
Returns
void
setReversePlotOrder(reversePlotOrder)
Specifies if Excel plots data points from last to first.
TypeScript
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
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
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
Parameters
tickLabelSpacing number
Returns
void
setTickMarkSpacing(tickMarkSpacing)
Specifies the number of categories or series between tick marks.
TypeScript
Parameters
tickMarkSpacing number
Returns
void
setVisible(visible)
Specifies if the axis is visible.
TypeScript
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
Methods
ノ Expand table
getFont() Specifies the font attributes (font name, font size, color, etc.) for a chart axis element.
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
Methods
ノ Expand table
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.
setFormula(formula) A string value that represents the formula of chart axis title using A1-
style notation.
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.
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
Parameters
formula string
A string that represents the formula to set.
Returns
void
setText(text)
Specifies the axis title.
TypeScript
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
Returns
void
setVisible(visible)
Specifies if the axis title is visible.
TypeScript
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
Methods
ノ Expand table
get Specifies the chart axis title's border format, which includes color, linestyle, and
Border() weight.
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
getType() Specifies the bin's type for a histogram chart or pareto chart.
setType(type) Specifies the bin's type for a histogram chart or pareto chart.
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
Parameters
allowOverflow boolean
Returns
void
setAllowUnderflow(allowUnderflow)
Specifies if bin underflow is enabled in a histogram chart or pareto chart.
TypeScript
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
Parameters
overflowValue number
Returns
void
setType(type)
Specifies the bin's type for a histogram chart or pareto chart.
TypeScript
Parameters
type ExcelScript.ChartBinType
Returns
void
setUnderflowValue(underflowValue)
Specifies the bin underflow value of a histogram chart or pareto chart.
TypeScript
Parameters
underflowValue number
Returns
void
setWidth(width)
Specifies the bin width value of a histogram chart or pareto chart.
TypeScript
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
Methods
ノ Expand table
getColor() HTML color code representing the color of borders in the chart.
setColor(color) HTML color code representing the color of borders in the chart.
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
Returns
void
setLineStyle(lineStyle)
Represents the line style of the border. See ExcelScript.ChartLineStyle for details.
TypeScript
Parameters
lineStyle ExcelScript.ChartLineStyle
Returns
void
setWeight(weight)
Represents weight of the border, in points.
TypeScript
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
Methods
ノ Expand table
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
Parameters
showMeanLine boolean
Returns
void
setShowMeanMarker(showMeanMarker)
Specifies if the mean marker is shown in a box and whisker chart.
TypeScript
Parameters
showMeanMarker boolean
Returns
void
setShowOutlierPoints(showOutlierPoints)
Specifies if outlier points are shown in a box and whisker chart.
TypeScript
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
Methods
ノ Expand table
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.
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.
getWidth() Returns the width, in points, of the chart data label. Value is null if
the chart data label is not visible.
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.
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.
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
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
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
Parameters
autoText boolean
Returns
void
setFormula(formula)
String value that represents the formula of chart data label using A1-style notation.
TypeScript
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
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
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
Parameters
linkNumberFormat boolean
Returns
void
setNumberFormat(numberFormat)
String value that represents the format code for data label.
TypeScript
Parameters
numberFormat string
Returns
void
setPosition(position)
Value that represents the position of the data label. See
ExcelScript.ChartDataLabelPosition for details.
TypeScript
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
Parameters
showBubbleSize boolean
Returns
void
setShowCategoryName(showCategoryName)
Specifies if the data label category name is visible.
TypeScript
Parameters
showCategoryName boolean
Returns
void
setShowLegendKey(showLegendKey)
Specifies if the data label legend key is visible.
TypeScript
Parameters
showLegendKey boolean
Returns
void
setShowPercentage(showPercentage)
Specifies if the data label percentage is visible.
TypeScript
Parameters
showPercentage boolean
Returns
void
setShowSeriesName(showSeriesName)
Specifies if the data label series name is visible.
TypeScript
Parameters
showSeriesName boolean
Returns
void
setShowValue(showValue)
Specifies if the data label value is visible.
TypeScript
Parameters
showValue boolean
Returns
void
setText(text)
String representing the text of the data label on a chart.
TypeScript
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
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
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
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
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
Methods
ノ Expand table
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.
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.
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.
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)
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.
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.
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
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
TypeScript
getVerticalAlignment(): ChartTextVerticalAlignment;
Returns
ExcelScript.ChartTextVerticalAlignment
setAutoText(autoText)
Specifies if data labels automatically generate appropriate text based on context.
TypeScript
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
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
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
Parameters
position ExcelScript.ChartDataLabelPosition
Returns
void
setSeparator(separator)
String representing the separator used for the data labels on a chart.
TypeScript
Parameters
separator string
Returns
void
setShowBubbleSize(showBubbleSize)
Specifies if the data label bubble size is visible.
TypeScript
Parameters
showBubbleSize boolean
Returns
void
setShowCategoryName(showCategoryName)
Specifies if the data label category name is visible.
TypeScript
Parameters
showCategoryName boolean
Returns
void
setShowLegendKey(showLegendKey)
Specifies if the data label legend key is visible.
TypeScript
Returns
void
setShowPercentage(showPercentage)
Specifies if the data label percentage is visible.
TypeScript
Parameters
showPercentage boolean
Returns
void
setShowSeriesName(showSeriesName)
Specifies if the data label series name is visible.
TypeScript
Parameters
showSeriesName boolean
Returns
void
setShowValue(showValue)
Specifies if the data label value is visible.
TypeScript
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
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
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
Methods
ノ Expand table
getShowLegendKey() Specifies whether to show the legend key of the data table.
setShowLegendKey(showLegend Specifies whether to show the legend key of the data table.
Key)
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
Parameters
showHorizontalBorder boolean
Returns
void
setShowLegendKey(showLegendKey)
Specifies whether to show the legend key of the data table.
TypeScript
Parameters
showLegendKey boolean
Returns
void
setShowOutlineBorder(showOutlineBorder)
Specifies whether to display the outline border of the data table.
TypeScript
Parameters
showOutlineBorder boolean
Returns
void
setShowVerticalBorder(showVerticalBorder)
Specifies whether to display the vertical border of the data table.
TypeScript
Parameters
showVerticalBorder boolean
Returns
void
setVisible(visible)
Specifies whether to show the data table of the chart.
TypeScript
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
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
Methods
ノ Expand table
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
Parameters
endStyleCap boolean
Returns
void
setInclude(include)
Specifies which parts of the error bars to include.
TypeScript
Parameters
include ExcelScript.ChartErrorBarsInclude
Returns
void
setType(type)
The type of range marked by the error bars.
TypeScript
Parameters
type ExcelScript.ChartErrorBarsType
Returns
void
setVisible(visible)
Specifies whether the error bars are displayed.
TypeScript
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
Methods
ノ Expand table
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
Methods
ノ Expand table
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
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
getColor() HTML color code representation of the text color (e.g., #FF0000
represents Red).
setColor(color) HTML color code representation of the text color (e.g., #FF0000
represents Red).
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
Parameters
bold boolean
Returns
void
setColor(color)
HTML color code representation of the text color (e.g., #FF0000 represents Red).
TypeScript
Parameters
color string
Returns
void
setItalic(italic)
Represents the italic status of the font.
TypeScript
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
Parameters
size number
Returns
void
setUnderline(underline)
Type of underline applied to the font. See ExcelScript.ChartUnderlineStyle for
details.
TypeScript
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
Methods
ノ Expand table
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
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
Methods
ノ Expand table
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
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.
getOverlay() Specifies if the chart legend should overlap with the main body of the
chart.
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.
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
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
Parameters
left number
Returns
void
setOverlay(overlay)
Specifies if the chart legend should overlap with the main body of the chart.
TypeScript
Parameters
overlay boolean
Returns
void
setPosition(position)
Specifies the position of the legend on the chart. See
ExcelScript.ChartLegendPosition for details.
TypeScript
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
Parameters
top number
Returns
void
setVisible(visible)
Specifies if the chart legend is visible.
TypeScript
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
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
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.
getWidth() Represents the width of the legend entry on the chart Legend.
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
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
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
Methods
ノ Expand table
getColor() HTML color code representing the color of lines in the chart.
setColor(color) HTML color code representing the color of lines in the chart.
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
Returns
void
setLineStyle(lineStyle)
Represents the line style. See ExcelScript.ChartLineStyle for details.
TypeScript
Parameters
lineStyle ExcelScript.ChartLineStyle
Returns
void
setWeight(weight)
Represents weight of the line, in points.
TypeScript
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
Methods
ノ Expand table
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
Parameters
labelStrategy ExcelScript.ChartMapLabelStrategy
Returns
void
setLevel(level)
Specifies the series mapping level of a region map chart.
TypeScript
Parameters
level ExcelScript.ChartMapAreaLevel
Returns
void
setProjectionType(projectionType)
Specifies the series projection type of a region map chart.
TypeScript
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
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.
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.
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
Parameters
showAxisFieldButtons boolean
Returns
void
setShowLegendFieldButtons(showLegendFieldButtons)
Specifies whether to display the legend field buttons on a PivotChart.
TypeScript
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
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
Methods
ノ Expand table
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
Parameters
height number
Returns
void
setInsideHeight(insideHeight)
Specifies the inside height value of a plot area.
TypeScript
Parameters
insideHeight number
Returns
void
setInsideLeft(insideLeft)
Specifies the inside left value of a plot area.
TypeScript
Parameters
insideLeft number
Returns
void
setInsideTop(insideTop)
Specifies the inside top value of a plot area.
TypeScript
Parameters
insideTop number
Returns
void
setInsideWidth(insideWidth)
Specifies the inside width value of a plot area.
TypeScript
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
Parameters
position ExcelScript.ChartPlotAreaPosition
Returns
void
setTop(top)
Specifies the top value of a plot area.
TypeScript
Parameters
top number
Returns
void
setWidth(width)
Specifies the width value of a plot area.
TypeScript
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
Methods
ノ Expand table
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
Methods
ノ Expand table
getHasDataLabel() Represents whether a data point has a data label. Not applicable for
surface charts.
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.
setHasDataLabel(has Represents whether a data point has a data label. Not applicable for
DataLabel) surface charts.
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
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
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
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
Returns
void
setMarkerStyle(markerStyle)
Represents marker style of a chart data point. See ExcelScript.ChartMarkerStyle for
details.
TypeScript
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
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
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");
Methods
ノ Expand table
addChartTrendline(type) Adds a new trendline to trendline collection.
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.
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.
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.
getFiltered() Specifies if the series is filtered. Not applicable for surface charts.
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()
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.
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.
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.
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.
getShowLeaderLines() Specifies whether leader lines are displayed for each data label in
the series.
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.
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.
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.
setFiltered(filtered) Specifies if the series is filtered. Not applicable for surface charts.
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)
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)
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)
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.
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.
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.
setShowLeaderLines(show Specifies whether leader lines are displayed for each data label in
LeaderLines) the series.
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.
Method Details
addChartTrendline(type)
Adds a new trendline to trendline collection.
TypeScript
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
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
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
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();
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");
// 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
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
Parameters
bubbleScale number
Returns
void
setBubbleSizes(sourceData)
Sets the bubble sizes for a chart series. Only works for bubble charts.
TypeScript
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
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
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
Returns
void
setFiltered(filtered)
Specifies if the series is filtered. Not applicable for surface charts.
TypeScript
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
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
Parameters
gapWidth number
Returns
void
setGradientMaximumColor(gradientMaximumColor)
Specifies the color for maximum value of a region map chart series.
TypeScript
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
Parameters
gradientMaximumValue number
Returns
void
setGradientMidpointColor(gradientMidpointColor)
Specifies the color for the midpoint value of a region map chart series.
TypeScript
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
Parameters
gradientMidpointValue number
Returns
void
setGradientMinimumColor(gradientMinimumColor)
Specifies the color for the minimum value of a region map chart series.
TypeScript
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
Parameters
gradientMinimumValue number
Returns
void
setGradientStyle(gradientStyle)
Specifies the series gradient style of a region map chart.
TypeScript
Parameters
gradientStyle ExcelScript.ChartGradientStyle
Returns
void
setHasDataLabels(hasDataLabels)
Specifies if the series has data labels.
TypeScript
Parameters
hasDataLabels boolean
Returns
void
setInvertColor(invertColor)
Specifies the fill color for negative data points in a series.
TypeScript
Parameters
invertColor string
Returns
void
setInvertIfNegative(invertIfNegative)
True if Excel inverts the pattern in the item when it corresponds to a negative
number.
TypeScript
Parameters
invertIfNegative boolean
Returns
void
setMarkerBackgroundColor(markerBackgroundColor)
Specifies the marker background color of a chart series.
TypeScript
Parameters
markerBackgroundColor string
Returns
void
setMarkerForegroundColor(markerForegroundColor)
Specifies the marker foreground color of a chart series.
TypeScript
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
Parameters
markerSize number
Returns
void
setMarkerStyle(markerStyle)
Specifies the marker style of a chart series. See ExcelScript.ChartMarkerStyle for
details.
TypeScript
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
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
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();
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
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
Parameters
secondPlotSize number
Returns
void
setShowConnectorLines(showConnectorLines)
Specifies whether connector lines are shown in waterfall charts.
TypeScript
Parameters
showConnectorLines boolean
Returns
void
setShowLeaderLines(showLeaderLines)
Specifies whether leader lines are displayed for each data label in the series.
TypeScript
Parameters
showLeaderLines boolean
Returns
void
setShowShadow(showShadow)
Specifies if the series has a shadow.
TypeScript
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
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
Parameters
splitValue number
Returns
void
setValues(sourceData)
Sets the values for a chart series. For scatter charts, it refers to y-axis values.
TypeScript
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
Parameters
varyByCategories boolean
Returns
void
setXAxisValues(sourceData)
Sets the values of the x-axis for a chart series.
TypeScript
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
Methods
ノ Expand table
getFill() Represents the fill format of a chart series, which includes background formatting
information.
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
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.
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.
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.
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.
setFormula(formula) Sets a string value that represents the formula of chart title using
A1-style notation.
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.
setShowShadow(show Represents a boolean value that determines if the chart title has a
Shadow) shadow.
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.
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
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
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
Parameters
left number
Returns
void
setOverlay(overlay)
Specifies if the chart title will overlay the chart.
TypeScript
Parameters
overlay boolean
Returns
void
setPosition(position)
Represents the position of chart title. See ExcelScript.ChartTitlePosition for
details.
TypeScript
Parameters
position ExcelScript.ChartTitlePosition
Returns
void
setShowShadow(showShadow)
Represents a boolean value that determines if the chart title has a shadow.
TypeScript
Parameters
showShadow boolean
Returns
void
setText(text)
Specifies the chart's title text.
TypeScript
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
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
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
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
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
Methods
ノ Expand table
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.
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.
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
Parameters
backwardPeriod number
Returns
void
setForwardPeriod(forwardPeriod)
Represents the number of periods that the trendline extends forward.
TypeScript
Parameters
forwardPeriod number
Returns
void
setIntercept(intercept)
Specifies the intercept value of the trendline.
TypeScript
Returns
void
setMovingAveragePeriod(movingAveragePeriod)
Represents the period of a chart trendline. Only applicable to trendlines with the
type MovingAverage .
TypeScript
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
Parameters
name string
Returns
void
setPolynomialOrder(polynomialOrder)
Represents the order of a chart trendline. Only applicable to trendlines with the type
Polynomial .
TypeScript
Parameters
polynomialOrder number
Returns
void
setShowEquation(showEquation)
True if the equation for the trendline is displayed on the chart.
TypeScript
Parameters
showEquation boolean
Returns
void
setShowRSquared(showRSquared)
True if the r-squared value for the trendline is displayed on the chart.
TypeScript
Returns
void
setType(type)
Represents the type of a chart trendline.
TypeScript
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
Methods
ノ Expand table
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
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.
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.
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)
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
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
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
Parameters
autoText boolean
Returns
void
setFormula(formula)
String value that represents the formula of the chart trendline label using A1-style
notation.
TypeScript
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
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
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
Parameters
linkNumberFormat boolean
Returns
void
setNumberFormat(numberFormat)
String value that represents the format code for the trendline label.
TypeScript
Parameters
numberFormat string
Returns
void
setText(text)
String representing the text of the trendline label on a chart.
TypeScript
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
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
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
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
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
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
Methods
ノ Expand table
getComment Returns a comment reply identified by its ID. If the comment reply
Reply(commentReplyId) object does not exist, then this method returns undefined .
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.
getMentions() Gets the entities (e.g., people) that are mentioned in comments.
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
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
Returns
void
setResolved(resolved)
The comment thread status. A value of true means that the comment thread is
resolved.
TypeScript
Parameters
resolved boolean
Returns
void
updateMentions(contentWithMentions)
Updates the comment content with a specially formatted string and a list of
mentions.
TypeScript
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
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);
Properties
ノ Expand table
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
Methods
ノ Expand table
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.
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
Parameters
content string
Returns
void
updateMentions(contentWithMentions)
Updates the comment content with a specially formatted string and a list of
mentions.
TypeScript
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();
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
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");
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);
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.
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
Properties
ノ Expand table
midpoint The midpoint of the color scale criterion, if the color scale is a 3-color scale.
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).
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
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
Parameters
fillColor string
Returns
void
setMatchPositiveBorderColor(matchPositiveBorderColor)
Specifies if the negative data bar has the same border color as the positive data bar.
TypeScript
Parameters
matchPositiveBorderColor boolean
Returns
void
setMatchPositiveFillColor(matchPositiveFillColor)
Specifies if the negative data bar has the same fill color as the positive data bar.
TypeScript
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").
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").
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
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
Parameters
fillColor string
Returns
void
setGradientFill(gradientFill)
Specifies if the data bar has a gradient.
TypeScript
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
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();
Properties
ノ Expand table
formula The formula, if required, on which to evaluate the data bar rule.
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
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.
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.
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
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");
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);
getColorScale()
Returns the color scale conditional format properties if the current conditional
format is a ColorScale type.
TypeScript
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();
// 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
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();
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
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();
getIconSet()
Returns the icon set conditional format properties if the current conditional format is
an IconSet type.
TypeScript
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");
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
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");
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
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");
firstColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.contai
nsText).getTextComparison();
// 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
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
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
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
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();
Methods
ノ Expand table
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
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
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");
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.
operator greaterThan or greaterThanOrEqual for each of the rule types for the icon
conditional format.
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
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");
// 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
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
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
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
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();
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);
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
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();
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);
getColor() HTML color code representation of the text color (e.g., #FF0000
represents Red).
setColor(color) HTML color code representation of the text color (e.g., #FF0000
represents Red).
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
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
Parameters
italic boolean
Returns
void
setStrikethrough(strikethrough)
Specifies the strikethrough status of the font.
TypeScript
Parameters
strikethrough boolean
Returns
void
setUnderline(underline)
The type of underline applied to the font. See
ExcelScript.ConditionalRangeFontUnderlineStyle for details.
TypeScript
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();
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);
Methods
ノ Expand table
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
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
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");
firstColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.containsT
ext).getTextComparison();
// 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
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
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();
// 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.
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);
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
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();
Methods
ノ Expand table
get Returns a format object, encapsulating the conditional formats font, fill, borders, and
Format() other properties.
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
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");
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
Methods
ノ Expand table
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
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
Methods
ノ Expand table
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
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
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();
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
Parameters
axisColor string
Returns
void
setAxisFormat(axisFormat)
Representation of how the axis is determined for an Excel data bar.
TypeScript
Parameters
axisFormat ExcelScript.ConditionalDataBarAxisFormat
Returns
void
setBarDirection(barDirection)
Specifies the direction that the data bar graphic should be based on.
TypeScript
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
Parameters
lowerBoundRule ExcelScript.ConditionalDataBarRule
Returns
void
setShowDataBarOnly(showDataBarOnly)
If true , hides the values from the cells where the data bar is applied.
TypeScript
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
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
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");
// 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
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
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
Parameters
position number
Returns
void
setShowAs(showAs)
Specifies if the data should be shown as a specific summary calculation.
TypeScript
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");
setSummarizeBy(summarizeBy)
Specifies if all items of the DataPivotHierarchy are shown.
TypeScript
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];
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
Methods
ノ Expand table
getIgnoreBlanks() Specifies if data validation will be performed on blank cells. Default is true .
getRule() Data validation rule that contains different type of data validation criteria.
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.
setIgnore Specifies if data validation will be performed on blank cells. Default is true .
Blanks(ignore
Blanks)
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();
/*
* 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
Parameters
errorAlert ExcelScript.DataValidationErrorAlert
Returns
void
setIgnoreBlanks(ignoreBlanks)
Specifies if data validation will be performed on blank cells. Default is true .
TypeScript
Parameters
ignoreBlanks boolean
Returns
void
setPrompt(prompt)
Prompt when users select a cell.
TypeScript
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();
setRule(rule)
Data validation rule that contains different type of data validation criteria.
TypeScript
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 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
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 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
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.
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
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();
Properties
ノ Expand table
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
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");
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();
// Apply the data validation to the first cell in the selected range.
const targetCell = selectedRange.getCell(0, 0);
const dataValidation = targetCell.getDataValidation();
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 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
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});
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.
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
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
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);
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);
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);
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
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();
Methods
ノ Expand table
Method Details
addCustomProperty(key, value)
Creates a new or sets an existing custom property.
TypeScript
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();
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
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();
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
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
Parameters
comments string
Returns
void
setCompany(company)
The company of the workbook.
TypeScript
Parameters
company string
Returns
void
setKeywords(keywords)
The keywords of the workbook.
TypeScript
Parameters
keywords string
Returns
void
setManager(manager)
The manager of the workbook.
TypeScript
Parameters
manager string
Returns
void
setRevisionNumber(revisionNumber)
Gets the revision number of the workbook.
TypeScript
Parameters
revisionNumber number
Returns
void
setSubject(subject)
The subject of the workbook.
TypeScript
Parameters
subject string
Returns
void
setTitle(title)
The title of the workbook.
TypeScript
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
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];
// Apply a filter to only show the rows with the top 10% of values in
this column.
pageViewFilter.applyTopPercentFilter(10);
}
Methods
ノ Expand table
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.
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.
Method Details
apply(criteria)
Apply the given filter criteria on the given column.
TypeScript
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
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
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
Parameters
color string
The background color of the cells to show.
Returns
void
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
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");
dateColumn.getFilter().applyDynamicFilter(ExcelScript.DynamicFilterCriter
ia.lastMonth);
}
applyFontColorFilter(color)
Apply a "Font Color" filter to the column for the given color.
TypeScript
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
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
Returns
void
applyTopPercentFilter(percent)
Apply a "Top Percent" filter to the column for the given percentage of elements.
TypeScript
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
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];
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];
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
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.
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.
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
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
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];
Properties
ノ Expand table
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
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");
Methods
ノ Expand table
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];
getPivotField(name)
Gets a PivotField by name. If the PivotField does not exist, then this method returns
undefined .
TypeScript
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
Parameters
enableMultipleFilterItems boolean
Returns
void
setName(name)
Name of the FilterPivotHierarchy.
TypeScript
Parameters
name string
Returns
void
setPosition(position)
Position of the FilterPivotHierarchy.
TypeScript
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
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
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
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
Methods
ノ Expand table
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
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
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
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
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
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
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.
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.
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)
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
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
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
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
Properties
ノ Expand table
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
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");
// 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.
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)
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
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
Parameters
reverseIconOrder boolean
Returns
void
setShowIconOnly(showIconOnly)
If true , hides the values and only shows icons.
TypeScript
Parameters
showIconOnly boolean
Returns
void
setStyle(style)
If set, displays the icon set option for the conditional format.
TypeScript
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");
Methods
ノ Expand table
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
Methods
ノ Expand table
getMaxIteration() Specifies the maximum number of iterations that Excel can use to
resolve a circular reference.
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
Parameters
enabled boolean
Returns
void
setMaxChange(maxChange)
Specifies the maximum amount of change between each iteration as Excel resolves
circular references.
TypeScript
Parameters
maxChange number
Returns
void
setMaxIteration(maxIteration)
Specifies the maximum number of iterations that Excel can use to resolve a circular
reference.
TypeScript
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
getBeginConnectedShape() Represents the shape to which the beginning of the specified line
is attached.
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.
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
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
Parameters
beginArrowheadLength ExcelScript.ArrowheadLength
Returns
void
setBeginArrowheadStyle(beginArrowheadStyle)
Represents the style of the arrowhead at the beginning of the specified line.
TypeScript
Parameters
beginArrowheadStyle ExcelScript.ArrowheadStyle
Returns
void
setBeginArrowheadWidth(beginArrowheadWidth)
Represents the width of the arrowhead at the beginning of the specified line.
TypeScript
Parameters
beginArrowheadWidth ExcelScript.ArrowheadWidth
Returns
void
setConnectorType(connectorType)
Represents the connector type for the line.
TypeScript
Parameters
connectorType ExcelScript.ConnectorType
Returns
void
setEndArrowheadLength(endArrowheadLength)
Represents the length of the arrowhead at the end of the specified line.
TypeScript
Parameters
endArrowheadLength ExcelScript.ArrowheadLength
Returns
void
setEndArrowheadStyle(endArrowheadStyle)
Represents the style of the arrowhead at the end of the specified line.
TypeScript
Returns
void
setEndArrowheadWidth(endArrowheadWidth)
Represents the width of the arrowhead at the end of the specified line.
TypeScript
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.`);
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
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();
// Apply the data validation to the first cell in the selected range.
const targetCell = selectedRange.getCell(0, 0);
const dataValidation = targetCell.getDataValidation();
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
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."
);
Methods
ノ Expand table
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
("=").
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 .
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.
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 .
setFormula(formula) The formula of the named item. Formulas always start with an equal sign
("=").
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
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
Returns
ExcelScript.Worksheet | undefined
setComment(comment)
Specifies the comment associated with this name.
TypeScript
Parameters
comment string
Returns
void
setFormula(formula)
The formula of the named item. Formulas always start with an equal sign ("=").
TypeScript
Parameters
formula string
Returns
void
setVisible(visible)
Specifies if the object is visible.
TypeScript
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
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
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.
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
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
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
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();
Methods
ノ Expand table
getBottomMargin() The worksheet's bottom page margin to use for printing in points.
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.
getFooterMargin() The worksheet's footer margin, in points, for use when printing.
getHeaderMargin() The worksheet's header margin, in points, for use when printing.
getLeftMargin() The worksheet's left margin, in points, for use when printing.
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.
setBottomMargin(bottom The worksheet's bottom page margin to use for printing in points.
Margin)
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.
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.
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.
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
Parameters
blackAndWhite boolean
Returns
void
setBottomMargin(bottomMargin)
The worksheet's bottom page margin to use for printing in points.
TypeScript
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
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
Parameters
centerVertically boolean
Returns
void
setDraftMode(draftMode)
The worksheet's draft mode option. If true , the sheet will be printed without
graphics.
TypeScript
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();
setFirstPageNumber(firstPageNumber)
The worksheet's first page number to print. A null value represents "auto" page
numbering.
TypeScript
Parameters
firstPageNumber number | ""
Returns
void
setFooterMargin(footerMargin)
The worksheet's footer margin, in points, for use when printing.
TypeScript
Parameters
footerMargin number
Returns
void
setHeaderMargin(headerMargin)
The worksheet's header margin, in points, for use when printing.
TypeScript
Parameters
headerMargin number
Returns
void
setLeftMargin(leftMargin)
The worksheet's left margin, in points, for use when printing.
TypeScript
Returns
void
setOrientation(orientation)
The worksheet's orientation of the page.
TypeScript
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();
setPaperSize(paperSize)
The worksheet's paper size of the page.
TypeScript
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
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
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();
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
Parameters
printGridlines boolean
Returns
void
setPrintHeadings(printHeadings)
Specifies if the worksheet's headings will be printed.
TypeScript
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
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();
setPrintTitleColumns(printTitleColumns)
Sets the columns that contain the cells to be repeated at the left of each page of the
worksheet for printing.
TypeScript
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
Parameters
rightMargin number
Returns
void
setTopMargin(topMargin)
The worksheet's top margin, in points, for use when printing.
TypeScript
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
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();
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
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
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();
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];
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];
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
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).
getPivotItem(name) Gets a PivotItem by name. If the PivotItem does not exist, then
this method returns undefined .
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
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()
};
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
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");
// 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
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
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
Parameters
name string
Returns
void
setShowAllItems(showAllItems)
Determines whether to show all items of the PivotField.
TypeScript
Parameters
showAllItems boolean
Returns
void
setSubtotals(subtotals)
Subtotals of the PivotField.
TypeScript
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
Parameters
sortBy ExcelScript.SortBy
Specifies if the sorting is done in ascending or descending order.
Returns
void
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");
// 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
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];
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");
// 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
};
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];
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];
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
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];
Methods
ノ Expand table
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
Parameters
name string
Name of the PivotField to be retrieved.
Returns
ExcelScript.PivotField | undefined
setName(name)
Name of the PivotHierarchy.
TypeScript
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
Methods
ノ Expand table
getIsExpanded() Determines whether the item is expanded to show child items or if it's
collapsed and child items are hidden.
setIsExpanded(is Determines whether the item is expanded to show child items or if it's
Expanded) collapsed and child items are hidden.
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
Parameters
name string
Returns
void
setVisible(visible)
Specifies if the PivotItem is visible.
TypeScript
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");
// 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
};
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
Methods
ノ Expand table
getBodyAndTotalRange() Returns the range where the PivotTable's data values reside.
getColumnLabelRange() Returns the range where the PivotTable's column labels reside.
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.
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)
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 range with the "grand totals" for the PivotTable columns.
let grandTotalRange = pivotDataRange.getLastRow();
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
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
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
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
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
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");
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
Parameters
preserveFormatting boolean
Returns
void
setShowColumnGrandTotals(showColumnGrandTotals)
Specifies if the PivotTable report shows grand totals for columns.
TypeScript
Parameters
showColumnGrandTotals boolean
Returns
void
setShowRowGrandTotals(showRowGrandTotals)
Specifies if the PivotTable report shows grand totals for rows.
TypeScript
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
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");
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];
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
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
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];
Methods
ノ Expand table
getLayout() The PivotLayout describing the layout and visual structure of the
PivotTable.
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];
pivotTable.addColumnHierarchy(pivotTable.getHierarchy("Classification"));
addDataHierarchy(pivotHierarchy)
Adds the PivotHierarchy to the current axis.
TypeScript
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];
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];
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];
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
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
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
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");
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
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");
// 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
Parameters
DataPivotHierarchy ExcelScript.DataPivotHierarchy
Returns
void
removeFilterHierarchy(filterPivotHierarchy)
Removes the PivotHierarchy from the current axis.
TypeScript
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
Parameters
enableDataValueEditing boolean
Returns
void
setName(name)
Name of the PivotTable.
TypeScript
Parameters
name string
Returns
void
setUseCustomSortLists(useCustomSortLists)
Specifies if the PivotTable uses custom lists when sorting.
TypeScript
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
Methods
ノ Expand table
duplicate() Creates a duplicate of this PivotTable style with copies of all the style elements.
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
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];
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
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
Methods
ノ Expand table
getBorders() A collection of four border objects that represent the style of the
four borders.
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.
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.
getNumberFormat() The format code of the number format for the style.
getNumberFormatLocal() The localized format code of the number format for the style.
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)
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)
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
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
Returns
void
setFormulaHidden(formulaHidden)
Specifies if the formula will be hidden when the worksheet is protected.
TypeScript
Parameters
formulaHidden boolean
Returns
void
setHorizontalAlignment(horizontalAlignment)
Represents the horizontal alignment for the style. See
ExcelScript.HorizontalAlignment for details.
TypeScript
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
Parameters
includeAlignment boolean
Returns
void
setIncludeBorder(includeBorder)
Specifies if the style includes the color, color index, line style, and weight border
properties.
TypeScript
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
Returns
void
setIncludeNumber(includeNumber)
Specifies if the style includes the number format property.
TypeScript
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
Parameters
includePatterns boolean
Returns
void
setIncludeProtection(includeProtection)
Specifies if the style includes the formula hidden and locked protection properties.
TypeScript
Parameters
includeProtection boolean
Returns
void
setIndentLevel(indentLevel)
An integer from 0 to 250 that indicates the indent level for the style.
TypeScript
Parameters
indentLevel number
Returns
void
setLocked(locked)
Specifies if the object is locked when the worksheet is protected.
TypeScript
Parameters
locked boolean
Returns
void
setNumberFormat(numberFormat)
The format code of the number format for the style.
TypeScript
Parameters
numberFormat string
Returns
void
setNumberFormatLocal(numberFormatLocal)
The localized format code of the number format for the style.
TypeScript
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
Parameters
rangeBorderTintAndShade number
Returns
void
setReadingOrder(readingOrder)
The reading order for the style.
TypeScript
Parameters
readingOrder ExcelScript.ReadingOrder
Returns
void
setShrinkToFit(shrinkToFit)
Specifies if text automatically shrinks to fit in the available column width.
TypeScript
Parameters
shrinkToFit boolean
Returns
void
setTextOrientation(textOrientation)
The text orientation for the style.
TypeScript
Parameters
textOrientation number
Returns
void
setVerticalAlignment(verticalAlignment)
Specifies the vertical alignment for the style. See ExcelScript.VerticalAlignment for
details.
TypeScript
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");
// 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.
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
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();
Methods
ノ Expand table
getError() Gets the query error message from when the query was last refreshed.
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();
Methods
ノ Expand table
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
getWidth() Returns the distance in points, for 100% zoom, from the left
edge of the range to the right edge of the range.
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.
replaceAll(text, replacement, Finds and replaces the given string based on the criteria
criteria) specified within the current range.
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.
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.
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.
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.
Method Details
addConditionalFormat(type)
Adds a new conditional format to the collection at the first/top priority.
TypeScript
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();
// 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
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();
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
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");
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);
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
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");
TypeScript
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();
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
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();
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
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
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();
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
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
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
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();
// 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.
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);
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];
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);
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);
cell.getFormat().getFont().setUnderline(ExcelScript.RangeUnderlineStyle.n
one);
cell.getFormat().getFont().setColor('Black');
clearedCount++;
}
}
}
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
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();
// 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
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
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
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.
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();
// 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
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
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();
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
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
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();
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
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
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
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();
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
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();
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());
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
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
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);
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
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();
// Add a blank first row and push existing data down a row.
let firstRow = currentSheet.getRange("1:1");
firstRow.insert(ExcelScript.InsertShiftDirection.down);
merge(across)
Merge the range cells into one region in the worksheet.
TypeScript
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();
TypeScript
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);
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];
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
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
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);
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
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
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
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();
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
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
Parameters
formulasR1C1 string[][]
Returns
void
setHyperlink(hyperlink)
Represents the hyperlink for the current range.
TypeScript
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();
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
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();
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
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
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
Parameters
numberFormatsLocal string[][]
Returns
void
setPredefinedCellStyle(predefinedCellStyle)
Represents the style of the current range.
TypeScript
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
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
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();
/*
* 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
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
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
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);
Methods
ノ Expand table
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.
getDataValidation() Returns a data validation object for all ranges in the 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").
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 .
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
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
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);
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
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
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();
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
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
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
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
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();
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
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.
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.
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
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
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");
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
Parameters
tintAndShade number
Returns
void
setWeight(weight)
Specifies the weight of the border around a range. See ExcelScript.BorderWeight for
details.
TypeScript
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 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
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();
Methods
ノ Expand table
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")
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 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();
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
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");
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
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
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
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
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);
Methods
ノ Expand table
getColor() HTML color code representation of the text color (e.g., #FF0000
represents Red).
getName() Font name (e.g., "Calibri"). The name's length should not be
greater than 31 characters.
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.
setColor(color) HTML color code representation of the text color (e.g., #FF0000
represents Red).
setName(name) Font name (e.g., "Calibri"). The name's length should not be
greater than 31 characters.
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.
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
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);
setColor(color)
HTML color code representation of the text color (e.g., #FF0000 represents Red).
TypeScript
Parameters
color string
Returns
void
setItalic(italic)
Specifies the italic status of the font.
TypeScript
Parameters
italic boolean
Returns
void
setName(name)
Font name (e.g., "Calibri"). The name's length should not be greater than 31
characters.
TypeScript
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);
setSize(size)
Font size.
TypeScript
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
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
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
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
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.
getColumnWidth() Specifies the width of all columns within the range. If the column
widths are not uniform, null will be returned.
getHorizontalAlignment() Represents the horizontal alignment for the specified object. See
ExcelScript.HorizontalAlignment for details.
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.
getRowHeight() The height of all rows in the range. If the row heights are not uniform,
null will be returned.
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
setHorizontal Represents the horizontal alignment for the specified object. See
Alignment(horizontal ExcelScript.HorizontalAlignment for details.
Alignment)
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.
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
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];
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();
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();
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();
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];
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);
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
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");
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();
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
Parameters
autoIndent boolean
Returns
void
setColumnWidth(columnWidth)
Specifies the width of all columns within the range.
TypeScript
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();
setHorizontalAlignment(horizontalAlignment)
Represents the horizontal alignment for the specified object. See
ExcelScript.HorizontalAlignment for details.
TypeScript
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];
headerRange.getFormat().setHorizontalAlignment(ExcelScript.HorizontalAlig
nment.center);
}
setIndentLevel(indentLevel)
An integer from 0 to 250 that indicates the indent level.
TypeScript
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
Parameters
rangeBorderTintAndShade number
Returns
void
setReadingOrder(readingOrder)
The reading order for the range.
TypeScript
Parameters
readingOrder ExcelScript.ReadingOrder
Returns
void
setRowHeight(rowHeight)
Specifies the height of all rows in the range.
TypeScript
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();
setShrinkToFit(shrinkToFit)
Specifies if text automatically shrinks to fit in the available column width.
TypeScript
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
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
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
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");
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
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");
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
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);
// Put the link in the cell and format the width to fit.
cell.setHyperlink(sampleHyperlink);
cell.getFormat().autofitColumns();
}
Properties
ノ Expand table
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();
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
Methods
ノ Expand table
Method Details
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();
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
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());
Methods
ノ Expand table
getNumberFormat() Represents Excel's number format code for the given cell.
getRange() Gets the parent range associated with the current 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.
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.
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());
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
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
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
Returns
void
setFormulasR1C1(formulasR1C1)
Represents the formula in R1C1-style notation. If a cell has no formula, its value is
returned instead.
TypeScript
Parameters
formulasR1C1 string[][]
Returns
void
setNumberFormat(numberFormat)
Represents Excel's number format code for the given cell.
TypeScript
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
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
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);
Methods
ノ Expand table
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
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).
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");
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();
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
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");
// 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
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
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
Parameters
name string
Returns
void
setPosition(position)
Position of the RowColumnPivotHierarchy.
TypeScript
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
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();
// 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).
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
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);
Methods
ノ Expand table
copyTo(destinationSheet) Copies and pastes a Shape object. The pasted shape is copied to the
same pixel location as 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".
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".
getPlacement() Represents how the object is attached to the cells below it.
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.
getZOrderPosition() Returns the position of the specified shape in the z-order, with 0
representing the bottom of the order stack.
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.
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.
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.
setPlacement(placement) Represents how the object is attached to the cells below it.
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.
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
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();
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
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
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();
// 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);
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");
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
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();
// 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
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
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
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
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
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
Parameters
altTextDescription string
Returns
void
setAltTextTitle(altTextTitle)
Specifies the alternative title text for a Shape object.
TypeScript
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
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
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
Parameters
left number
Returns
void
setLockAspectRatio(lockAspectRatio)
Specifies if the aspect ratio of this shape is locked.
TypeScript
Parameters
lockAspectRatio boolean
Returns
void
setName(name)
Specifies the name of the shape.
TypeScript
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
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");
// 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
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
Parameters
top number
Returns
void
setVisible(visible)
Specifies if the shape is visible.
TypeScript
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
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
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
Methods
ノ Expand table
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")
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".
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
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
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
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];
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
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
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
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
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
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
getShape(key) Gets a shape using its name or ID. If the shape object does not exist, then this
method returns undefined .
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
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.
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.
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
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
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
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
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
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
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");
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
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");
Methods
ノ Expand table
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.
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.
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.
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
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
Parameters
items string[]
Optional. The specified slicer item names to be selected.
Returns
void
setCaption(caption)
Represents the caption of the slicer.
TypeScript
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
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
Parameters
left number
Returns
void
setName(name)
Represents the name of the slicer.
TypeScript
Parameters
name string
Returns
void
setSortBy(sortBy)
Represents the sort order of the items in the slicer. Possible values are:
"DataSourceOrder", "Ascending", "Descending".
TypeScript
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
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
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
Methods
ノ Expand table
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.
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
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
duplicate() Creates a duplicate of this slicer style with copies of all the style elements.
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
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
Properties
ノ Expand table
color Specifies the color that is the target of the condition if the sorting is on font or cell
color.
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).
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");
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];
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();
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
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
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();
// 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
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.
getHeaderRowRange() Gets the range object associated with the header row of the table.
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.
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()
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.
getTotalRowRange() Gets the range object associated with the totals row of 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.
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
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.
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];
addRow(index, values)
Adds one row to the table.
TypeScript
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.
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];
addRows(index, values)
Adds one or more rows to the table.
TypeScript
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.
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];
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();
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];
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");
deleteRowsAt(index, count)
Delete a specified number of rows at a given index.
TypeScript
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
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];
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
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");
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];
// 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];
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];
// 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();
TypeScript
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
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
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
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
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
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();
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
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
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");
setShowTotals(showTotals)
Specifies if the total row is visible. This value can be set to show or remove the total
row.
TypeScript
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];
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
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];
Methods
ノ Expand table
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.
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.
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");
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];
// 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];
// 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");
setName(name)
Specifies the name of the table column.
TypeScript
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");
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
Methods
ノ Expand table
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.
Method Details
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();
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();
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
duplicate() Creates a duplicate of this table style with copies of all the style elements.
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
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
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");
firstColumn.addConditionalFormat(ExcelScript.ConditionalFormatType.containsT
ext).getTextComparison();
// 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.
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
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();
// 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
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.
getHorizontalOverflow() Represents the horizontal overflow behavior of the text frame. See
ExcelScript.ShapeTextHorizontalOverflow for details.
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.
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.
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.
setHorizontal Represents the horizontal overflow behavior of the text frame. See
Overflow(horizontal ExcelScript.ShapeTextHorizontalOverflow for details.
Overflow)
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)
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
Parameters
autoSizeSetting ExcelScript.ShapeAutoSize
Returns
void
setBottomMargin(bottomMargin)
Represents the bottom margin, in points, of the text frame.
TypeScript
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
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
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
Parameters
readingOrder ExcelScript.ShapeTextReadingOrder
Returns
void
setRightMargin(rightMargin)
Represents the right margin, in points, of the text frame.
TypeScript
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
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);
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)
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];
getSubstring(start, length)
Returns a TextRange object for the substring in the given range.
TypeScript
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[][] = [];
setText(text)
Represents the plain text content of the text range.
TypeScript
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
Methods
ノ Expand table
duplicate() Creates a duplicate of this timeline style with copies of all the style elements.
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
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
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();
// 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.
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
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();
Methods
ノ Expand table
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.
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.
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.
getBinding(id) Gets a binding object by ID. If the binding object does not
exist, then this method returns undefined .
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 .
getCustomXmlPart(id) Gets a custom XML part based on its ID. If the CustomXmlPart
does not exist, then this method returns undefined .
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.
getLinkedWorkbookRefresh Represents the update mode of the workbook links. The mode
Mode() is same for all of the workbook links present in the workbook.
getNamedItem(name) Gets a NamedItem object using its name. If the object does not
exist, then this method returns undefined .
getPredefinedCellStyle(name) Gets a style by name. If the style object does not exist, then
this method returns undefined .
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 .
getTable(key) Gets a table by name or ID. If the table doesn't exist, then this
method returns undefined .
getTableStyle(name) Gets a TableStyle by name. If the table style does not exist,
then this method returns undefined .
getWorksheet(key) Gets a worksheet object using its name or ID. If the worksheet
does not exist, then this method returns undefined .
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)
Method Details
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
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
Parameters
bindingType ExcelScript.BindingType
Type of binding. See ExcelScript.BindingType .
id string
Name of the binding.
Returns
ExcelScript.Binding
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.
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
Parameters
xml string
XML content. Must be a valid XML fragment.
Returns
ExcelScript.CustomXmlPart
TypeScript
addNamedItem(
name: string,
reference: Range | string,
comment?: string
): NamedItem;
Parameters
name string
The name of the named item.
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."
);
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
TypeScript
addPivotTable(
name: string,
source: Range | string | Table,
destination: Range | string
): PivotTable;
Parameters
name string
The name of the new PivotTable.
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");
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
Parameters
name string
Name of the style to be added.
Returns
void
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.
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");
addSlicerStyle(name, makeUniqueName)
Creates a blank slicer style with the specified name.
TypeScript
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();
addTableStyle(name, makeUniqueName)
Creates a blank TableStyle with the specified name.
TypeScript
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
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
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
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
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
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
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
Parameters
id string
ID of the object to be retrieved.
Returns
ExcelScript.CustomXmlPart | undefined
getCustomXmlPartByNamespace(namespaceUri)
2 Warning
Gets a new collection of custom XML parts whose namespaces match the given
namespace.
TypeScript
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
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
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
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
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");
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.`);
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();
getNamedItem(name)
Gets a NamedItem object using its name. If the object does not exist, then this
method returns undefined .
TypeScript
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
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
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
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();
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
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
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
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
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
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
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
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();
// 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
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
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
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
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
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
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
Methods
ノ Expand table
protect(password) Protects the workbook. Fails if the workbook has been protected.
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();
protect(password)
Protects the workbook. Fails if the workbook has been protected.
TypeScript
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();
TypeScript
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();
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
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
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
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
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.
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)
addNamedItemFormula Adds a new name to the collection of the given scope using the
Local(name, formula, user's locale for the formula.
comment)
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.
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.
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.
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.
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 .
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.
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.
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.
getNext(visibleOnly) Gets the worksheet that follows this one. If there are no worksheets
following this one, then this method returns undefined .
getPivotTable(name) Gets a PivotTable by name. If the PivotTable does not exist, then this
method returns undefined .
getPrevious(visibleOnly) Gets the worksheet that precedes this one. If there are no previous
worksheets, then this method returns undefined .
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)
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.
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.
getTable(key) Gets a table by name or ID. If the table doesn't exist, then this
method returns undefined .
getUsedRange(values
Only)
getVerticalPageBreaks() Gets the vertical page break collection for the worksheet. This
collection only contains manual page breaks.
replaceAll(text, Finds and replaces the given string based on the criteria specified
replacement, criteria) within the current worksheet.
setName(name) The display name of the worksheet. The name must be fewer than
32 characters.
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.
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.`);
}
}
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();
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
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);
addGroup(values)
Groups a subset of shapes in this collection's worksheet. Returns a Shape object that
represents the new group of shapes.
TypeScript
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
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
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);
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
TypeScript
addNamedItem(
name: string,
reference: Range | string,
comment?: string
): NamedItem;
Parameters
name string
The name of the named item.
comment string
Optional. The comment associated with the named item.
Returns
ExcelScript.NamedItem
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
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
TypeScript
addPivotTable(
name: string,
source: Range | string | Table,
destination: Range | string
): PivotTable;
Parameters
name string
The name of the new PivotTable.
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];
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.
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];
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
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();
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
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
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
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");
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];
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
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 });
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
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
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();
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
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
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
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 = [];
getNamedItem(name)
Gets a NamedItem object using its name. If the object does not exist, then this
method returns undefined .
TypeScript
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
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();
getPivotTable(name)
Gets a PivotTable by name. If the PivotTable does not exist, then this method returns
undefined .
TypeScript
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
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();
getRange(address)
Gets the Range object, representing a single rectangular block of cells, specified by
the address or name.
TypeScript
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();
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
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
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
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
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
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
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
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');
setPosition(position)
The zero-based position of the worksheet within the workbook.
TypeScript
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
Parameters
showGridlines boolean
Returns
void
setShowHeadings(showHeadings)
Specifies if headings are visible to the user.
TypeScript
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
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
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();
setVisibility(visibility)
The visibility of the worksheet.
TypeScript
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
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
Methods
ノ Expand table
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.)
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
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.
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 .
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
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
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
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
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();
protection.resumeProtection();
} else {
console.log("Incorrect password");
}
}
Methods
ノ Expand table
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.
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.
Method Details
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
};
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
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
TypeScript
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
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
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();
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
Parameters
password string
The password associated with the WorksheetProtection object.
Returns
void
unprotect(password)
Unprotects a worksheet.
TypeScript
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
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
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();
Properties
ノ Expand table
allowAutoFilter Represents the worksheet protection option allowing use of the AutoFilter
feature.
allowPivotTables Represents the worksheet protection option allowing use of the PivotTable
feature.
allowSort Represents the worksheet protection option allowing use of the sort
feature.
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
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);
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.