Class Range

Range

Access and modify spreadsheet ranges. A range can be a single cell in a sheet or a group of adjacent cells in a sheet.

Methods

MethodReturn typeBrief description
activate()RangeSets the specified range as the active range, with the top left cell in the range as the current cell.
activateAsCurrentCell()RangeSets the specified cell as the current cell.
applyColumnBanding()BandingApplies a default column banding theme to the range.
applyColumnBanding(bandingTheme)BandingApplies a specified column banding theme to the range.
applyColumnBanding(bandingTheme, showHeader, showFooter)BandingApplies a specified column banding theme to the range with specified header and footer settings.
applyRowBanding()BandingApplies a default row banding theme to the range.
applyRowBanding(bandingTheme)BandingApplies a specified row banding theme to the range.
applyRowBanding(bandingTheme, showHeader, showFooter)BandingApplies a specified row banding theme to the range with specified header and footer settings.
autoFill(destination, series)voidFills the destinationRange with data based on the data in this range.
autoFillToNeighbor(series)voidCalculates a range to fill with new data based on neighboring cells and automatically fills that range with new values based on the data contained in this range.
breakApart()RangeBreak any multi-column cells in the range into individual cells again.
canEdit()BooleanDetermines whether the user has permission to edit every cell in the range.
clear()RangeClears the range of contents, formats, and data validation rules.
clear(options)RangeClears the range of contents, format, data validation rules, and/or comments, as specified with the given advanced options.
clearContent()RangeClears the content of the range, leaving the formatting intact.
clearDataValidations()RangeClears the data validation rules for the range.
clearFormat()RangeClears formatting for this range.
clearNote()RangeClears the note in the given cell or cells.
collapseGroups()RangeCollapses all groups that are wholly contained within the range.
copyFormatToRange(gridId, column, columnEnd, row, rowEnd)voidCopy the formatting of the range to the given location.
copyFormatToRange(sheet, column, columnEnd, row, rowEnd)voidCopy the formatting of the range to the given location.
copyTo(destination)voidCopies the data from a range of cells to another range of cells.
copyTo(destination, copyPasteType, transposed)voidCopies the data from a range of cells to another range of cells.
copyTo(destination, options)voidCopies the data from a range of cells to another range of cells.
copyValuesToRange(gridId, column, columnEnd, row, rowEnd)voidCopy the content of the range to the given location.
copyValuesToRange(sheet, column, columnEnd, row, rowEnd)voidCopy the content of the range to the given location.
createFilter()FilterCreates a filter applied to the range.
createPivotTable(sourceData)PivotTableCreates an empty pivot table from the specified sourceData anchored at the first cell in this range.
deleteCells(shiftDimension)voidDeletes this range of cells.
expandGroups()RangeExpands the collapsed groups whose range or control toggle intersects with this range.
getA1Notation()StringReturns a string description of the range, in A1 notation.
getBackground()StringReturns the background color of the top-left cell in the range (i.e., '#ffffff').
getBackgrounds()String[][]Returns the background colors of the cells in the range (i.e., '#ffffff').
getBandings()Banding[]Returns all the bandings that are applied to any cells in this range.
getCell(row, column)RangeReturns a given cell within a range.
getColumn()IntegerReturns the starting column position for this range.
getDataSourceUrl()StringReturns a URL for the data in this range, which can be used to create charts and queries.
getDataTable()DataTableReturn the data inside this object as a DataTable.
getDataTable(firstRowIsHeader)DataTableReturn the data inside this range as a DataTable.
getDataValidation()DataValidationReturns the data validation rule for the top-left cell in the range.
getDataValidations()DataValidation[][]Returns the data validation rules for all cells in the range.
getDisplayValue()StringReturns the displayed value of the top-left cell in the range.
getDisplayValues()String[][]Returns the rectangular grid of values for this range.
getFilter()FilterReturns the filter in the sheet this range belongs to, or null if there is no filter on the sheet.
getFontColor()StringReturns the font color of the cell in the top-left corner of the range, in CSS notation (such as '#ffffff' or 'white').
getFontColors()String[][]Returns the font colors of the cells in the range in CSS notation (such as '#ffffff' or 'white').
getFontFamilies()String[][]Returns the font families of the cells in the range.
getFontFamily()StringReturns the font family of the cell in the top-left corner of the range.
getFontLine()StringGets the line style of the cell in the top-left corner of the range ('underline', 'line-through', or 'none').
getFontLines()String[][]Gets the line style of the cells in the range ('underline', 'line-through', or 'none').
getFontSize()IntegerReturns the font size in point size of the cell in the top-left corner of the range.
getFontSizes()Integer[][]Returns the font sizes of the cells in the range.
getFontStyle()StringReturns the font style ('italic' or 'normal') of the cell in the top-left corner of the range.
getFontStyles()String[][]Returns the font styles of the cells in the range.
getFontWeight()StringReturns the font weight (normal/bold) of the cell in the top-left corner of the range.
getFontWeights()String[][]Returns the font weights of the cells in the range.
getFormula()StringReturns the formula (A1 notation) for the top-left cell of the range, or an empty string if the cell is empty or doesn't contain a formula.
getFormulaR1C1()StringReturns the formula (R1C1 notation) for a given cell, or null if none.
getFormulas()String[][]Returns the formulas (A1 notation) for the cells in the range.
getFormulasR1C1()String[][]Returns the formulas (R1C1 notation) for the cells in the range.
getGridId()IntegerReturns the grid ID of the range's parent sheet.
getHeight()IntegerReturns the height of the range.
getHorizontalAlignment()StringReturns the horizontal alignment of the text (left/center/right) of the cell in the top-left corner of the range.
getHorizontalAlignments()String[][]Returns the horizontal alignments of the cells in the range.
getLastColumn()IntegerReturns the end column position.
getLastRow()IntegerReturns the end row position.
getMergedRanges()Range[]Returns an array of Range objects representing merged cells that either are fully within the current range, or contain at least one cell in the current range.
getNextDataCell(direction)RangeStarting at the cell in the first column and row of the range, returns the next cell in the given direction that is the edge of a contiguous range of cells with data in them or the cell at the edge of the spreadsheet in that direction.
getNote()StringReturns the note associated with the given range.
getNotes()String[][]Returns the notes associated with the cells in the range.
getNumColumns()IntegerReturns the number of columns in this range.
getNumRows()IntegerReturns the number of rows in this range.
getNumberFormat()StringGet the number or date formatting of the top-left cell of the given range.
getNumberFormats()String[][]Returns the number or date formats for the cells in the range.
getRow()IntegerReturns the row position for this range.
getRowIndex()IntegerReturns the row position for this range.
getSheet()SheetReturns the sheet this range belongs to.
getTextDirection()TextDirectionReturns the text direction for the top left cell of the range.
getTextDirections()TextDirection[][]Returns the text directions for the cells in the range.
getTextRotation()TextRotationReturns the text rotation settings for the top left cell of the range.
getTextRotations()TextRotation[][]Returns the text rotation settings for the cells in the range.
getValue()ObjectReturns the value of the top-left cell in the range.
getValues()Object[][]Returns the rectangular grid of values for this range.
getVerticalAlignment()StringReturns the vertical alignment (top/middle/bottom) of the cell in the top-left corner of the range.
getVerticalAlignments()String[][]Returns the vertical alignments of the cells in the range.
getWidth()IntegerReturns the width of the range in columns.
getWrap()BooleanReturns the wrapping policy of the cell in the top-left corner of the range.
getWrapStrategies()WrapStrategy[][]Returns the text wrapping strategies for the cells in the range.
getWrapStrategy()WrapStrategyReturns the text wrapping strategy for the top left cell of the range.
getWraps()Boolean[][]Returns the wrapping policy of the cells in the range.
insertCells(shiftDimension)RangeInserts empty cells into this range.
isBlank()BooleanReturns true if the range is totally blank.
isEndColumnBounded()BooleanDetermines whether the end of the range is bound to a particular column.
isEndRowBounded()BooleanDetermines whether the end of the range is bound to a particular row.
isPartOfMerge()BooleanReturns true if the cells in the current range overlap any merged cells.
isStartColumnBounded()BooleanDetermines whether the start of the range is bound to a particular column.
isStartRowBounded()BooleanDetermines whether the start of the range is bound to a particular row.
merge()RangeMerges the cells in the range together into a single block.
mergeAcross()RangeMerge the cells in the range across the columns of the range.
mergeVertically()RangeMerges the cells in the range together.
moveTo(target)voidCut and paste (both format and values) from this range to the target range.
offset(rowOffset, columnOffset)RangeReturns a new range that is offset from this range by the given number of rows and columns (which can be negative).
offset(rowOffset, columnOffset, numRows)RangeReturns a new range that is relative to the current range, whose upper left point is offset from the current range by the given rows and columns, and with the given height in cells.
offset(rowOffset, columnOffset, numRows, numColumns)RangeReturns a new range that is relative to the current range, whose upper left point is offset from the current range by the given rows and columns, and with the given height and width in cells.
protect()ProtectionCreates an object that can protect the range from being edited except by users who have permission.
randomize()RangeRandomizes the order of the rows in the given range.
setBackground(color)RangeSets the background color of all cells in the range in CSS notation (such as '#ffffff' or 'white').
setBackgroundRGB(red, green, blue)RangeSets the background to the given color using RGB values (integers between 0 and 255 inclusive).
setBackgrounds(color)RangeSets a rectangular grid of background colors (must match dimensions of this range).
setBorder(top, left, bottom, right, vertical, horizontal)RangeSets the border property.
setBorder(top, left, bottom, right, vertical, horizontal, color, style)RangeSets the border property with color and/or style.
setDataValidation(rule)RangeSets one data validation rule for all cells in the range.
setDataValidations(rules)RangeSets the data validation rules for all cells in the range.
setFontColor(color)RangeSets the font color in CSS notation (such as '#ffffff' or 'white').
setFontColors(colors)RangeSets a rectangular grid of font colors (must match dimensions of this range).
setFontFamilies(fontFamilies)RangeSets a rectangular grid of font families (must match dimensions of this range).
setFontFamily(fontFamily)RangeSets the font family, such as "Arial" or "Helvetica".
setFontLine(fontLine)RangeSets the font line style of the given range ('underline', 'line-through', or 'none').
setFontLines(fontLines)RangeSets a rectangular grid of line styles (must match dimensions of this range).
setFontSize(size)RangeSets the font size, with the size being the point size to use.
setFontSizes(sizes)RangeSets a rectangular grid of font sizes (must match dimensions of this range).
setFontStyle(fontStyle)RangeSet the font style for the given range ('italic' or 'normal').
setFontStyles(fontStyles)RangeSets a rectangular grid of font styles (must match dimensions of this range).
setFontWeight(fontWeight)RangeSet the font weight for the given range (normal/bold).
setFontWeights(fontWeights)RangeSets a rectangular grid of font weights (must match dimensions of this range).
setFormula(formula)RangeUpdates the formula for this range.
setFormulaR1C1(formula)RangeUpdates the formula for this range.
setFormulas(formulas)RangeSets a rectangular grid of formulas (must match dimensions of this range).
setFormulasR1C1(formulas)RangeSets a rectangular grid of formulas (must match dimensions of this range).
setHorizontalAlignment(alignment)RangeSet the horizontal (left to right) alignment for the given range (left/center/right).
setHorizontalAlignments(alignments)RangeSets a rectangular grid of horizontal alignments.
setNote(note)RangeSets the note to the given value.
setNotes(notes)RangeSets a rectangular grid of notes (must match dimensions of this range).
setNumberFormat(numberFormat)RangeSets the number or date format to the given formatting string.
setNumberFormats(numberFormats)RangeSets a rectangular grid of number or date formats (must match dimensions of this range).
setShowHyperlink(showHyperlink)RangeSets whether or not the range should show hyperlinks.
setTextDirection(direction)RangeSets the text direction for the cells in the range.
setTextDirections(directions)RangeSets a rectangular grid of text directions.
setTextRotation(degrees)RangeSets the text rotation settings for the cells in the range.
setTextRotation(rotation)RangeSets the text rotation settings for the cells in the range.
setTextRotations(rotations)RangeSets a rectangular grid of text rotations.
setValue(value)RangeSets the value of the range.
setValues(values)RangeSets a rectangular grid of values (must match dimensions of this range).
setVerticalAlignment(alignment)RangeSet the vertical (top to bottom) alignment for the given range (top/middle/bottom).
setVerticalAlignments(alignments)RangeSets a rectangular grid of vertical alignments (must match dimensions of this range).
setVerticalText(isVertical)RangeSets whether or not to stack the text for the cells in the range.
setWrap(isWrapEnabled)RangeSet the cell wrap of the given range.
setWrapStrategies(strategies)RangeSets a rectangular grid of wrap strategies.
setWrapStrategy(strategy)RangeSets the text wrapping strategy for the cells in the range.
setWraps(isWrapEnabled)RangeSets a rectangular grid of word wrap policies (must match dimensions of this range).
shiftColumnGroupDepth(delta)RangeChanges the column grouping depth of the range by the specified amount.
shiftRowGroupDepth(delta)RangeChanges the row grouping depth of the range by the specified amount.
sort(sortSpecObj)RangeSorts the cells in the given range, by column and order specified.
splitTextToColumns()voidSplits a column of text into multiple columns based on an auto-detected delimiter.
splitTextToColumns(delimiter)voidSplits a column of text into multiple columns using the specified string as a custom delimiter.
splitTextToColumns(delimiter)voidSplits a column of text into multiple columns based on the specified delimiter.

