在 Microsoft Excel 中,您可以藉由將結果儲存在工作表的非計算部分來建立執行中總計,以避免循環參考。 本文包含範例 Microsoft Visual Basic for Applications 程式,可藉由將執行中的總計儲存在單元格批注中來執行此動作。
其他相關資訊
Microsoft 提供的程式設計範例僅供說明之用,並不具任何明示或暗示的責任擔保。 這包括 (但不限於) 任何目的之適售性及適用性的暗示責任擔保。 本文假設您熟悉示範的程式設計語言,也熟悉用以建立和偵錯程序的工具。 Microsoft 技術支援工程師可以協助說明特定程序的功能,但不會修改這些範例以提供附加功能或建構程序來滿足您的特定需求。
在儲存格中建立執行中總計
在 Microsoft Excel 中開啟新的活頁簿。
啟動 Visual Basic 編輯器 (按 ALT+F11) 。
在 [插入] 功能表上,按一下 [模組]。
在此課程模組中輸入下列宏:
VB
' 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"EndSub'----------------------------------------------------------' 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()
OnErrorGoTo 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.TextText:="RT= " & RT
EndIfEndWithExitSub' Skip over the errorhandler routine.
errorhandler: ' End the procedure if no comment in the cell.ExitSubEndSub'--------------------------------------------------------------' 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.TextText:="RT= " & (ActiveCell * 1)
EndWithEndSub