Google Sheets script - bold words from range in target range

Martin Z

how can I create script that will bold target range, but only words that are in source range? Lest say I have target range in column A, source range B

Column A - target Column B - source
A cup of coffee coffee
Mobile phone phone
Phone number
Flatscreen
Laptop
Cellphone

Result of this script will be that it will bold like this:

Column A - target Column B - source
A cup of coffee coffee
Mobile phone phone
Phone number
Flatscreen
Laptop
Cellphone

Much thanks for answers.

Cooper

The only way to accomplish this sort of formatting in a spreadsheet is with the use of Class richTextValue and Class richTextValueBuilder all other forms of formatting of this nature apply to entire ranges or cells.

This function will bold all of the selected words in the selected range:

function boldMywords() {
  //const red = SpreadsheetApp.newTextStyle().setForegroundColor('red').build();
  //const org = SpreadsheetApp.newTextStyle().setForegroundColor('orange').build();
  //const blu = SpreadsheetApp.newTextStyle().setForegroundColor('blue').build();
  const bold = SpreadsheetApp.newTextStyle().setBold(true).build();
  //const cA = [red,org,blu];//colors array
  const wordA = ['coffee','phone'];//words array
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  const rg = sh.getDataRange();//selected range
  let vs = rg.getDisplayValues();
  
  vs.forEach((r, i) => {
    r.forEach((c, j) => {
      let idxObj = { pA: [] };
      wordA.forEach(w => {
        let idx = c.indexOf(w);
        if (~idx) {
          idxObj[w] = idx;
          idxObj.pA.push(w);
        }
      });
      if (idxObj.pA.length > 0) {
        let cell = sh.getRange(i + 1, j + 1);
        let val = SpreadsheetApp.newRichTextValue().setText(c);
        idxObj.pA.forEach((p,k) => {
          //val.setTextStyle(idxObj[p], idxObj[p] + p.length, cA[k % cA.length]);
          val.setTextStyle(idxObj[p], idxObj[p] + p.length, bold);
        });
        cell.setRichTextValue(val.build());
      }
    });
  });
}

enter image description here

SpreadsheetApp.newTextStyle

This function is modified to search for words in column A that are selected from words in column B

function boldMywords() {
  //const red = SpreadsheetApp.newTextStyle().setForegroundColor('red').build();
  //const org = SpreadsheetApp.newTextStyle().setForegroundColor('orange').build();
  //const blu = SpreadsheetApp.newTextStyle().setForegroundColor('blue').build();
  const bold = SpreadsheetApp.newTextStyle().setBold(true).build();
  //const cA = [red,org,blu];//colors array
  //const wordA = ['coffee','phone'];
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  const rg = sh.getRange(1,1,sh.getLastRow());
  const wrg = sh.getRange(1,2,getColumnHeight(2,sh,ss));
  const wordA = wrg.getDisplayValues().flat();
  let vs = rg.getDisplayValues();
  
  vs.forEach((r, i) => {
    r.forEach((c, j) => {
      let idxObj = { pA: [] };
      wordA.forEach(w => {
        let idx = c.indexOf(w);
        if (~idx) {
          idxObj[w] = idx;
          idxObj.pA.push(w);
        }
      });
      if (idxObj.pA.length > 0) {
        let cell = sh.getRange(i + 1, j + 1);
        let val = SpreadsheetApp.newRichTextValue().setText(c);
        idxObj.pA.forEach((p,k) => {
          //val.setTextStyle(idxObj[p], idxObj[p] + p.length, cA[k % cA.length]);
          val.setTextStyle(idxObj[p], idxObj[p] + p.length, bold);
        });
        cell.setRichTextValue(val.build());
      }
    });
  });
}

function getColumnHeight(col, sh, ss) {
  var ss = ss || SpreadsheetApp.getActive();
  var sh = sh || ss.getActiveSheet();
  var col = col || sh.getActiveCell().getColumn();
  var rcA = [];
  if (sh.getLastRow()){ rcA = sh.getRange(1, col, sh.getLastRow(), 1).getValues().flat().reverse(); }
  let s = 0;
  for (let i = 0; i < rcA.length; i++) {
    if (rcA[i].toString().length == 0) {
      s++;
    } else {
      break;
    }
  }
  return rcA.length - s;
  //const h = Utilities.formatString('col: %s len: %s', col, rcA.length - s);
  //Logger.log(h);
  //SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(h).setWidth(150).setHeight(100), 'Col Length')
}

This one will provide case free matching:

function boldMywords() {
  //const red = SpreadsheetApp.newTextStyle().setForegroundColor('red').build();
  //const org = SpreadsheetApp.newTextStyle().setForegroundColor('orange').build();
  //const blu = SpreadsheetApp.newTextStyle().setForegroundColor('blue').build();
  const bold = SpreadsheetApp.newTextStyle().setBold(true).build();
  //const cA = [red,org,blu];//colors array
  //const wordA = ['coffee','phone'];
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  const rg = sh.getRange(1,1,sh.getLastRow());
  const wrg = sh.getRange(1,2,getColumnHeight(2,sh,ss));
  const wordA = wrg.getDisplayValues().flat();
  let vs = rg.getDisplayValues();
  
  vs.forEach((r, i) => {
    r.forEach((c, j) => {
      let idxObj = { pA: [] };
      wordA.forEach(w => {
        let idx = c.toLowerCase().indexOf(w.toLowerCase());
        if (~idx) {
          idxObj[w] = idx;
          idxObj.pA.push(w);
        }
      });
      if (idxObj.pA.length > 0) {
        let cell = sh.getRange(i + 1, j + 1);
        let val = SpreadsheetApp.newRichTextValue().setText(c);
        idxObj.pA.forEach((p,k) => {
          //val.setTextStyle(idxObj[p], idxObj[p] + p.length, cA[k % cA.length]);
          val.setTextStyle(idxObj[p], idxObj[p] + p.length, bold);
        });
        cell.setRichTextValue(val.build());
      }
    });
  });
}