Detailed documentation

activate()

Sets the specified range as the active range, with the top left cell in the range as the current cell.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = sheet.getRange('A1:D10');
range.activate();

var selection = sheet.getSelection();
// Current cell: A1
var currentCell = selection.getCurrentCell();
// Active Range: A1:D10
var activeRange = selection.getActiveRange();

Return

Range — this range, for chaining


activateAsCurrentCell()

Sets the specified cell as the current cell.

If the specified cell is present in an existing range, then that range becomes the active range with the cell as the current cell.

If the specified cell is not present in any existing range, then the existing selection is removed and the cell becomes the current cell and the active range.

Note: The specified Range must consist of one cell, otherwise it throws an exception.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = sheet.getRange('B5');
range.activate();

var selection = sheet.getSelection();
// Current cell: B5
var currentCell = selection.getCurrentCell();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

applyColumnBanding()

Applies a default column banding theme to the range. By default, the banding has header and no footer color.

Return

Banding — the new banding

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

applyColumnBanding(bandingTheme)

Applies a specified column banding theme to the range. By default, the banding has header and no footer color.

Parameters

NameTypeDescription
bandingThemeBandingThemeA color theme to apply to the columns in the range.

Return

Banding — the new banding

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

applyColumnBanding(bandingTheme, showHeader, showFooter)

Applies a specified column banding theme to the range with specified header and footer settings.

Parameters

NameTypeDescription
bandingThemeBandingThemeA color theme to apply to the columns in the range.
showHeaderBooleanIf true, the banding theme header color is applied to the first column.
showFooterBooleanIf true, the banding theme footer color is applied to the last column.

Return

Banding — the new banding

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

applyRowBanding()

Applies a default row banding theme to the range. By default, the banding has header and no footer color.

Return

Banding — the new banding

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

applyRowBanding(bandingTheme)

Applies a specified row banding theme to the range. By default, the banding has header and no footer color.

Parameters

NameTypeDescription
bandingThemeBandingThemeA color theme to apply to the rows in the range.

Return

Banding — the new banding

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

applyRowBanding(bandingTheme, showHeader, showFooter)

Applies a specified row banding theme to the range with specified header and footer settings.

Parameters

NameTypeDescription
bandingThemeBandingThemeA color theme to apply to the rows in the range.
showHeaderBooleanIf true, the banding theme header color is applied to the first row.
showFooterBooleanIf true, the banding theme footer color is applied to the last row.

Return

Banding — the new banding

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

autoFill(destination, series)

Fills the destinationRange with data based on the data in this range. The new values are also determined by the specified series type. The destination range must contain this range and extend it in only one direction. For example, the following fills A1:A20 with a series of increasing numbers based on the current values in A1:A4:

var sheet = SpreadsheetApp.getActiveSheet();

// Has values [1, 2, 3, 4].
var sourceRange = sheet.getRange("A1:A4");
// The range to fill with values.
var destination = sheet.getRange("A1:A20");

// Inserts new values in A5:A20, continuing the pattern expressed in A1:A4
sourceRange.autoFill(destination, SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);

Parameters

NameTypeDescription
destinationRangeThe range to be auto-filled with values. The destination range should contain this range and extend it in only one direction (upwards, downwards, left, or right).
seriesAutoFillSeriesThe type of autoFill series that should be used to calculate new values. The effect of this series differs based on the type and amount of source data.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

autoFillToNeighbor(series)

Calculates a range to fill with new data based on neighboring cells and automatically fills that range with new values based on the data contained in this range. These new values are also determined by the specified series type.

The calculated destination range considers the surrounding data to determine where the new values should be inserted: if there is data to the immediate left or right of a column that is being auto-filled, new values only extend as far as this adjacent data.

For example, if A1:A20 is filled with a series of increasing numbers and this method is called on the range B1:B4 which contains a series of dates, new values are only inserted into B5:B20. In this way, these new values "stick" to the cells that contain values in column A.

var sheet = SpreadsheetApp.getActiveSheet();

// A1:A20 has values [1, 2, 3, ... 20].
// B1:B4 has values [1/1/2017, 1/2/2017, ...]
var sourceRange = sheet.getRange("B1:B4");

// Results in B5:B20 having values [1/5/2017, ... 1/20/2017]
sourceRange.autoFillToNeighbor(SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);

Parameters

NameTypeDescription
seriesAutoFillSeriesThe type of autoFill series that should be used to calculate new values. The effect of this series differs based on the type and amount of source data.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

