Apps Scriptリファレンス: Apps Script Reference |障害・課題追跡: IssueTracker |Google Workspace: Status Dashboard - Summary

2024年6月9日日曜日

Apps Scriptでスプレッドシートのセルを結合して上揃えにしたい - Merge cells and align top in Spreadsheet using Apps Script


スプレッドシートのセルを結合して垂直方向の配置を設定するコードを試しました。
I tried Apps Script to merge cells and set the vertical alignment in a spreadsheet.


今回の例では、
In this example,

3列目の4行目と5行目のセルを結合します。
I will merge the cells in the 3rd column, 4th and 5th rows.

垂直方向の配置は「上」に設定します。
The vertical alignment will be set to "top."

結合したセルにvalueという値を入力します。
The merged cell will be filled with the value "value."



Apps Script


Code.gs
function mergeCellsInColumnU() {
const value = "value";
const sheet = SpreadsheetApp.getActiveSheet();
const startRow = 4;
const startCol = 3;
const numRows = 2;
const numCols = 1;
const range = sheet.getRange(startRow, startCol, numRows, numCols);
range.merge().setVerticalAlignment("top").setValue(value);
}


Tips

選択範囲で行単位、列単位で結合するメソッドもあったので試してみました。
I also tried using the methods that allow merging cells by row or column within a selected range.


mergeAcross()
function mergeCellsInColumnU() {
const value = "value";
const sheet = SpreadsheetApp.getActiveSheet();
const startRow = 4;
const startCol = 3;
const numRows = 2;
const numCols = 3;
const range = sheet.getRange(startRow, startCol, numRows, numCols);
range.mergeAcross().setVerticalAlignment("top").setValue(value);
}



mergeVertically()
function mergeCellsInColumnU() {
const value = "value";
const sheet = SpreadsheetApp.getActiveSheet();
const startRow = 4;
const startCol = 3;
const numRows = 2;
const numCols = 3;
const range = sheet.getRange(startRow, startCol, numRows, numCols);
range.mergeVertically().setVerticalAlignment("top").setValue(value);
}


Reference

Class Range > merge()

Class Range > mergeAcross()

Class Range > mergeVertically()

Latest post

Googleドキュメントに見出しを追加したい

今回の例では、ドキュメントの末尾に「見出しD」 を追加します。 見出しA, B, C, Dのスタイルは、見出し3 ( HEADING3 ) に設定しています。  下記Code.gsの  GOOGLE_DOCUMENT_URL を設定して  addHeadingToEnd()  を...