Class SpreadsheetApp

試算表應用程式

存取及建立 Google 試算表檔案。這個類別是 Spreadsheet 服務的父項類別。

屬性

屬性類型說明
AutoFillSeriesAutoFillSeries用於計算自動填入值的數列類型列舉。
BandingThemeBandingTheme列舉可能的樂團主題。
BooleanCriteriaBooleanCriteria條件式格式設定布林值條件的列舉。
BorderStyleBorderStyle列舉可為 Range 設定邊框的有效樣式。
ColorTypeColorType列舉可能的顏色類型。
CopyPasteTypeCopyPasteType列舉可能的貼上類型。
DataExecutionErrorCodeDataExecutionErrorCode可能資料執行錯誤代碼的列舉。
DataExecutionStateDataExecutionState列舉可能的資料執行狀態。
DataSourceParameterTypeDataSourceParameterType列舉可能的資料來源參數類型。
DataSourceRefreshScopeDataSourceRefreshScope列舉可能的資料來源重新整理範圍。
DataSourceTypeDataSourceType列舉可能的資料來源類型。
DataValidationCriteriaDataValidationCriteria列舉,代表可對範圍設定的資料驗證條件。
DateTimeGroupingRuleTypeDateTimeGroupingRuleType日期時間分組規則的列舉。
DeveloperMetadataLocationTypeDeveloperMetadataLocationType可能出現的開發人員中繼資料位置類型列舉。
DeveloperMetadataVisibilityDeveloperMetadataVisibility列舉可能的開發人員中繼資料瀏覽權限。
DimensionDimension試算表可能維度的列舉。
DirectionDirection使用方向鍵在試算表中移動時,可能出現的方向列舉。
FrequencyTypeFrequencyType列舉可能的頻率類型。
GroupControlTogglePositionGroupControlTogglePosition群組控制項切換按鈕可處於的位置列舉。
InterpolationTypeInterpolationType條件式格式漸層插補類型列舉。
PivotTableSummarizeFunctionPivotTableSummarizeFunction可用於匯總資料透視表值的函式列舉。
PivotValueDisplayTypePivotValueDisplayType列舉樞紐值可能顯示的方式。
ProtectionTypeProtectionType列舉,代表可防止編輯的試算表部分。
RecalculationIntervalRecalculationInterval列舉可用於試算表重新計算的可能間隔。
RelativeDateRelativeDate列舉相對日期選項,用於計算日期型 BooleanCriteria 中使用的值。
SheetTypeSheetType試算表可包含的不同類型工作表列舉。
SortOrderSortOrder排序順序的列舉。
TextDirectionTextDirection有效文字方向的列舉。
TextToColumnsDelimiterTextToColumnsDelimiter將文字分隔成不同欄的預設分隔符號列舉。
ThemeColorTypeThemeColorType列舉可能的主題顏色類型。
ValueTypeValueType列舉 Range.getValue()Range.getValues() 從 Spreadsheet 服務的 Range 類別傳回的值類型。除了 NumberBooleanDateString 之外,列舉值還包括下列項目。
WrapStrategyWrapStrategy用於包裝儲存格的策略列舉。

方法