breakApart()

Break any multi-column cells in the range into individual cells again.

Calling this function on a range is equivalent to selecting a range and clicking Format -> Merge -> Unmerge.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

canEdit()

Determines whether the user has permission to edit every cell in the range. The spreadsheet owner is always able to edit protected ranges and sheets.

Return

Booleantrue if the user has permission to edit every cell in the range; false if not

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

clear()

Clears the range of contents, formats, and data validation rules.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:D10");
range.clear();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

clear(options)

Clears the range of contents, format, data validation rules, and/or comments, as specified with the given advanced options. By default all data is cleared.

// The code below clears range C2:G8 in the active sheet, but preserves the format,
// data validation rules, and comments.
SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).clear({contentsOnly: true});

Parameters

NameTypeDescription
optionsObjectA JavaScript object that specifies advanced parameters, as listed below.

Advanced parameters

NameTypeDescription
commentsOnlyBooleanWhether to clear only the comments.
contentsOnlyBooleanWhether to clear only the contents.
formatOnlyBooleanWhether to clear only the format; note that clearing format also clears data validation rules.
validationsOnlyBooleanWhether to clear only data validation rules.
skipFilteredRowsBooleanWhether to avoid clearing filtered rows.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

clearContent()

Clears the content of the range, leaving the formatting intact.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:D10");
range.clearContent();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

clearDataValidations()

Clears the data validation rules for the range.

// Clear the data validation rules for cells A1:B5.
var range = SpreadsheetApp.getActive().getRange('A1:B5');
range.clearDataValidations();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

clearFormat()

Clears formatting for this range.

This clears text formatting for the cell or cells in the range, but does not reset any number formatting rules.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:D10");
range.clearFormat();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

clearNote()

Clears the note in the given cell or cells.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:D10");
range.clearNote();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

collapseGroups()

Collapses all groups that are wholly contained within the range. If no group is fully within the range, the deepest expanded group that is partially within the range is collapsed.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = sheet.getActiveRange();

// All row and column groups within the range are collapsed.
range.expandGroups();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

copyFormatToRange(gridId, column, columnEnd, row, rowEnd)

Copy the formatting of the range to the given location. If the destination is larger or smaller than the source range then the source is repeated or truncated accordingly. Note that this method copies the formatting only.

For a detailed description of the gridId parameter, see getGridId().

var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheets()[0];

var range = source.getRange("B2:D4");

// This copies the formatting in B2:D4 in the source sheet to
// D4:F6 in the sheet with gridId 1555299895. Note that you can get the gridId
// of a sheet by calling sheet.getSheetId() or range.getGridId().
range.copyFormatToRange(1555299895, 4, 6, 4, 6);

Parameters

NameTypeDescription
gridIdIntegerThe unique ID of the sheet within the spreadsheet, irrespective of position.
columnIntegerThe first column of the target range.
columnEndIntegerThe end column of the target range.
rowIntegerThe start row of the target range.
rowEndIntegerThe end row of the target range.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

See also


copyFormatToRange(sheet, column, columnEnd, row, rowEnd)

Copy the formatting of the range to the given location. If the destination is larger or smaller than the source range then the source is repeated or truncated accordingly. Note that this method copies the formatting only.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheets()[0];
var destination = ss.getSheets()[1];

var range = source.getRange("B2:D4");

// This copies the formatting in B2:D4 in the source sheet to
// D4:F6 in the second sheet
range.copyFormatToRange(destination, 4, 6, 4, 6);

Parameters

NameTypeDescription
sheetSheetThe target sheet.
columnIntegerThe first column of the target range.
columnEndIntegerThe end column of the target range.
rowIntegerThe start row of the target range.
rowEndIntegerThe end row of the target range.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

copyTo(destination)

Copies the data from a range of cells to another range of cells. Both the values and formatting are copied.

// The code below copies the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
var rangeToCopy = sheet.getRange(1, 1, sheet.getMaxRows(), 5);
rangeToCopy.copyTo(sheet.getRange(1, 6));
}

Parameters

NameTypeDescription
destinationRangeA destination range to copy to; only the top-left cell position is relevant.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

copyTo(destination, copyPasteType, transposed)

Copies the data from a range of cells to another range of cells.

// The code below copies only the values of the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("A:E").copyTo(sheet.getRange("F1"), spreadsheetApp.CopyPasteType.PASTE_VALUES);

Parameters

NameTypeDescription
destinationRangeA destination range to copy to; only the top-left cell position is relevant.
copyPasteTypeCopyPasteTypeA type that specifies how the range contents are pasted to the destination.
transposedBooleanwhether the range should be pasted in its transposed orientation.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

copyTo(destination, options)

Copies the data from a range of cells to another range of cells. By default both the values and formatting are copied, but this can be overridden using advanced arguments.

// The code below copies only the values of the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("A:E").copyTo(sheet.getRange("F1"), {contentsOnly:true});
}

Parameters

NameTypeDescription
destinationRangeA destination range to copy to; only the top-left cell position is relevant.
optionsObjectA JavaScript object that specifies advanced parameters, as listed below.

Advanced parameters

NameTypeDescription
formatOnlyBooleandesignates that only the format should be copied
contentsOnlyBooleandesignates that only the content should be copied

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

copyValuesToRange(gridId, column, columnEnd, row, rowEnd)

Copy the content of the range to the given location. If the destination is larger or smaller than the source range then the source is repeated or truncated accordingly.

For a detailed description of the gridId parameter, see getGridId().

var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheets()[0];

var range = source.getRange("B2:D4");

// This copies the data in B2:D4 in the source sheet to
// D4:F6 in the sheet with gridId 0
range.copyValuesToRange(0, 4, 6, 4, 6);

Parameters

NameTypeDescription
gridIdIntegerThe unique ID of the sheet within the spreadsheet, irrespective of position.
columnIntegerThe first column of the target range.
columnEndIntegerThe end column of the target range.
rowIntegerThe start row of the target range.
rowEndIntegerThe end row of the target range.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

See also


copyValuesToRange(sheet, column, columnEnd, row, rowEnd)

Copy the content of the range to the given location. If the destination is larger or smaller than the source range then the source is repeated or truncated accordingly.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheets()[0];
var destination = ss.getSheets()[1];

var range = source.getRange("B2:D4");

// This copies the data in B2:D4 in the source sheet to
// D4:F6 in the second sheet
range.copyValuesToRange(destination, 4, 6, 4, 6);

Parameters

NameTypeDescription
sheetSheetThe target sheet.
columnIntegerThe first column of the target range.
columnEndIntegerThe end column of the target range.
rowIntegerThe start row of the target range.
rowEndIntegerThe end row of the target range.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

createFilter()

Creates a filter applied to the range. There can be at most one filter in a sheet.

Return

Filter — the new filter

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

createPivotTable(sourceData)

Creates an empty pivot table from the specified sourceData anchored at the first cell in this range.

Parameters

NameTypeDescription
sourceDataRange

Return

PivotTable — the newly created PivotTable

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

deleteCells(shiftDimension)

Deletes this range of cells. Existing data in the sheet along the provided dimension is shifted towards the deleted range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:D10");
range.deleteCells(SpreadsheetApp.Dimension.COLUMNS);

Parameters

NameTypeDescription
shiftDimensionDimensionThe dimension along which to shift existing data.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

expandGroups()

Expands the collapsed groups whose range or control toggle intersects with this range. The control toggle location is the index at which the control toggle is shown, directly before or after the group depending on settings. If there is more than one group at the same location, the shallowest group is expanded.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = sheet.getActiveRange();

// All row and column groups within the range are expanded.
range.expandGroups();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getA1Notation()

Returns a string description of the range, in A1 notation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange(1, 1, 2, 5);

// Logs "A1:E2"
Logger.log(range.getA1Notation());

Return

String — the string description of the range in A1 notation

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getBackground()

Returns the background color of the top-left cell in the range (i.e., '#ffffff').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B5");
Logger.log(cell.getBackground());

Return

String — the color code of the background

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getBackgrounds()

Returns the background colors of the cells in the range (i.e., '#ffffff').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B5:C6");
var bgColors = range.getBackgrounds();
for (var i in bgColors) {
  for (var j in bgColors[i]) {
    Logger.log(bgColors[i][j]);
  }
}

Return

String[][] — a two-dimensional array of color codes of the backgrounds

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getBandings()

Returns all the bandings that are applied to any cells in this range.

Return

Banding[] — all the bandings that are applied to any cells in this range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getCell(row, column)

Returns a given cell within a range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2:D4");

// The row and column here are relative to the range
// getCell(1,1) in this code returns the cell at B2, B2
var cell = range.getCell(1, 1);
Logger.log(cell.getValue());

Parameters

NameTypeDescription
rowIntegerThe row of the cell relative to the range.
columnIntegerThe column of the cell relative to the range.

Return

Range — a range containing a single cell at the specified coordinates

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getColumn()

Returns the starting column position for this range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2:D4");
// Logs "2.0"
Logger.log(range.getColumn());

