VBA 数式の挿入



数式の挿入


VBAを使ってセルに数式を入力する方法です。
VBA処理で計算するのではなくエクセルシートに数式を残します。

関数、メソッドなど
FormulaプロパティとFormulaR1C1プロパティの2種類で実行できます。
Range.Formula = "=A2+B2"
Range("A1").FormulaR1C1 = "=R2C1+R2C2"
「Formula =」以降はダブルクォーテーションで囲った中に「=数式」という形式で記述します。

「Formula =」以降変数を使用する場合はCells形式とAddressプロパティを使用します。

サンプルコード
Sub formula1()
Dim a As Long, b As Long
    
    'そのまま数式を直接
    Range("A1").Formula = "=A2+B2"
    '変数使う場合
    a = 1
    b = 2
    Range("A1").Formula = "=" & Cells(b, a).Address & "+" & Cells(b, b).Address
End Sub


解説
上記サンプルでは両方ともA1セルにA2+B2を入力しています。
(Cells形式+Addressだと既定値は絶対参照になるので"=$A$2+$B$2"になっています。
絶対参照ではなく相対参照にするには

        Range("A1").Formula = "=" & Cells(b, a).Address(RowAbsolute:=False, ColumnAbsolute:=False) & _
     "+" & Cells(b, b).Address(RowAbsolute:=False, ColumnAbsolute:=False)

としてAddressプロパティのRowAbsoluteとColumnAbsoluteをFalseにします。)

○その他
・「Formula =」あと["=…"]の[=]を入れないと文字列として扱われます。

・エクセル関数を使用する場合も基本的に同じです。
Sub formula2()
    Range("A1").Formula = "=sum(A2,B2)"
    Range("A1").Formula = "=sum(" & Cells(b, a).Address & "+" & Cells(b, b).Address & ")"
End Sub