方法傳回類型簡短說明
create(name)Spreadsheet建立新試算表並提供名稱。
create(name, rows, columns)Spreadsheet建立新試算表,並指定名稱和列數/欄數。
enableAllDataSourcesExecution()void為所有類型的資料來源啟用資料執行程序。
enableBigQueryExecution()void為 BigQuery 資料來源啟用資料執行作業。
enableLookerExecution()void為 Looker 資料來源啟用資料執行程序。
flush()void套用所有待處理的試算表變更。
getActive()Spreadsheet傳回目前有效的試算表,如果沒有則傳回 null
getActiveRange()Range傳回有效工作表中的所選範圍,如果沒有有效範圍,則傳回「null」。
getActiveRangeList()RangeList|null傳回目前工作表中的有效範圍清單,或如果未選取任何範圍,則傳回「null」。
getActiveSheet()Sheet取得試算表中的現用工作表。
getActiveSpreadsheet()Spreadsheet傳回目前有效的試算表,如果沒有則傳回 null
getCurrentCell()Range|null傳回目前 (醒目顯示) 儲存格,該儲存格是在有效工作表或 null 的有效範圍中選取,如果沒有目前儲存格,則傳回 null
getSelection()Selection傳回試算表中的目前 Selection
getUi()Ui傳回試算表使用者介面環境的執行個體,讓指令碼新增選單、對話方塊和側欄等功能。
newCellImage()CellImageBuilder建立 CellImage 的建構工具。
newColor()ColorBuilder建立 Color 的建構工具。
newConditionalFormatRule()ConditionalFormatRuleBuilder建立條件式格式設定規則的建構工具。
newDataSourceSpec()DataSourceSpecBuilder建立 DataSourceSpec 的建構工具。
newDataValidation()DataValidationBuilder為資料驗證規則建立建構工具。
newFilterCriteria()FilterCriteriaBuilder建立 FilterCriteria 的建構工具。
newRichTextValue()RichTextValueBuilder建立 RTF 格式值的建構工具。
newTextStyle()TextStyleBuilder建立文字樣式的建構工具。
open(file)Spreadsheet開啟與指定 File 物件對應的試算表。
openById(id)Spreadsheet開啟具有指定 ID 的試算表。
openByUrl(url)Spreadsheet開啟指定網址的試算表。
setActiveRange(range)Range將指定範圍設為 active range,並將範圍內左上方的儲存格設為 current cell
setActiveRangeList(rangeList)RangeList將指定範圍清單設為 active ranges
setActiveSheet(sheet)Sheet在試算表中設定有效的工作表。
setActiveSheet(sheet, restoreSelection)Sheet設定試算表中的作用中工作表,並可選擇還原該工作表中的最新選取範圍。
setActiveSpreadsheet(newActiveSpreadsheet)void設定有效試算表。
setCurrentCell(cell)Range將指定儲存格設為 current cell

內容詳盡的說明文件

create(name)

建立新試算表並提供名稱。

// The code below creates a new spreadsheet "Finances" and logs the URL for it
const ssNew = SpreadsheetApp.create('Finances');
Logger.log(ssNew.getUrl());

參數

名稱類型說明
nameString試算表的名稱。

回攻員

Spreadsheet:新試算表

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

create(name, rows, columns)

建立新試算表,並指定名稱和資料列/欄數。

// The code below creates a new spreadsheet "Finances" with 50 rows and 5
// columns and logs the URL for it
const ssNew = SpreadsheetApp.create('Finances', 50, 5);
Logger.log(ssNew.getUrl());

參數

名稱類型說明
nameString試算表的名稱。
rowsInteger試算表的列數。
columnsInteger試算表的欄數。

回攻員

Spreadsheet:新試算表

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

enableAllDataSourcesExecution()

為所有類型的資料來源啟用資料執行程序。

如果資料來源類型未開啟,資料執行作業就會擲回例外狀況。使用這個方法,為所有資料來源類型啟用資料執行程序。

// Turns data execution on for all types of data sources.
SpreadsheetApp.enableAllDataSourcesExecution();

// Opens the spreadsheet file by its ID. If you created your script from a
// Google Sheets file, use SpreadsheetApp.getActiveSpreadsheet().
// TODO(developer): Replace the ID with your own.
const ss = SpreadsheetApp.openById('abc123456');

// Gets the first data source sheet in the spreadsheet and refreshes the data.
ss.getDataSourceSheets()[0].refreshData();

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

  • https://www.googleapis.com/auth/bigquery.readonly

enableBigQueryExecution()

為 BigQuery 資料來源開啟資料執行。

如果未開啟,BigQuery 資料來源的資料執行作業會擲回例外狀況。

// Turns data execution on for BigQuery data sources.
SpreadsheetApp.enableBigQueryExecution();