Return

Integer — the range's starting column position in the spreadsheet

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getDataSourceUrl()

Returns a URL for the data in this range, which can be used to create charts and queries.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("A1:B7");

var dataSourceUrl = range.getDataSourceUrl();

// Note that this doesn't build an EmbeddedChart, so we can't just use
// Sheet#insertChart(). If we want to do that, we should use
// sheet.newChart().addRange() instead.
var chart = Charts.newBarChart()
    .setOption("title", "Your Title Here")
    .setDataSourceUrl(dataSourceUrl)
    .build();

var app = UiApp.createApplication();
app.add(chart);
ss.show(app);

Return

String — a URL for this range as a data source that can be passed to other APIs such as charts

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getDataTable()

Return the data inside this object as a DataTable.

Return

DataTable — the data as a datatable.


getDataTable(firstRowIsHeader)

Return the data inside this range as a DataTable.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("A1:B7");

// Calling this method with "true" sets the first line to be the title of the axes
var datatable = range.getDataTable(true);

// Note that this doesn't build an EmbeddedChart, so we can't just use
// Sheet#insertChart(). If we want to do that, we should use
// sheet.newChart().addRange() instead.
var chart = Charts.newBarChart()
    .setDataTable(datatable)
    .setOption("title", "Your Title Here")
    .build();

var app = UiApp.createApplication();
app.add(chart);
ss.show(app);

Parameters

NameTypeDescription
firstRowIsHeaderBooleanWhether to treat the first row as a header.

Return

DataTable — the data as a datatable

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getDataValidation()

Returns the data validation rule for the top-left cell in the range. If data validation has not been set on the cell, this method returns null.

// Log information about the data validation rule for cell A1.
var cell = SpreadsheetApp.getActive().getRange('A1');
var rule = cell.getDataValidation();
if (rule != null) {
  var criteria = rule.getCriteriaType();
  var args = rule.getCriteriaValues();
  Logger.log('The data validation rule is %s %s', criteria, args);
} else {
  Logger.log('The cell does not have a data validation rule.')
}

Return

DataValidation — the data validation rule for the top-left cell in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getDataValidations()

Returns the data validation rules for all cells in the range. If data validation has not been set on a given cell, this method returns null for that cell's position in the array.

// Change existing data validation rules that require a date in 2013 to require a date in 2014.
var oldDates = [new Date('1/1/2013'), new Date('12/31/2013')];
var newDates = [new Date('1/1/2014'), new Date('12/31/2014')];
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns());
var rules = range.getDataValidations();

for (var i = 0; i < rules.length; i++) {
  for (var j = 0; j < rules[i].length; j++) {
    var rule = rules[i][j];

    if (rule != null) {
      var criteria = rule.getCriteriaType();
      var args = rule.getCriteriaValues();

      if (criteria == SpreadsheetApp.DataValidationCriteria.DATE_BETWEEN
          && args[0].getTime() == oldDates[0].getTime()
          && args[1].getTime() == oldDates[1].getTime()) {
        // Create a builder from the existing rule, then change the dates.
        rules[i][j] = rule.copy().withCriteria(criteria, newDates).build();
      }
    }
  }
}
range.setDataValidations(rules);

Return

DataValidation[][] — a two-dimensional array of data validation rules associated with the cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getDisplayValue()

Returns the displayed value of the top-left cell in the range. The value is a String. The displayed value takes into account date, time and currency formatting formatting, including formats applied automatically by the spreadsheet's locale setting. Empty cells return an empty string.

Return

String — the displayed value in this cell

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getDisplayValues()

Returns the rectangular grid of values for this range.

Returns a two-dimensional array of displayed values, indexed by row, then by column. The values are String objects. The displayed value takes into account date, time and currency formatting, including formats applied automatically by the spreadsheet's locale setting. Empty cells are represented by an empty string in the array. Remember that while a range index starts at 1, 1, the JavaScript array is indexed from [0][0].

// The code below gets the displayed values for the range C2:G8
// in the active spreadsheet.  Note that this is a JavaScript array.
var values = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getDisplayValues();
Logger.log(values[0][0]);

Return

String[][] — a two-dimensional array of values

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFilter()

Returns the filter in the sheet this range belongs to, or null if there is no filter on the sheet.

Return

Filter — the filter

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontColor()

Returns the font color of the cell in the top-left corner of the range, in CSS notation (such as '#ffffff' or 'white').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getFontColor());

Return

String — the font color in CSS notation (such as '#ffffff' or 'white')

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontColors()

Returns the font colors of the cells in the range in CSS notation (such as '#ffffff' or 'white').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getFontColors();

for (var i in results) {
  for (var j in results[i]) {
    Logger.log(results[i][j]);
  }
}

Return

String[][] — a two-dimensional array of font colors associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontFamilies()

Returns the font families of the cells in the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getFontFamilies();

for (var i in results) {
  for (var j in results[i]) {
    Logger.log(results[i][j]);
  }
}

Return

String[][] — a two-dimensional array of font families associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontFamily()

Returns the font family of the cell in the top-left corner of the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getFontFamily());

Return

String — the font family of the cell

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontLine()

Gets the line style of the cell in the top-left corner of the range ('underline', 'line-through', or 'none').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getFontLine());

Return

String — the font line

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontLines()

Gets the line style of the cells in the range ('underline', 'line-through', or 'none').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getFontLines();

for (var i in results) {
  for (var j in results[i]) {
    Logger.log(results[i][j]);
  }
}

Return

String[][] — a two-dimensional array of font lines associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontSize()

Returns the font size in point size of the cell in the top-left corner of the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getFontSize());

Return

Integer — the font size in point size

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontSizes()

Returns the font sizes of the cells in the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getFontSizes();

for (var i in results) {
  for (var j in results[i]) {
    Logger.log(results[i][j]);
  }
}

Return

Integer[][] — a two-dimensional array of font sizes of text associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontStyle()

Returns the font style ('italic' or 'normal') of the cell in the top-left corner of the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getFontStyle());

Return

String — the font style of the text in the cell

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontStyles()

Returns the font styles of the cells in the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getFontStyles();

for (var i in results) {
  for (var j in results[i]) {
    Logger.log(results[i][j]);
  }
}

Return

String[][] — a two-dimensional array of font styles of text associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontWeight()

Returns the font weight (normal/bold) of the cell in the top-left corner of the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getFontWeight());

Return

String — the font weight of the text in the cell

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFontWeights()

Returns the font weights of the cells in the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getFontWeights();

for (var i in results) {
  for (var j in results[i]) {
    Logger.log(results[i][j]);
  }
}

Return

String[][] — a two-dimensional array of font weights of text associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFormula()

Returns the formula (A1 notation) for the top-left cell of the range, or an empty string if the cell is empty or doesn't contain a formula.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// This assumes we have a function in B5 that sums up
// B2:B4
var range = sheet.getRange("B5");

// Logs the calculated value and the formula
Logger.log("Calculated value: %s Formula: %s",
           range.getValue(),
           range.getFormula());

Return

String — the formula for the cell

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFormulaR1C1()

Returns the formula (R1C1 notation) for a given cell, or null if none.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B5");
var formula = range.getFormulaR1C1();
Logger.log(formula);

Return

String — the formula in R1C1 notation

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFormulas()

Returns the formulas (A1 notation) for the cells in the range. Entries in the 2D array are empty strings for cells with no formula.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B5:C6");
var formulas = range.getFormulas();
for (var i in formulas) {
  for (var j in formulas[i]) {
    Logger.log(formulas[i][j]);
  }
}

Return

String[][] — a two-dimensional array of formulas in string format

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getFormulasR1C1()

Returns the formulas (R1C1 notation) for the cells in the range. Entries in the 2D array are null for cells with no formula.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B5:C6");
var formulas = range.getFormulasR1C1();
for (var i in formulas) {
  for (var j in formulas[i]) {
    Logger.log(formulas[i][j]);
  }
}

Return

String[][] — a two-dimensional array of formulas in R1C1 notation

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getGridId()

Returns the grid ID of the range's parent sheet. IDs are random non-negative int values.

// Log the grid ID of the first sheet (by tab position) in the spreadsheet.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getGridId());

Return

Integer — the grid ID of the parent sheet

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getHeight()

Returns the height of the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2:D4");
// logs 3.0
Logger.log(range.getHeight());

Return

Integer — the height of the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getHorizontalAlignment()

Returns the horizontal alignment of the text (left/center/right) of the cell in the top-left corner of the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getHorizontalAlignment());

Return

String — the horizontal alignment of the text in the cell

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getHorizontalAlignments()

Returns the horizontal alignments of the cells in the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getHorizontalAlignments();

for (var i in results) {
  for (var j in results[i]) {
    Logger.log(results[i][j]);
  }
}

Return

String[][] — a two-dimensional array of horizontal alignments of text associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getLastColumn()

Returns the end column position.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2:D4");
// Logs "4.0"
Logger.log(range.getLastColumn());

Return

