GASで選択中のセルの背景色をすべて別の色に置換する方法

Googleスプレッドシートは背景色を検索できない

特定の背景色をすべて別の色に変更したい場合はExcelであれば背景色を検索して置換できるが、Googleスプレッドシートは背景色の検索機能がないのでできない。

そのため、同様のことを行う場合はGAS (Google Apps Script)で機能を追加する必要がある。

GASで選択中のセルの背景色を置換

今回はGASで選択中のセルの背景色をすべて別の色に置換するコードは以下のようになる。

function onOpen() {
  const ui = SpreadsheetApp.getUi()
  const menu = ui.createMenu('GAS')
  menu.addItem('セルの背景色を現在指定している背景色から変更', 'replaceCellColor')
  menu.addToUi()
}

function showPrompt(backgroundColor) {
  const ui = SpreadsheetApp.getUi()
  const title = '背景色を入力してください'
  const prompt = `${backgroundColor} から変更する背景色を入力してください。\n例) #ffff00 or yellow`
  return ui.prompt(title, prompt, ui.ButtonSet.OK_CANCEL).getResponseText()
}

function replaceCellColor() {
  const sheet = SpreadsheetApp.getActiveSheet()
  const selection = sheet.getSelection()
  const currentCell = selection.getCurrentCell()
  const currentCellBackground = currentCell.getBackground()
  const newBackgroundColor = showPrompt(currentCellBackground)
  const range = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn())
  for (let row = 1; row <= range.getNumRows(); row++) {
    for (let col = 1; col <= range.getNumColumns(); col++) {
      const cell = range.getCell(row, col);
      const cellBackground = cell.getBackground()
      if (cellBackground === currentCellBackground) {
        cell.setBackground(newBackgroundColor)
      }
    }
  }
}

解説するとreplaceCellColor()という関数を作成して、まずcurrentCell.getBackground()で現在選択しているセルの背景色を取得する。

次に別途showPrompt()という背景色を入力するダイアログを表示させる関数を作成し、現在の背景色から変更したい背景色を16進数またはカラーコードを入力してOKを押して返すようにします。

あとはシート内の背景色を現在選択中のものから指定した背景色にforでループさせて置換するだけです。

利用しやすいようonOpen()でメニューに「GAS => セルの背景色を現在指定している背景色から変更」を追加して実行しやすいようにしています。

何も入力せずにOKを押した場合、setBackgroundが空指定になるため背景色はなしになります。

応用すればgetValue使用して特定の文字列だけ背景色を変更するなどの処理も行えるようになります。

GASで選択中のセルの背景色をすべて別の色に置換するサンプル