OnEntry マクロを使用して、Excel のセル コメントに実行中の合計を作成する
概要
Microsoft Excel では、ワークシートの計算されていない部分に結果を格納することで、実行合計を作成するときに循環参照を回避できます。 この記事には、実行中の合計をセル コメントに格納することでこれを行うサンプルの Microsoft Visual Basic for Applications プロシージャが含まれています。
詳細
Microsoft は、例示のみを目的としてプログラミング例を提供しており、明示または黙示にかかわらず、いかなる責任も負わないものとします。 これには、市販性または特定の目的との適合性についての黙示の保証も含まれますが、これに限定はされません。 この記事は、説明されているプログラミング言語、手順を作成およびデバッグするために使用されているツールに読者が精通していることを前提にしています。 マイクロソフト サポート窓口では、特定のプロシージャの機能説明に関するご質問に対して支援いたしますが、本例を特定の目的を満たすために機能を追加したり、プロシージャを構築することは行いません。
セルに実行中の合計を作成するには
Microsoft Excel で新しいブックを開きます。
Visual Basic エディターを起動します (Alt キーを押しながら F11 キーを押します)。
[挿入] メニューの [モジュール] をクリックします。
このモジュールに次のマクロを入力します。
' The Auto_Open name forces this macro to run every time ' the workbook containing this macro is opened. Sub Auto_Open() ' Every time a cell's value is changed, ' the RunningTotal macro runs. Application.OnEntry = "RunningTotal" End Sub '---------------------------------------------------------- ' This macro runs each time the value of a cell changes. ' It adds the current value of the cell to the value of the ' cell comment. Then it stores the new total in the cell comment. Sub RunningTotal() On Error GoTo errorhandler ' Skip cells that have no comment. With Application.Caller ' Checks to see if the cell is a running total by ' checking to see if the first 4 characters of the cell ' comment are "RT= ". NOTE: there is a space after the equal ' sign. If Left(.Comment.Text, 4) = "RT= " Then ' Change the cell's value to the new value in the cell ' plus the old total stored in the cell comment. RT = .Value + Right(.Comment.Text, Len(.Comment.Text) - 4) .Value = RT ' Store the new total in the cell note. .Comment.Text Text:="RT= " & RT End If End With Exit Sub ' Skip over the errorhandler routine. errorhandler: ' End the procedure if no comment in the cell. Exit Sub End Sub '-------------------------------------------------------------- ' This macro sets up a cell to be a running total cell. Sub SetComment() With ActiveCell ' Set comment to indicate that a running total is present. ' If the ActiveCell is empty, multiplying by 1 will ' return a 0. .AddComment .Comment.Text Text:="RT= " & (ActiveCell * 1) End With End Sub
マクロを入力したら、[ファイル] メニューの [閉じる] をクリックし、[Microsoft Excel に戻る] をクリックします。
ブックを保存して閉じてから、もう一度開きます。
入力したAuto_Open マクロは、ブックを開くときに実行されます。
セル C3 を選択します。
これは、実行中の合計を含むコメントを含むセルです。
SetComment マクロを実行するには、次の手順に従います。
- [ツール] メニューの [マクロ] をポイントし、[マクロ] をクリックします。
- [マクロ] ダイアログ ボックスで、[SetComment] をクリックし、[実行] をクリックします。
実行合計の使用例
実行中の合計を使用するには、次の手順に従います。
- セル C3 に数値 10 を入力します。
- セル C3 を選択すると、コメントに "RT= 10" (引用符なし) が表示されます。
- セル C3 に数値 7 を入力します。
- セル C3 を選択すると、コメントに "RT= 17" (引用符なし) が表示されます。
実行中の合計を削除するには
実行中の合計を削除するには、次の手順に従います。
- 削除する実行合計を含むセルを選択します。
- セルを右クリックし、ショートカット メニューの [コメントの削除] をクリックします。
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示