Integer — the range's ending column position in the spreadsheet

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getLastRow()

Returns the end row position.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2:D4");
// Logs "4.0"
Logger.log(range.getLastRow());

Return

Integer — the range's ending row position in the spreadsheet

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getMergedRanges()

Returns an array of Range objects representing merged cells that either are fully within the current range, or contain at least one cell in the current range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:B3");

var mergedRanges = range.getMergedRanges();
for (var i = 0; i < mergedRanges.length; i++) {
  Logger.log(mergedRanges[i].getA1Notation());
  Logger.log(mergedRanges[i].getDisplayValue());
}

Return

Range[] — An array of Range objects, representing merged cells overlapping the range


getNextDataCell(direction)

Starting at the cell in the first column and row of the range, returns the next cell in the given direction that is the edge of a contiguous range of cells with data in them or the cell at the edge of the spreadsheet in that direction. This is equivalent to typing Ctrl+[arrow key] in the editor.

// Assume the active spreadsheet is blank.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("C3:E5");
// Logs "C1"
Logger.log(range.getNextDataCell(Direction.UP).getA1Notation());

Parameters

NameTypeDescription
directionDirectionThe direction in which to find the next data region edge cell.

Return

Range — the data region edge cell or the cell at the edge of the spreadsheet

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getNote()

Returns the note associated with the given range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getNote());

Return

String — the note associated with the given cell

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getNotes()

Returns the notes associated with the cells in the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getNotes();

for (var i in results) {
  for (var j in results[i]) {
    Logger.log(results[i][j]);
  }
}

Return

String[][] — a two-dimensional array of notes associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getNumColumns()

Returns the number of columns in this range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2:D5");
Logger.log(range.getNumColumns());

Return

Integer — the number of columns in this range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getNumRows()

Returns the number of rows in this range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2:D5");
Logger.log(range.getNumRows());

Return

Integer — the number of rows in this range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getNumberFormat()

Get the number or date formatting of the top-left cell of the given range. The returned format patterns are described in the Sheets API documentation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("C4");
Logger.log(cell.getNumberFormat());

Return

String — the number format of the top-left cell of the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getNumberFormats()

Returns the number or date formats for the cells in the range. The returned format patterns are described in the Sheets API documentation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B5:C6");
var formats = range.getNumberFormats();
for (var i in formats) {
  for (var j in formats[i]) {
    Logger.log(formats[i][j]);
  }
}

Return

String[][] — a two-dimensional array of number formats

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getRow()

Returns the row position for this range. Identical to getRowIndex().

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2");
Logger.log(range.getRow());

Return

Integer — the row position of the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getRowIndex()

Returns the row position for this range. Identical to getRow().

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2");
Logger.log(range.getRowIndex());

Return

Integer — the row position of the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

See also


getSheet()

Returns the sheet this range belongs to.

Return

Sheet — the sheet that this range belongs to

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getTextDirection()

Returns the text direction for the top left cell of the range. Returns null if the cell text direction is determined with automatic detection.

// Get the text direction of cell B1.
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B1:D4");
Logger.log(range.getTextDirection());

Return

TextDirection — the text direction of the top left cell in the range.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getTextDirections()

Returns the text directions for the cells in the range. Entries in the 2D array are null for cells using automatic detection.

// Get the text directions for all cells in range B5:C6
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B5:C6");
var directions = range.getTextDirections();

for (var i = 0; i < directions.length; i++) {
  for (var j = 0; j < directions[i].length; j++) {
    Logger.log(directions[i][j]);
  }
}

Return

TextDirection[][] — a two-dimensional array of text directions.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getTextRotation()

Returns the text rotation settings for the top left cell of the range.

// Log the text rotation settings for a cell.
var sheet = SpreadsheetApp.getActiveSheet();

var cell = sheet.getRange("A1");
Logger.log(cell.getTextRotation());

Return

TextRotation — The text rotation settings.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getTextRotations()

Returns the text rotation settings for the cells in the range.

var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B2:D4");

var results = range.getTextRotations();

for (var i in results) {
  for (var j in results[i]) {
    var rotation = results[i][j];
    Logger.log("Cell [%s, %s] has text rotation: %v", i, j, rotation);
  }
}

Return

TextRotation[][] — a two-dimensional array of text rotations associated with cells in the range.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getValue()

Returns the value of the top-left cell in the range. The value may be of type Number, Boolean, Date, or String depending on the value of the cell. Empty cells return an empty string.

Return

Object — the value in this cell

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getValues()

Returns the rectangular grid of values for this range.

Returns a two-dimensional array of values, indexed by row, then by column. The values may be of type Number, Boolean, Date, or String, depending on the value of the cell. Empty cells are represented by an empty string in the array. Remember that while a range index starts at 1, 1, the JavaScript array is indexed from [0][0].

// The code below gets the values for the range C2:G8
// in the active spreadsheet.  Note that this is a JavaScript array.
var values = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getValues();
Logger.log(values[0][0]);

Return

Object[][] — a two-dimensional array of values

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getVerticalAlignment()

Returns the vertical alignment (top/middle/bottom) of the cell in the top-left corner of the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getVerticalAlignment());

Return

String — the vertical alignment of the text in the cell

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getVerticalAlignments()

Returns the vertical alignments of the cells in the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getVerticalAlignments();

for (var i in results) {
  for (var j in results[i]) {
    Logger.log(results[i][j]);
  }
}

Return

String[][] — a two-dimensional array of vertical alignments of text associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getWidth()

Returns the width of the range in columns.

Return

Integer — the number of columns in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getWrap()

Returns the wrapping policy of the cell in the top-left corner of the range. true if the text wraps, false if the text does not.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.getWrap());

Return

Boolean — whether the text in this cell wraps or not

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getWrapStrategies()

Returns the text wrapping strategies for the cells in the range.

// Get the text wrapping strategies for all cells in range B5:C6
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B5:C6");
var strategies = range.getWrapStrategies();

for (var i = 0; i < strategies.length; i++) {
  for (var j = 0; j < strategies[i].length; j++) {
    Logger.log(strategies[i][j]);
  }
}

Return

WrapStrategy[][] — a two-dimensional array of text wrapping strategies

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getWrapStrategy()

Returns the text wrapping strategy for the top left cell of the range.

// Get the text wrapping strategy of cell B1.
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B1:D4");
Logger.log(range.getWrapStrategy());

Return

WrapStrategy — the text wrapping strategy of the top left cell in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getWraps()

Returns the wrapping policy of the cells in the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

var results = range.getVerticalAlignments();

for (var i in results) {
  for (var j in results[i]) {
    var isWrapped = results[i][j];
    if (isWrapped) {
       Logger.log("Cell [%s, %s] has wrapped text", i, j);
    }
  }
}

Return

Boolean[][] — a two-dimensional array of vertical alignments of text associated with cells in the range

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

insertCells(shiftDimension)

Inserts empty cells into this range. The new cells retain any formatting present in the cells previously occupying this range. Existing data in the sheet along the provided dimension is shifted away from the inserted range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:D10");
range.insertCells(SpreadsheetApp.Dimension.COLUMNS);

Parameters

NameTypeDescription
shiftDimensionDimensionThe dimension along which to shift existing data.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

isBlank()

Returns true if the range is totally blank.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("B2:D4");

Logger.log(range.isBlank());

Return

Boolean — whether the range is blank or not

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

isEndColumnBounded()

Determines whether the end of the range is bound to a particular column. For example, for the ranges A1:B10 or B:B, which are bound to columns at the end of the range, this method returns true; for the ranges 3:7 or A1:5, which are bound only to particular rows at the end of the range, this method returns false.

Return

Booleantrue if the end of the range is bound to a particular column; false if not

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

isEndRowBounded()

Determines whether the end of the range is bound to a particular row. For example, for the ranges A1:B10 or 3:7, which are bound to rows at the end of the range, this method returns true; for the ranges B:B or A1:C, which are bound only to particular columns at the end of the range, this method returns false.

Return

Booleantrue if the end of the range is bound to a particular row; false if not

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

isPartOfMerge()

Returns true if the cells in the current range overlap any merged cells.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:B3");

// True if any of the cells in A1:B3 is included in a merge.
var isPartOfMerge = range.isPartOfMerge();

Return

Booleantrue if the range overlaps any merged cells, otherwise returns false


isStartColumnBounded()

Determines whether the start of the range is bound to a particular column. For example, for the ranges A1:B10 or B:B, which are bound to columns at the start of the range, this method returns true; for the range 3:7, which is bound only to a row at the start of the range, this method returns false.

Return

Booleantrue if the start of the range is bound to a particular column; false if not

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

isStartRowBounded()

Determines whether the start of the range is bound to a particular row. For example, for the ranges A1:B10 or 3:7, which are bound to rows at the start of the range, this method returns true; for the range B:B, which is bound only to a particular column at the start of the range, this method returns false.

Return

Booleantrue if the start of the range is bound to a particular row; false if not

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

merge()

Merges the cells in the range together into a single block.

var sheet = SpreadsheetApp.getActiveSheet();