This last one get's the words to search for from a prompt:

function boldMyWords() {
  const red = SpreadsheetApp.newTextStyle().setForegroundColor('red').setBold(true).build();
  const bold = SpreadsheetApp.newTextStyle().setBold(true).build();
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const rg = sh.getDataRange();
  let vs = rg.getDisplayValues();
  let r = SpreadsheetApp.getUi().prompt('Enter words to search for separated by commas', SpreadsheetApp.getUi().ButtonSet.OK_CANCEL);
  if (r.getSelectedButton() == SpreadsheetApp.getUi().Button.OK) {
    let wordA = r.getResponseText().split(',');
    vs.forEach((r, i) => {
      r.forEach((c, j) => {
        let idxObj = { pA: [] };
        wordA.forEach(w => {
          let idx = c.toLowerCase().indexOf(w.toLowerCase());
          if (~idx) {
            idxObj[w] = idx;
            idxObj.pA.push(w);
          }
        });
        if (idxObj.pA.length > 0) {
          let cell = sh.getRange(i + 1, j + 1);
          let val = SpreadsheetApp.newRichTextValue().setText(c);
          idxObj.pA.forEach((p, k) => {
            val.setTextStyle(idxObj[p], idxObj[p] + p.length, red);
            val.setTextStyle(idxObj[p], idxObj[p] + p.length, bold);
          });
          cell.setRichTextValue(val.build());
        }
      });
    });
  }
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Google sheets API range issue

Google sheets lookup with substring on range

Google Sheets get.range syntax if the range is formed partly from a cell value

How to delete all unprotected rows in a range of particular sheets from Google Sheets using Apps Scripts

Google Sheets: extract one column of a named range

Google App Script: How do I get only data range from named range?

Google Sheets: How do I create an array from a range, adding a column with a constant literal value in every row?

How sum a range column in google app script

Google Apps Script-ForEach in Range

Google Sheets: how to sum a dynamic range across columns using a variable to determine range length

How to get the specific range of row data from google sheet through apps script

Google script that triggers copy of a range to another spreadsheet - NOT WORKING for me

Google Sheets Script getLastRow

How to transfer the data from input range to output range based on the condition in google sheet?

Passing arguments / parameters from a Google sheets custom function to the script function

Rearrange values displayed in firebase realtime database from google sheets script

Select new range based on another sheets selection

Getting a code that copies a range from multiple sheets and paste it into a final sheet called "ALL SURVEY"

Google Sheets App Script:onChange関数がトリガーを介して実行されると、e.rangeはnullになります

Using target offset to clear a range of cells in excel

VBA Worksheet_Change(ByVal Target As Range)

Python Segfault, from range?

Another user should be able to update the protected range in google spreadsheet using google app script

Is it possible to find as much matching words from different sentences located in different columns in Google Sheets?

Copy image from Google Sheets to Google Docs using Google Apps Script

google sheets - convert data in entire column from KB to GB using google script

Creating an Array from a Range in VBA

Creating an Array from a Range in VBA

Count values from range in Matlab

TOP 一覧

  1. 1

    STSでループプロセス「クラスパス通知の送信」のループを停止する方法

  2. 2

    Spring Boot Filter is not getting invoked if remove @component in fitler class

  3. 3

    Python / SciPyのピーク検出アルゴリズム

  4. 4

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  5. 5

    tkinterウィンドウを閉じてもPythonプログラムが終了しない

  6. 6

    androidsoongビルドシステムによるネイティブコードカバレッジ

  7. 7

    ZScalerと証明書の問題により、Dockerを使用できません

  8. 8

    VisualStudioコードの特異点/ドッカー画像でPythonインタープリターを使用するにはどうすればよいですか?

  9. 9

    ビュー用にサイズ変更した後の画像の高さと幅を取得する方法

  10. 10

    二次導関数を数値計算するときの大きな誤差

  11. 11

    Ansibleで複数行のシェルスクリプトを実行する方法

  12. 12

    画像変更コードを実行してもボタンの画像が変更されない

  13. 13

    Reactでclsxを使用する方法

  14. 14

    Three.js indexed BufferGeometry vs. InstancedBufferGeometry

  15. 15

    __init__。pyファイルの整理中に循環インポートエラーが発生しました

  16. 16

    PyTesseractを使用した背景色のため、スクリーンショットからテキストを読み取ることができません

  17. 17

    値間の一致を見つける最も簡単な方法は何ですか

  18. 18

    reCAPTCHA-エラーコード:ユーザーの応答を検証するときの「missing-input-response」、「missing-input-secret」(POSTの詳細がない)

  19. 19

    三項演算子良い練習の代わりとしてOptional.ofNullableを使用していますか?

  20. 20

    好き/愛の関係のためのデータベース設計

  21. 21

    エンティティIDを含む@RequestBody属性をSpringの対応するエンティティに変換します

ホットタグ

アーカイブ