2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Power Automate for desktop「Excelセルに条件書式を設定」

Last updated at Posted at 2022-01-30

概要

前回に続き、視認性を高めるため条件によってセルの背景に色付けします。VBScriptの実行アクションを使い、複数起動しているExcelブックから任意のExcelワークシートの列に条件書式を設定します。
Convert.gif

環境

  • Windows 10 Pro 21H2 11 Pro 23H2
  • Power Automate for desktop 2.16.215.22020 2.46.263.24194 インストーラー版
  • Microsoft Excel for Microsoft 365バージョン2112ビルド16.0.14729.20254 Microsoft® Excel® for Microsoft 365 MSO (バージョン 2408 ビルド 16.0.17928.20114) 64 ビット

注意等

  • Windows11では未検証です。
  • あくまでサンプルとご理解ください。
  • 自己責任でお願いします。
  • 2022年1月2024年9月の情報です。

列に条件書式を設定して背景に色を付ける

%ExcelInstance%に1~100の乱数を10000個出力。50以上の場合セルに色を付けます。VBScriptで列に条件書式を設定します。
image.png

  1. 乱数の生成
    image.png

  2. Excelの起動
    %ExcelInstance%を起動

  3. Excelワークシートに書き込む
    image.png

  4. VBScriptの実行
    vbs

    FormatConditionsオブジェクトに、AddメソッドでXlFormatConditionTypeとXlFormatConditionOperatorを設定します。サンプルでは(1,1,50,100)としています。セルの値が50~100という意味の条件になります。

    FormatConditions

    https://docs.microsoft.com/ja-jp/office/vba/api/excel.formatconditions

    XlFormatConditionType

    https://docs.microsoft.com/ja-jp/office/vba/api/excel.xlformatconditiontype

    XlFormatConditionOperator

    https://docs.microsoft.com/ja-jp/office/vba/api/excel.xlformatconditionoperator

    VBScript
    Option Explicit
    Dim XlApp
    Dim XlSheet
    Dim XlRange
    Dim XlCondition
    
    Set XlApp = GetObject("Book1").Application
    
    Set XlSheet = XlApp.Worksheets(1)
    Set XlRange = XlSheet.Range("A:A")
    '条件付き書式設定( 1=xlCellValue, 1=xlBetween ,50~100)
    Set XlCondition=XlRange.FormatConditions.Add(1,1,50,100)
    XlCondition.Interior.Color = RGB(184, 41, 117)
    
    Set XlCondition = Nothing
    Set XlRange = Nothing
    Set XlSheet = Nothing
    Set XlApp = Nothing
    

5. Excelを閉じる
%ExcelInstance%を閉じる

まとめ

条件書式を設定することができました。他にも列や行の幅を変えたりといろいろできます。スクリプトをフロー内で管理できるのは良いです。

2024年9月追記

セルに色を付けるアクション「Set color of cells in Excel worksheet」が実装されています。VBSを使わなくてもセルに色付けすることが可能です。

image.png

おまけ

2024年9月現在は解決されています。

Excelの起動アクションを使った後、Excelを閉じるアクションを使わず閉じるボタンで終了させていると、プロセスが終了せず、どんどんたまります。「新しいExcelプロセスの配下にネストする」がONの場合ひどいことになります。
e1

コマンドプロンプトでtasklist /v /fi "IMAGENAME eq excel.exe"などとするか、タスクマネージャーで確認できます。プロセスが残っている場合、たとえばVBScriptの実行アクションにGetobject(, "Excel.Application")を使っていたりするとエラーになります。
e2

フローを初期化するときに
e3

などとしてあげるとよいかもしれません。

参考

FormatConditionsについては

XlFormatConditionTypeについては

XlFormatConditionOperatorについては

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?