【问题标题】:Storing resultant cell value from an addition and then adding it to new results every time从添加中存储结果单元格值,然后每次将其添加到新结果中
【发布时间】:2018-04-01 00:51:37
【问题描述】:

我正在 Excel 中创建一个模型,其中一个单元格计算两个单元格的总和,并在每次它所依赖的两个单元格更改值时不断添加该值。例如,

如果,

A + B = C

那么,

实例 1:-> 5 + 5 = 10

实例 2:-> 4 + 3 = 17

实例 3:-> 2 + 3 = 22

等等……

我相信这可以通过 VB 脚本来实现。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您只需将以下代码放入工作表代码窗格中:

    Private Sub Worksheet_Change(ByVal Target As Range)
        If Intersect(Range("A1:A2"), Target) Is Nothing Then Exit Sub
        Range("B1") = Range("B1") + WorksheetFunction.sum(Range("A1:A2"))
    End Sub
    

    当然你必须改变:

    • 所有“A1:A2”出现在您的实际单元格中以求和地址

    • 所有“B1”出现在您保存运行总和地址的实际单元格中

    【讨论】:

    • 这是给你的 +1。我为 debug.print 写了代码,却忘了重构,然后使用工作表单元格来保存结果 :-) Dammit
    • 感谢@QHarr。好吧,结果单元格被 OP 明确引用,所以我选择了它
    • 你是对的。我没有正确阅读,何时重新编写,但完全忘记了我现在正在使用一个范围来存储值:-)
    • 嘿,谢谢,代码有效。现在,如果我想为求和添加一个条件,例如,如果 C1 = 1,那么 A1+A2 = B1,我该怎么做?
    • 嘿抱歉。没有注意到。已经做到了。
    【解决方案2】:

    将运行总计保存在公共变量 (total) 中。在工作簿打开时使用 workbook_open 事件将其初始化为两个感兴趣单元格的总和。然后使用 worksheet_change 事件来监视对这两个单元格的更改,如果其中任何一个发生更改,则将其新值添加到 total 的现有值中。我使用单元格C1 来显示运行总数。

    在标准模块中:

    Option Explicit
    
    Public total As Long
    Public targetCell As Range
    

    在 ThisWorkbook 代码窗格中

    Option Explicit
    
    Private Sub Workbook_Open()
    
        With ThisWorkbook.Worksheets("Sheet1")
    
            Set targetCell = .Range("C1")
    
            total = Application.WorksheetFunction.Sum(.Range("A1:B1"))
            targetCell = total
    
        End With
    
    End Sub
    

    在要监控的单元格所在的工作表代码窗格中

    Option Explicit
    
    Private Sub Worksheet_Change(ByVal Target As Range)
    
        If Not Application.Intersect(Target, Range("A1")) Is Nothing Then
            total = total + Target
            targetCell = total
        End If
    
        If Not Application.Intersect(Target, Range("B1")) Is Nothing Then
            total = total + Target
            targetCell = total
        End If
    
    End Sub
    

    或者正确地做@DisplayName 所做的事情!我最初是为总计的 Debug.Print(不写入单元格)而写的,但忘记了重构。

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2014-08-03
      • 1970-01-01
      • 2019-05-14
      相关资源
      最近更新 更多