// The code below 2-dimensionally merges the cells in A1 to B3
sheet.getRange('A1:B3').merge();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

mergeAcross()

Merge the cells in the range across the columns of the range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The code below merges cells C5:E5 into one cell
var range1 = sheet.getRange("C5:E5");
range1.mergeAcross();

// The code below creates 2 horizontal cells, F5:H5 and F6:H6
var range2 = sheet.getRange("F5:H6");
range2.mergeAcross();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

mergeVertically()

Merges the cells in the range together.

var sheet = SpreadsheetApp.getActiveSheet();

// The code below vertically merges the cells in A1 to A10
sheet.getRange('A1:A10').mergeVertically();

// The code below creates 3 merged columns: B1 to B10, C1 to C10, and D1 to D10
sheet.getRange('B1:D10').mergeVertically();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

moveTo(target)

Cut and paste (both format and values) from this range to the target range.

// The code below moves the first 5 columns over to the 6th column
var sheet = SpreadsheetApp.getActiveSheet()
sheet.getRange("A1:E").moveTo(sheet.getRange("F1"));

Parameters

NameTypeDescription
targetRangeA target range to copy this range to; only the top-left cell position is relevant.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

offset(rowOffset, columnOffset)

Returns a new range that is offset from this range by the given number of rows and columns (which can be negative). The new range is the same size as the original range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("A1");

// newCell references B2
var newCell = cell.offset(1, 1);

Parameters

NameTypeDescription
rowOffsetIntegerThe number of rows down from the range's top-left cell; negative values represent rows up from the range's top-left cell.
columnOffsetIntegerThe number of columns right from the range's top-left cell; negative values represent columns left from the range's top-left cell.

Return

Range — this range, for chaining


offset(rowOffset, columnOffset, numRows)

Returns a new range that is relative to the current range, whose upper left point is offset from the current range by the given rows and columns, and with the given height in cells.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("A1");

// newCell references B2:B3
var newRange = cell.offset(1, 1, 2);

Parameters

NameTypeDescription
rowOffsetIntegerThe number of rows down from the range's top-left cell; negative values represent rows up from the range's top-left cell.
columnOffsetIntegerThe number of columns right from the range's top-left cell; negative values represent columns left from the range's top-left cell.
numRowsIntegerThe height in rows of the new range.

Return

Range — this range, for chaining


offset(rowOffset, columnOffset, numRows, numColumns)

Returns a new range that is relative to the current range, whose upper left point is offset from the current range by the given rows and columns, and with the given height and width in cells.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("A1");

// newCell references B2:C3
var newRange = cell.offset(1, 1, 2, 2);

Parameters

NameTypeDescription
rowOffsetIntegerThe number of rows down from the range's top-left cell; negative values represent rows up from the range's top-left cell.
columnOffsetIntegerThe number of columns right from the range's top-left cell; negative values represent columns left from the range's top-left cell.
numRowsIntegerThe height in rows of the new range.
numColumnsIntegerThe width in columns of the new range.

Return

Range — this range, for chaining


protect()

Creates an object that can protect the range from being edited except by users who have permission. Until the script actually changes the list of editors for the range (by calling Protection.removeEditor(emailAddress), Protection.removeEditor(user), Protection.removeEditors(emailAddresses), Protection.addEditor(emailAddress), Protection.addEditor(user), Protection.addEditors(emailAddresses), or setting a new value for Protection.setDomainEdit(editable)), the permissions mirror those of the spreadsheet itself, which effectively means that the range remains unprotected. If the range is already protected, this method creates a new protected range that overlaps the existing one. If a cell is protected by multiple protected ranges and any of them prevent a particular user from editing the cell, then that user is not permitted to edit the cell.

// Protect range A1:B10, then remove all other users from the list of editors.
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect().setDescription('Sample protected range');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

Return

Protection — an object representing the protection settings

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

randomize()

Randomizes the order of the rows in the given range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("A1:C7");

// Randomizes the range
range.randomize();

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setBackground(color)

Sets the background color of all cells in the range in CSS notation (such as '#ffffff' or 'white').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("B2:D5");
range.setBackground("red");

Parameters

NameTypeDescription
colorStringA color code in CSS notation (such as '#ffffff' or 'white'); a null value resets the color.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setBackgroundRGB(red, green, blue)

Sets the background to the given color using RGB values (integers between 0 and 255 inclusive).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");

// Sets the background to white
cell.setBackgroundRGB(255, 255, 255);

// Sets the background to red
cell.setBackgroundRGB(255, 0, 0);

Parameters

NameTypeDescription
redIntegerThe red value in RGB notation.
greenIntegerThe green value in RGB notation.
blueIntegerThe blue value in RGB notation.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setBackgrounds(color)

Sets a rectangular grid of background colors (must match dimensions of this range). The colors are in CSS notation (such as '#ffffff' or 'white').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var colors = [
  ["red", "white", "blue"],
  ["#FF0000", "#FFFFFF", "#0000FF"] // These are the hex equivalents
];

var cell = sheet.getRange("B5:D6");
cell.setBackgrounds(colors);

Parameters

NameTypeDescription
colorString[][]A two-dimensional array of colors in CSS notation (such as '#ffffff' or 'white'); null values reset the color.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setBorder(top, left, bottom, right, vertical, horizontal)

Sets the border property. Valid values are true (on), false (off) and null (no change).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
// Sets borders on the top and bottom, but leaves the left and right unchanged
cell.setBorder(true, null, true, null, false, false);

Parameters

NameTypeDescription
topBooleantrue for border, false for none, null for no change.
leftBooleantrue for border, false for none, null for no change.
bottomBooleantrue for border, false for none, null for no change.
rightBooleantrue for border, false for none, null for no change.
verticalBooleantrue for internal vertical borders, false for none, null for no change.
horizontalBooleantrue for internal horizontal borders, false for none, null for no change.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setBorder(top, left, bottom, right, vertical, horizontal, color, style)

Sets the border property with color and/or style. Valid values are true (on), false (off) and null (no change). For color, use Color in CSS notation (such as '#ffffff' or 'white')

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
// Sets borders on the top and bottom, but leaves the left and right unchanged
// Also sets the color to "red", and the border to "DASHED".
cell.setBorder(true, null, true, null, false, false, "red", SpreadsheetApp.BorderStyle.DASHED);

Parameters

NameTypeDescription
topBooleantrue for border, false for none, null for no change.
leftBooleantrue for border, false for none, null for no change.
bottomBooleantrue for border, false for none, null for no change.
rightBooleantrue for border, false for none, null for no change.
verticalBooleantrue for internal vertical borders, false for none, null for no change.
horizontalBooleantrue for internal horizontal borders, false for none, null for no change.
colorStringA color in CSS notation (such as '#ffffff' or 'white'), null for default color (black).
styleBorderStyleA style for the borders, null for default style (solid).

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setDataValidation(rule)

Sets one data validation rule for all cells in the range.

// Set the data validation rule for cell A1 to require a value from B1:B10.
var cell = SpreadsheetApp.getActive().getRange('A1');
var range = SpreadsheetApp.getActive().getRange('B1:B10');
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(range).build();
cell.setDataValidation(rule);

Parameters

NameTypeDescription
ruleDataValidationThe data validation rule to set, or null to remove data validation.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setDataValidations(rules)

Sets the data validation rules for all cells in the range. This method takes a two-dimensional array of data validations, indexed by row then by column. The array dimensions must correspond to the range dimensions.

// Set the data validation rules for Sheet1!A1:B5 to require a value from Sheet2!A1:A10.
var destinationRange = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange('A1:B5');
var sourceRange = SpreadsheetApp.getActive().getSheetByName('Sheet2').getRange('A1:A10');
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(sourceRange).build();
var rules = destinationRange.getDataValidations();
for (var i = 0; i < rules.length; i++) {
  for (var j = 0; j < rules[i].length; j++) {
    rules[i][j] = rule;
  }
}
destinationRange.setDataValidations(rules);

Parameters

NameTypeDescription
rulesDataValidation[][]A two-dimensional array of data validation rules to set; null values remove data validation.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontColor(color)

Sets the font color in CSS notation (such as '#ffffff' or 'white').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setFontColor("red");

Parameters

NameTypeDescription
colorStringThe font color in CSS notation (such as '#ffffff' or 'white'); a null value resets the color.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontColors(colors)

Sets a rectangular grid of font colors (must match dimensions of this range). The colors are in CSS notation (such as '#ffffff' or 'white').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var colors = [
  ["red", "white", "blue"],
  ["#FF0000", "#FFFFFF", "#0000FF"] // These are the hex equivalents
];

var cell = sheet.getRange("B5:D6");
cell.setFontColors(colors);

Parameters

NameTypeDescription
colorsObject[][]A two-dimensional array of colors in CSS notation (such as '#ffffff' or 'white'); null values reset the color.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontFamilies(fontFamilies)