// Opens the spreadsheet file by its ID. If you created your script from a
// Google Sheets file, use SpreadsheetApp.getActiveSpreadsheet().
// TODO(developer): Replace the ID with your own.
const ss = SpreadsheetApp.openById('abc123456');

// Gets the first data source sheet in the spreadsheet and refreshes the
// BigQuery data.
ss.getDataSourceSheets()[0].refreshData();

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

  • https://www.googleapis.com/auth/bigquery.readonly

enableLookerExecution()

為 Looker 資料來源啟用資料執行程序。

如果未開啟,Looker 資料來源的資料執行作業會擲回例外狀況。

// Turns data execution on for Looker data sources.
SpreadsheetApp.enableLookerExecution();

// Opens the spreadsheet file by its ID. If you created your script from a
// Google Sheets file, use SpreadsheetApp.getActiveSpreadsheet().
// TODO(developer): Replace the ID with your own.
const ss = SpreadsheetApp.openById('abc123456');

// Gets the first data source sheet in the spreadsheet and refreshes the
// associated Looker data.
ss.getDataSourceSheets()[0].refreshData();

flush()

套用所有待處理的試算表變更。

為提升效能,系統有時會將試算表作業捆綁在一起,例如多次呼叫 Range.getValue() 時。不過,有時您可能希望確保所有待處理的變更都會立即完成,例如在指令碼執行時向使用者顯示資料。

// The code below changes the background color of cells A1 and B1 twenty times.
// You should be able to see the updates live in the spreadsheet. If flush() is
// not called, the updates may be applied live or may all be applied at once
// when the script completes.
function colors() {
  const sheet = SpreadsheetApp.getActiveSheet();
  for (let i = 0; i < 20; i++) {
    if (i % 2 === 0) {
      sheet.getRange('A1').setBackground('green');
      sheet.getRange('B1').setBackground('red');
    } else {
      sheet.getRange('A1').setBackground('red');
      sheet.getRange('B1').setBackground('green');
    }
    SpreadsheetApp.flush();
  }
}

getActive()

傳回目前有效的試算表,如果沒有,則傳回 null

在試算表環境中執行的函式可以呼叫這個函式,取得對應的試算表物件參照。

// The code below logs the URL for the active spreadsheet.
Logger.log(SpreadsheetApp.getActive().getUrl());

回攻員

Spreadsheet:有效試算表物件

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

getActiveRange()

傳回有效工作表中的所選範圍,如果沒有有效範圍,則傳回「null」。如果選取多個範圍,這個方法只會傳回最後選取的範圍。

這通常是指使用者在有效工作表中選取的範圍,但在自訂函式中,則是指正在重新計算的儲存格。

// The code below logs the background color for the active range.
const colorObject = SpreadsheetApp.getActiveRange().getBackgroundObject();
// Assume the color has ColorType.RGB.
Logger.log(colorObject.asRgbColor().asHexString());

回攻員

Range:有效範圍。

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

getActiveRangeList()

傳回目前工作表中的有效範圍清單,或如果未選取任何範圍,則傳回 null。含有目前醒目顯示儲存格的有效範圍會放在清單的最後。

如果只選取單一範圍,這項操作的行為與 getActiveRange() 呼叫相同。

// Returns the list of active ranges.
const rangeList = SpreadsheetApp.getActiveRangeList();

回攻員

RangeList|null - 有效範圍清單

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

getActiveSheet()

取得試算表中的現用工作表。

試算表中的現用工作表是指試算表 UI 中顯示的工作表。

// The code below logs the name of the active sheet.
Logger.log(SpreadsheetApp.getActiveSheet().getName());

回攻員

Sheet:有效 Sheet 物件

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

getActiveSpreadsheet()

傳回目前有效的試算表,如果沒有,則傳回 null

在試算表環境中執行的函式可以呼叫這個函式,取得對應 Spreadsheet 物件的參照。

