GASでスプレッドシートの範囲内にある数式を一括取得・活用する方法

Googleスプレッドシートを使ってると、数式を一括で取得したくなることがあるばい。そんなときに役立つのがgetFormulas()メソッドさ!この記事では、基本的な使い方から応用テクまで分かりやすく解説するばい。

スポンサーリンク

getFormulas()とは?

getFormulas()はGoogle Apps Script(GAS)でスプレッドシートの範囲内にある数式を取得できるメソッドさ。対象のセルに数式があればその内容を、なければ空文字('')を返すばい。

使い方の基本

例えば、A1:C3の範囲にある数式を取得するには、こんな感じのコードを書くばい。

function getFormulasExample() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const range = sheet.getRange("A1:C3");
  const formulas = range.getFormulas();
  
  formulas.forEach((row, rowIndex) => {
    row.forEach((formula, colIndex) => {
      if (formula) {
        Logger.log(`Cell ${range.getCell(rowIndex+1, colIndex+1).getA1Notation()}: ${formula}`);
      }
    });
  });
}

getFormulasR1C1()との違い

数式をR1C1形式(相対参照)で取得するには、getFormulasR1C1()を使うばい。

const formulasR1C1 = sheet.getRange("A1:C3").getFormulasR1C1();
Logger.log(formulasR1C1);

この方法なら=R[1]Cみたいに参照が相対的になり、大規模データを扱うときに便利さ。

実践的な活用方法

スプレッドシートの数式監査

スプレッドシートの数式を一覧でチェックするシステムを作るばい。

function auditSpreadsheetFormulas() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const auditReport = [];
  
  ss.getSheets().forEach(sheet => {
    const range = sheet.getDataRange();
    const formulas = range.getFormulas();
    
    formulas.forEach((row, i) => {
      row.forEach((formula, j) => {
        if (formula) {
          auditReport.push({
            sheet: sheet.getName(),
            cell: sheet.getRange(i+1, j+1).getA1Notation(),
            formula: formula
          });
        }
      });
    });
  });
  
  Logger.log(auditReport);
}

動的な数式生成

テンプレートシートの数式を取得し、動的に値を埋め込むばい。

function generateDynamicFormulas() {
  const templateSheet = SpreadsheetApp.getActive().getSheetByName('Template');
  const outputSheet = SpreadsheetApp.getActive().getSheetByName('Report');
  const lastMonthData = { month: '02', year: '2025' };
  
  const formulas = templateSheet.getRange("B2:F10").getFormulas();
  
  const processedFormulas = formulas.map(row =>
    row.map(formula =>
      formula.replace(/\{\{month\}\}/g, lastMonthData.month)
             .replace(/\{\{year\}\}/g, lastMonthData.year)
    )
  );
  
  outputSheet.getRange("B2:F10").setFormulas(processedFormulas);
}

よくあるエラーと対策

1. 範囲が不正

指定した範囲が間違ってると、エラーになるばい。

if (!range || !range.getSheet()) {
  throw new Error('Invalid range specified');
}

2. 数式パースエラー

無効な数式が入ってると動かないこともあるけ、エラーをキャッチしとくばい。

try {
  const formulas = range.getFormulas();
} catch (e) {
  Logger.log(`Error: ${e.message}`);
}

まとめ

getFormulas()メソッドを使えば、スプレッドシートの数式を自在に扱えるばい。これを活用すれば、監査やレポート自動化、データ処理の効率化が簡単にできるけ。ぜひ試してみてさ!

コメント

タイトルとURLをコピーしました