この記事では、ExcelのRangeオブジェクトに関連するFormulaプロパティについて説明しています。Formulaプロパティは、A1形式の表記でオブジェクトの暗黙の交差式を表します。Dynamic Arraysが有効なExcelでは、Range.Formula2が推奨されますが、以前のFormulaも互換性のためにサポートされ続けます。数式をセルに設定すると、数式が文字列として返され、セルが定数や空白の場合はそれに応じた値が返されます。例として、特定のセルに数式を設定するコードが示されています。
Excel VBAのRange.Formula2プロパティについて
Excel VBA(Visual Basic for Applications)は、Excelの機能を拡張するためのプログラミング言語です。本記事では、Excel VBAにおけるRange.Formula2プロパティについて詳しく解説します。このプロパティは、セルの数式を設定したり取得したりするために使用されます。
Range.Formula2プロパティの概要
Range.Formula2プロパティは、指定したRangeオブジェクトの数式をA1スタイルの表記で返したり設定したりします。このプロパティは、動的配列が有効になったExcelで新たに導入され、Range.Formulaプロパティに取って代わるものです。なお、Range.Formulaも互換性を保つために引き続きサポートされます。
つまり、Range.Formulaを使用しても問題はありませんが、動的配列の機能を最大限に生かしたい場合は、Range.Formula2を使用することが推奨されます。
構文
以下がRange.Formula2の基本的な構文です。
expression.Formula2
ここで、expressionはRangeオブジェクトを表す変数です。
特徴と注意点
- 動的配列のサポート:
Range.Formula2は動的配列に対応しており、必要に応じて計算結果を自動的に展開します。 - OLAPデータソース非対応:
Range.Formula2プロパティは、OLAP(Online Analytical Processing)データソースには使用できません。 - 定数または空のセル: セルが定数を含む場合、その値が返されます。また、セルが空である場合は空文字列が返されます。数式が含まれる場合、数式を見るために数式バーに表示される形式の文字列が返されます。
- 日付の検証: 日付の値または数式をセルに設定した場合、Excelはセルの書式が適用されているかを確認し、必要に応じて短い日付形式に変更します。
使用例
以下のコード例は、Sheet1のA1セルに数式を設定する方法を示しています。
Worksheets("Sheet1").Range("A1").Formula = "=$A$4+$A$10"
さらに、以下の例では、Sheet1のA1セルに今日の日付を表示する数式を設定しています。
Sub InsertTodaysDate()
' 本マクロはSheet1のA1セルに今日の日付を挿入します
Sheets("Sheet1").Select
Range("A1").Select
Selection.Formula = "=TEXT(NOW(),""mmm dd yyyy"")"
Selection.Columns.AutoFit
End Sub
サポートとフィードバック
Office VBAやこのドキュメントに関する質問やフィードバックがある場合は、Office VBAのサポートとフィードバックを参照してください。ここでは、サポートを受けたり、フィードバックを提供する方法についてのガイダンスが得られます。
結論
Range.Formula2プロパティは、Excel VBAを使用する際に非常に便利な機能です。特に動的配列の機能が求められる場合には、このプロパティを利用することでより柔軟かつ強力な数式操作が可能になります。是非、実際のシナリオで試してみてください。
————-
Range.Formula property (Excel) | Microsoft Learn
Source link
The article discusses the Formula property of a Range object in Excel VBA, which allows users to return or set a formula in A1-style notation for cells. It mentions that Formula2 is the newer property used with Dynamic Arrays in Excel, though Formula remains available for compatibility reasons.
Key points include:
- The
Formulaproperty returns the cell’s formula as a string, including an equal sign, or its constant value if no formula exists. An empty cell returns an empty string. - When setting a formula to a cell containing a date, Excel ensures the cell is formatted correctly as a date; if not, it applies a default format.
- Formulas can be assigned to one- or two-dimensional ranges, and multiple cells can be filled with the same formula.
- The article provides example VBA code for setting a formula in a specific cell and for inserting the current date into a cell.
The article also emphasizes that the Formula property is not applicable for OLAP data sources and invites readers for feedback or assistance with Office VBA.