// The code below logs the URL for the active spreadsheet.
Logger.log(SpreadsheetApp.getActiveSpreadsheet().getUrl());

回攻員

Spreadsheet:有效試算表物件

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

getCurrentCell()

傳回目前 (醒目顯示) 儲存格,該儲存格是在有效工作表的有效範圍中選取,如果沒有目前儲存格,則傳回 null

// Returns the current highlighted cell in the one of the active ranges.
const currentCell = SpreadsheetApp.getCurrentCell();

回攻員

Range|null:目前的儲存格

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

getSelection()

傳回試算表中的目前 Selection

const selection = SpreadsheetApp.getSelection();
const currentCell = selection.getCurrentCell();

回攻員

Selection:目前選取的項目

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

getUi()

傳回試算表使用者介面環境的執行個體,讓指令碼新增選單、對話方塊和側欄等功能。指令碼只能與目前開啟試算表的執行個體互動,且指令碼必須繫結至試算表。詳情請參閱選單對話方塊與側欄指南。

// Add a custom menu to the active spreadsheet, including a separator and a
// sub-menu.
function onOpen(e) {
  SpreadsheetApp.getUi()
      .createMenu('My Menu')
      .addItem('My menu item', 'myFunction')
      .addSeparator()
      .addSubMenu(
          SpreadsheetApp.getUi()
              .createMenu('My sub-menu')
              .addItem('One sub-menu item', 'mySecondFunction')
              .addItem('Another sub-menu item', 'myThirdFunction'),
          )
      .addToUi();
}

回攻員

Ui:這個試算表使用者介面環境的執行個體


newCellImage()

建立 CellImage 的建構工具。

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets cell A1 on Sheet1.
const range = sheet.getRange('A1');

// Builds an image using a source URL.
const cellImage =
    SpreadsheetApp.newCellImage()
        .setSourceUrl(
            'https://www.gstatic.com/images/branding/productlogos/apps_script/v10/web-64dp/logo_apps_script_color_1x_web_64dp.png',
            )
        .build();

// Sets the image in cell A1.
range.setValue(cellImage);

回攻員

CellImageBuilder:新的建構工具。


newColor()

建立 Color 的建構工具。

const rgbColor = SpreadsheetApp.newColor().setRgbColor('#FF0000').build();

回攻員

ColorBuilder:新的建構工具。


newConditionalFormatRule()

建立條件式格式設定規則的建構工具。

// Adds a conditional format rule to a sheet that causes all cells in range
// A1:B3 to turn red if they contain a number between 1 and 10.
const sheet = SpreadsheetApp.getActive().getActiveSheet();
const range = sheet.getRange('A1:B3');
const rule = SpreadsheetApp.newConditionalFormatRule()
                 .whenNumberBetween(1, 10)
                 .setBackground('#FF0000')
                 .setRanges([range])
                 .build();
const rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);

回攻員

ConditionalFormatRuleBuilder:新的建構工具。


newDataSourceSpec()

建立 DataSourceSpec 的建構工具。

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Enables BigQuery.
SpreadsheetApp.enableBigQueryExecution();

// Builds a data source specification.
// TODO (developer): Update the project ID to your own Google Cloud project ID.
const dataSourceSpec = SpreadsheetApp.newDataSourceSpec()
                           .asBigQuery()
                           .setProjectId('project-id-1')
                           .setTableProjectId('bigquery-public-data')
                           .setDatasetId('ncaa_basketball')
                           .setTableId('mbb_historical_teams_games')
                           .build();

// Adds the data source and its data to the spreadsheet.
ss.insertDataSourceSheet(dataSourceSpec);

回攻員

DataSourceSpecBuilder:新的建構工具。


newDataValidation()

為資料驗證規則建立建構工具。

const cell = SpreadsheetApp.getActive().getRange('A1');
const rule = SpreadsheetApp.newDataValidation()
                 .requireNumberBetween(1, 100)
                 .setAllowInvalid(false)
                 .setHelpText('Number must be between 1 and 100.')
                 .build();