Sets a rectangular grid of font families (must match dimensions of this range). Examples of font families are "Arial" or "Helvetica".

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var fonts = [
  ["Arial", "Helvetica", "Verdana"],
  ["Courier New", "Arial", "Helvetica]
];

var cell = sheet.getRange("B2:D3");
cell.setFontFamilies(fonts);

Parameters

NameTypeDescription
fontFamiliesObject[][]A two-dimensional array of font families; null values reset the font family.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontFamily(fontFamily)

Sets the font family, such as "Arial" or "Helvetica".

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setFontFamily("Helvetica");

Parameters

NameTypeDescription
fontFamilyStringThe font family to set; a null value resets the font family.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontLine(fontLine)

Sets the font line style of the given range ('underline', 'line-through', or 'none').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setFontLine("line-through");

Parameters

NameTypeDescription
fontLineStringThe font line style, either 'underline', 'line-through', or 'none'; a null value resets the font line style.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontLines(fontLines)

Sets a rectangular grid of line styles (must match dimensions of this range).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var fontLines = [
  ["underline", "line-through", "none"]
];

var range = sheet.getRange("B2:D2");
range.setFontLines(fontLines);

Parameters

NameTypeDescription
fontLinesObject[][]A two-dimensional array of font line styles ('underline', 'line-through', or 'none'); null values reset the font line style.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontSize(size)

Sets the font size, with the size being the point size to use.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setFontSize(20);

Parameters

NameTypeDescription
sizeIntegerA font size in point size.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontSizes(sizes)

Sets a rectangular grid of font sizes (must match dimensions of this range). The sizes are in points.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var fontSizes = [
  [16, 20, 24]
];

var range = sheet.getRange("B2:D2");
range.setFontSizes(fontSizes);

Parameters

NameTypeDescription
sizesObject[][]A two-dimensional array of sizes.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontStyle(fontStyle)

Set the font style for the given range ('italic' or 'normal').

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setFontStyle("italic");

Parameters

NameTypeDescription
fontStyleStringThe font style, either 'italic' or 'normal'; a null value resets the font style.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontStyles(fontStyles)

Sets a rectangular grid of font styles (must match dimensions of this range).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var fontStyles = [
  ["italic", "normal"]
];

var range = sheet.getRange("B2:C2");
range.setFontStyles(fontStyles);

Parameters

NameTypeDescription
fontStylesObject[][]A two-dimensional array of font styles, either 'italic' or 'normal'; null values reset the font style.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontWeight(fontWeight)

Set the font weight for the given range (normal/bold).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setFontWeight("bold");

Parameters

NameTypeDescription
fontWeightStringThe font weight, either 'bold' or 'normal'; a null value resets the font weight.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFontWeights(fontWeights)

Sets a rectangular grid of font weights (must match dimensions of this range). An example of a font weight is "bold".

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var fontStyles = [
  [ "bold", "bold", "normal" ]
];

var range = sheet.getRange("B2:D2");
range.setFontWeights(fontStyles);

Parameters

NameTypeDescription
fontWeightsObject[][]A two-dimensional array of font weights, either 'bold' or 'normal'; null values reset the font weight.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFormula(formula)

Updates the formula for this range. The given formula must be in A1 notation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B5");
cell.setFormula("=SUM(B3:B4)");

Parameters

NameTypeDescription
formulaStringA string representing the formula to set for the cell.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFormulaR1C1(formula)

Updates the formula for this range. The given formula must be in R1C1 notation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B5");
// This sets the formula to be the sum of the 3 rows above B5
cell.setFormulaR1C1("=SUM(R[-3]C[0]:R[-1]C[0])");

Parameters

NameTypeDescription
formulaStringA string formula.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFormulas(formulas)

Sets a rectangular grid of formulas (must match dimensions of this range). The given formulas must be in A1 notation. This method takes a two-dimensional array of formulas, indexed by row, then by column. The array dimensions must correspond to the range dimensions.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// This sets the formulas to be a row of sums, followed by a row of averages right below.
// The size of the two-dimensional array must match the size of the range.
var formulas = [
  ["=SUM(B2:B4)", "=SUM(C2:C4)", "=SUM(D2:D4)"],
  ["=AVERAGE(B2:B4)", "=AVERAGE(C2:C4)", "=AVERAGE(D2:D4)"]
];

var cell = sheet.getRange("B5:D6");
cell.setFormulas(formulas);

Parameters

NameTypeDescription
formulasString[][]A two-dimensional string array of formulas.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setFormulasR1C1(formulas)

Sets a rectangular grid of formulas (must match dimensions of this range). The given formulas must be in R1C1 notation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// This creates formulas for a row of sums, followed by a row of averages.
var sumOfRowsAbove = "=SUM(R[-3]C[0]:R[-1]C[0])";
var averageOfRowsAbove = "=AVERAGE(R[-4]C[0]:R[-2]C[0])";

// The size of the two-dimensional array must match the size of the range.
var formulas = [
  [sumOfRowsAbove, sumOfRowsAbove, sumOfRowsAbove],
  [averageOfRowsAbove, averageOfRowsAbove, averageOfRowsAbove]
];

var cell = sheet.getRange("B5:D6");
// This sets the formula to be the sum of the 3 rows above B5.
cell.setFormulasR1C1(formulas);

Parameters

NameTypeDescription
formulasString[][]A two-dimensional array of formulas in R1C1 format.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setHorizontalAlignment(alignment)

Set the horizontal (left to right) alignment for the given range (left/center/right).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setHorizontalAlignment("center");

Parameters

NameTypeDescription
alignmentStringThe alignment, either 'left', 'center' or 'normal'; a null value resets the alignment.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setHorizontalAlignments(alignments)

Sets a rectangular grid of horizontal alignments. see setHorizontalAlignment(alignment)

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var horizontalAlignments = [
  [ "left", "right", "center" ]
];

var range = sheet.getRange("B2:D2");
range.setHorizontalAlignments(horizontalAlignments);

Parameters

NameTypeDescription
alignmentsObject[][]A two-dimensional array of alignments, either 'left', 'center' or 'normal'; a null value resets the alignment.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

See also


setNote(note)

Sets the note to the given value.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setNote("This is a note");

Parameters

NameTypeDescription
noteStringThe note value to set for the range; a null value removes the note.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setNotes(notes)

Sets a rectangular grid of notes (must match dimensions of this range).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var notes = [
  ["it goes", "like this", "the fourth, the fifth"],
  ["the minor fall", "and the", "major lift"]
];

var cell = sheet.getRange("B2:D3");
cell.setNotes(notes)

Parameters

NameTypeDescription
notesObject[][]A two-dimensional array of notes; null values remove the note.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

See also


setNumberFormat(numberFormat)

Sets the number or date format to the given formatting string. The accepted format patterns are described in the Sheets API documentation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
// Always show 3 decimal points
cell.setNumberFormat("0.000");

Parameters

NameTypeDescription
numberFormatStringA number format string.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setNumberFormats(numberFormats)

Sets a rectangular grid of number or date formats (must match dimensions of this range). The values are format pattern strings as described in the Sheets API documentation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var formats = [
  [ "0.000", "0,000,000", "$0.00" ]
];

var range = sheet.getRange("B2:D2");
range.setNumberFormats(formats);

Parameters

NameTypeDescription
numberFormatsObject[][]A two-dimensional array of number formats.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setShowHyperlink(showHyperlink)

Sets whether or not the range should show hyperlinks.

Parameters

NameTypeDescription
showHyperlinkBooleanWhether or not to show the hyperlink.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setTextDirection(direction)

Sets the text direction for the cells in the range. If a specified direction is null, the direction is inferred and then set.

// Sets right-to-left text direction for the range.
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B5:C6");
range.setTextDirection(SpreadsheetApp.TextDirection.RIGHT_TO_LEFT);

Parameters

NameTypeDescription
directionTextDirectionThe desired text direction; if null the direction is inferred before setting.

Return

Range — this range, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setTextDirections(directions)

Sets a rectangular grid of text directions. If a specified direction is null, the direction is inferred and then set.

// Copies all of the text directions from range A1:B2 over to range C5:D6.
var sheet = SpreadsheetApp.getActiveSheet();
var range1 = sheet.getRange("A1:B2");
var range2 = sheet.getRange("C5:D6");

range2.setTextRotations(range1.getTextDirections());

Parameters

NameTypeDescription
directionsTextDirection[][]The desired text directions; if a specified direction is null it is inferred before setting.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setTextRotation(degrees)

Sets the text rotation settings for the cells in the range. The input corresponds to the angle between the standard text orientation and the desired orientation. An input of zero indicates that the text is set to the standard orientation.

For left to right text direction, positive angles are in the counterclockwise direction, whereas for right to left they are in the clockwise direction.

// Sets all cell's in range B2:D4 to have text rotated up 45 degrees.
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B2:D4");

range.setTextRotation(45);

Parameters

NameTypeDescription
degreesIntegerThe desired angle between the standard orientation and the desired orientation. For left to right text, positive angles are in the counterclockwise direction.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setTextRotation(rotation)

Sets the text rotation settings for the cells in the range.

// Sets all cell's in range B2:D4 to have the same text rotation settings as cell A1.
var sheet = SpreadsheetApp.getActiveSheet();

var rotation = sheet.getRange("A1").getTextRotation();

sheet.getRange("B2:D4").setTextRotation(rotation);

Parameters

NameTypeDescription
rotationTextRotationThe desired text rotation settings.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setTextRotations(rotations)

Sets a rectangular grid of text rotations.

// Copies all of the text rotations from range A1:B2 over to range C5:D6.
var sheet = SpreadsheetApp.getActiveSheet();
var range1 = sheet.getRange("A1:B2");
var range2 = sheet.getRange("C5:D6");

range2.setTextRotations(range1.getTextRotations());

Parameters

NameTypeDescription
rotationsTextRotation[][]The desired text rotation settings.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setValue(value)

Sets the value of the range. The value can be numeric, string, boolean or date. If it begins with '=' it is interpreted as a formula.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setValue(100);

Parameters

NameTypeDescription
valueObjectThe value for the range.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setValues(values)

Sets a rectangular grid of values (must match dimensions of this range).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var values = [
  [ "2.000", "1,000,000", "$2.99" ]
];

var range = sheet.getRange("B2:D2");
range.setValues(values);

Parameters

NameTypeDescription
valuesObject[][]A two-dimensional array of values.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setVerticalAlignment(alignment)

Set the vertical (top to bottom) alignment for the given range (top/middle/bottom).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setVerticalAlignment("middle");

Parameters

NameTypeDescription
alignmentStringThe alignment, either 'top', 'middle' or 'bottom'; a null value resets the alignment.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setVerticalAlignments(alignments)

Sets a rectangular grid of vertical alignments (must match dimensions of this range).

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var alignments = [
  [ "top", "middle", "bottom" ]
];

var range = sheet.getRange("B2:D2");
range.setVerticalAlignments(alignments);

Parameters

NameTypeDescription
alignmentsObject[][]A two-dimensional array of alignments, either 'top', 'middle' or 'bottom'; a null value resets the alignment.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

See also


setVerticalText(isVertical)

Sets whether or not to stack the text for the cells in the range. If the text is stacked vertically, the degree text rotation setting is ignored.

// Sets all cell's in range B2:D4 to have vertically stacked text.
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B2:D4");

range.setVerticalText(true);

Parameters

NameTypeDescription
isVerticalBooleanWhether or not to stack the text.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setWrap(isWrapEnabled)

Set the cell wrap of the given range.

Cells with wrap enabled (the default) resize to display their full content. Cells with wrap disabled display as much as possible in the cell without resizing or running to multiple lines.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
cell.setWrap(true);

Parameters

NameTypeDescription
isWrapEnabledBooleanWhether to wrap text or not.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setWrapStrategies(strategies)

Sets a rectangular grid of wrap strategies.

// Copies all of the wrap strategies from range A1:B2 over to range C5:D6.
var sheet = SpreadsheetApp.getActiveSheet();
var range1 = sheet.getRange("A1:B2");
var range2 = sheet.getRange("C5:D6");

range2.setWrapStrategies(range1.getWrapStrategies());

Parameters

NameTypeDescription
strategiesWrapStrategy[][]The desired wrapping strategies.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setWrapStrategy(strategy)

Sets the text wrapping strategy for the cells in the range.

// Sets all cells in range B2:D4 to use the clip wrap strategy.
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B2:D4");

range.setWrapStrategy(SpreadsheetApp.WrapStrategy.CLIP);

Parameters

NameTypeDescription
strategyWrapStrategyThe desired wrapping strategy.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setWraps(isWrapEnabled)

Sets a rectangular grid of word wrap policies (must match dimensions of this range). Cells with wrap enabled (the default) resize to display their full content. Cells with wrap disabled display as much as possible in the cell without resizing or running to multiple lines.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
var wraps = [
  [ true, true, false ]
];

var range = sheet.getRange("B2:D2");
range.setWraps(wraps);

Parameters

NameTypeDescription
isWrapEnabledObject[][]A two-dimensional array of wrap variables that determine whether to wrap text in a cell or not.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

See also


shiftColumnGroupDepth(delta)

Changes the column grouping depth of the range by the specified amount.

This has the effect of creating, modifying, or deleting groups that intersect with the range. For positive deltas, groups are created and/or modified; for negative deltas, groups are destroyed and/or modified.

This has no effect when decreasing the group depth below zero or above eight.

If the column group control position is BEFORE, this throws an error when attempting to shift the depth of the first row.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = sheet.getActiveRange();

// The column grouping depth is increased by 1.
range.shiftColumnGroupDepth(1);

// The column grouping depth is decreased by 1.
range.shiftColumnGroupDepth(-1);

Parameters

NameTypeDescription
deltaIntegerThe amount by which to change the column group depth of this range.

Return

Range — this range, for chaining

Throws

Error — when attempting to shift the depth of the first column when the control position is GroupControlTogglePosition.BEFORE

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

shiftRowGroupDepth(delta)

Changes the row grouping depth of the range by the specified amount.

This has the effect of creating, modifying, or deleting groups that intersect with the range. For positive deltas, groups are created and/or modified; for negative deltas, groups are destroyed and/or modified.

This has no effect when decreasing the group depth below zero or above eight.

If the row group control position is BEFORE, this throws an error when attempting to shift the depth of the first row.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = sheet.getActiveRange();

// The row grouping depth is increased by 1.
range.shiftRowGroupDepth(1);

// The row grouping depth is decreased by 1.
range.shiftRowGroupDepth(-1);

Parameters

NameTypeDescription
deltaIntegerThe amount by which to change the row group depth of this range.

Return

Range — this range, for chaining

Throws

Error — when attempting to shift the depth of the first row when the control position is GroupControlTogglePosition.BEFORE

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

sort(sortSpecObj)

Sorts the cells in the given range, by column and order specified.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("A1:C7");

// Sorts by the values in the first column (A)
range.sort(1);

// Sorts by the values in the second column (B)
range.sort(2);

// Sorts descending by column B
range.sort({column: 2, ascending: false});

// Sorts descending by column B, then ascending by column A
// Note the use of an array
range.sort([{column: 2, ascending: false}, {column: 1, ascending: true}]);

// For rows that are sorted in ascending order, the "ascending" parameter is
// optional, and just an integer with the column can be used instead. Note that
// in general, keeping the sort specification consistent results in more readable
// code. We could have expressed the earlier sort as:
range.sort([{column: 2, ascending: false}, 1]);

// Alternatively, if we wanted all columns to be in ascending order, we would use
// the following (this would make column 2 ascending)
range.sort([2, 1]);
// ... which is equivalent to
range.sort([{column: 2, ascending: true}, {column: 1, ascending: true}]);

Parameters

NameTypeDescription
sortSpecObjObjectThe column(s) to sort by.

Return

Range — this range, for chaining

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

splitTextToColumns()

Splits a column of text into multiple columns based on an auto-detected delimiter.

// A1:A3 has the following values:
//           A                  B                 C
// 1 |one,one,one      |                 |                 |
// 2 |two,two,two      |                 |                 |
// 3 |three,three,three|                 |                 |

var range = SpreadsheetApp.getActiveSheet().getRange("A1:A3");
range.splitTextToColumns();

// Result after spliting the text to columns:
//           A                  B                 C
// 1 |one              |one              |one              |
// 2 |two              |two              |two              |
// 3 |three            |three            |three            |

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

splitTextToColumns(delimiter)

Splits a column of text into multiple columns using the specified string as a custom delimiter.

// A1:A3 has the following values:
//           A                  B                 C
// 1 |one#one#one      |                 |                 |
// 2 |two#two#two      |                 |                 |
// 3 |three#three#three|                 |                 |

var range = SpreadsheetApp.getActiveSheet().getRange("A1:A3");
range.splitTextToColumns('#');

// Result after spliting the text to columns:
//           A                  B                 C
// 1 |one              |one              |one              |
// 2 |two              |two              |two              |
// 3 |three            |three            |three            |

Parameters

NameTypeDescription
delimiterStringThe custom delimiter to split on.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

splitTextToColumns(delimiter)

Splits a column of text into multiple columns based on the specified delimiter.

// A1:A3 has the following values:
//           A                  B                 C
// 1 |one;one;one      |                 |                 |
// 2 |two;two;two      |                 |                 |
// 3 |three;three;three|                 |                 |

var range = SpreadsheetApp.getActiveSheet().getRange("A1:A3");
range.splitTextToColumns(SpreadsheetApp.TextToColumnsDelimiter.SEMICOLON);

// Result after spliting the text to columns:
//           A                  B                 C
// 1 |one              |one              |one              |
// 2 |two              |two              |two              |
// 3 |three            |three            |three            |

Parameters

NameTypeDescription
delimiterTextToColumnsDelimiterThe preset delimiter to split on.

Authorization

Scripts that use this method require authorization with one or more of the following scopes:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

フィードバックを送信...

ご不明な点がありましたら、Google のサポートページをご覧ください。