cell.setDataValidation(rule);

回攻員

DataValidationBuilder:新的建構工具。


newFilterCriteria()

建立 FilterCriteria 的建構工具。

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Sets the range to A1:D20.
const range = sheet.getRange('A1:D20');

// Creates a filter and applies it to the specified range.
range.createFilter();

// Gets the current filter for the range and creates filter criteria that only
// shows cells that aren't empty.
const filter = range.getFilter();
const criteria = SpreadsheetApp.newFilterCriteria().whenCellNotEmpty().build();

// Sets the criteria to  column C.
filter.setColumnFilterCriteria(3, criteria);

回攻員

FilterCriteriaBuilder:新版建構工具


newRichTextValue()

建立 RTF 格式值的建構工具。

// Sets cell A1 to have the text "Hello world", with "Hello" bolded.
const cell = SpreadsheetApp.getActive().getRange('A1');
const bold = SpreadsheetApp.newTextStyle().setBold(true).build();
const value = SpreadsheetApp.newRichTextValue()
                  .setText('Hello world')
                  .setTextStyle(0, 5, bold)
                  .build();
cell.setRichTextValue(value);

回攻員

RichTextValueBuilder:新的建構工具。


newTextStyle()

為文字樣式建立建構工具。

// Sets range A1:B3 to have red, size 22, bolded, underlined text.
const range = SpreadsheetApp.getActive().getRange('A1:B3');
const style = SpreadsheetApp.newTextStyle()
                  .setForegroundColor('red')
                  .setFontSize(22)
                  .setBold(true)
                  .setUnderline(true)
                  .build();
range.setTextStyle(style);

回攻員

TextStyleBuilder:新的建構工具。


open(file)

開啟與指定 File 物件對應的試算表。

// Get any starred spreadsheets from Google Drive, then open the spreadsheets
// and log the name of the first sheet within each spreadsheet.
const files = DriveApp.searchFiles(
    `starred = true and mimeType = "${MimeType.GOOGLE_SHEETS}"`,
);
while (files.hasNext()) {
  const spreadsheet = SpreadsheetApp.open(files.next());
  const sheet = spreadsheet.getSheets()[0];
  Logger.log(sheet.getName());
}

參數

名稱類型說明
fileFile要開啟的檔案。

回攻員

Spreadsheet - 試算表

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

openById(id)

開啟具有指定 ID 的試算表。試算表 ID 可從網址中擷取。舉例來說,網址 https://docs.google.com/spreadsheets/d/abc1234567/edit#gid=0 中的試算表 ID 為「abc1234567」。

// The code below opens a spreadsheet using its ID and logs the name for it.
// Note that the spreadsheet is NOT physically opened on the client side.
// It is opened on the server only (for modification by the script).
const ss = SpreadsheetApp.openById('abc1234567');
Logger.log(ss.getName());

參數

名稱類型說明
idString試算表的專屬 ID。

回攻員

Spreadsheet - 具有指定 ID 的試算表物件

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

openByUrl(url)

開啟指定網址的試算表。如果網址不存在,或使用者沒有存取權,就會擲回指令碼例外狀況。

// Opens a spreadsheet by its URL and logs its name.
// Note that the spreadsheet doesn't physically open on the client side.
// It opens on the server only (for modification by the script).
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc1234567/edit',
);
console.log(ss.getName());

參數

名稱類型說明
urlString試算表的網址。

回攻員

Spreadsheet:具有指定網址的試算表物件。

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

setActiveRange(range)

將指定範圍設為 active range,並將範圍內左上方的儲存格設為 current cell

試算表 UI 會顯示包含所選範圍的工作表,並選取所選範圍中定義的儲存格。

// The code below sets range C1:D4 in the first sheet as the active range.
const range =
    SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange('C1:D4');
SpreadsheetApp.setActiveRange(range);

const selection = SpreadsheetApp.getSelection();
// Current cell: C1
const currentCell = selection.getCurrentCell();
// Active Range: C1:D4
const activeRange = selection.getActiveRange();

參數

名稱類型說明
rangeRange要設為有效範圍的範圍。

回攻員

Range:新的有效範圍


setActiveRangeList(rangeList)

將指定範圍清單設為 active ranges。清單中的最後一個範圍會設為 active range

// The code below sets ranges [D4, B2:C4] in the active sheet as the active
// ranges.
const rangeList = SpreadsheetApp.getActiveSheet().getRanges(['D4', 'B2:C4']);
SpreadsheetApp.setActiveRangeList(rangeList);

const selection = SpreadsheetApp.getSelection();
// Current cell: B2
const currentCell = selection.getCurrentCell();
// Active range: B2:C4
const activeRange = selection.getActiveRange();
// Active range list: [D4, B2:C4]
const activeRangeList = selection.getActiveRangeList();

參數

名稱類型說明
rangeListRangeList可選取的範圍清單。

回攻員

RangeList:新選取的範圍清單

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

setActiveSheet(sheet)

在試算表中設定有效的工作表。Google 試算表 UI 會顯示所選工作表,除非該工作表屬於其他試算表。

// The code below makes the 2nd sheet active in the active spreadsheet.
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[1]);

參數

名稱類型說明
sheetSheet新的現用工作表。

回攻員

Sheet:已成為新有效工作表的工作表


setActiveSheet(sheet, restoreSelection)

設定試算表中的作用中工作表,並可選擇還原該工作表中的最新選取項目。Google 試算表使用者介面會顯示所選工作表,除非該工作表屬於其他試算表。

const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const firstSheet = spreadsheet.getSheets()[0];
const secondSheet = spreadsheet.getSheets()[1];
// Set the first sheet as the active sheet and select the range D4:F4.
spreadsheet.setActiveSheet(firstSheet).getRange('D4:F4').activate();

// Switch to the second sheet to do some work.
spreadsheet.setActiveSheet(secondSheet);
// Switch back to first sheet, and restore its selection.
spreadsheet.setActiveSheet(firstSheet, true);

// The selection of first sheet is restored, and it logs D4:F4
const range = spreadsheet.getActiveSheet().getSelection().getActiveRange();
Logger.log(range.getA1Notation());

參數

名稱類型說明
sheetSheet新的現用工作表。
restoreSelectionBoolean如果是 true,系統會在新工作表啟用時,再次選取您最近選取的新工作表;如果是 false,系統會啟用新工作表,但不會變更目前選取項目。

回攻員

Sheet:新的使用中工作表

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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

setActiveSpreadsheet(newActiveSpreadsheet)

設定有效試算表。

// The code below makes the spreadsheet with key "1234567890" the active
// spreadsheet
const ss = SpreadsheetApp.openById('1234567890');
SpreadsheetApp.setActiveSpreadsheet(ss);

參數

名稱類型說明
newActiveSpreadsheetSpreadsheet要設為使用中試算表的試算表。

setCurrentCell(cell)

將指定儲存格設為 current cell

如果指定儲存格位於已選取的範圍中,該範圍就會成為有效範圍,且該儲存格會成為目前儲存格。

如果指定儲存格不在任何選取範圍內,系統會移除現有選取範圍,並將該儲存格設為目前儲存格和有效範圍。

注意:指定的 Range 必須由一個儲存格組成,否則這個方法會擲回例外狀況。

// The code below sets the cell B5 in the first sheet as the current cell.
const cell =
    SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange('B5');
SpreadsheetApp.setCurrentCell(cell);

const selection = SpreadsheetApp.getSelection();
// Current cell: B5
const currentCell = selection.getCurrentCell();

參數

名稱類型說明
cellRange要設為目前儲存格的儲存格。

回攻員

Range:新設定的目前儲存格

授權

使用這個方法的指令碼需要一或多個下列範圍的授權:

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