首页 > 解决方案 > 当自动触发公式时,如何更改我的 Worksheet_Change 代码以更改单元格的值

问题描述

我的 Excel 工作表示例

我的工作表的目的是将客户信息输入到所需的单元格中,就像我在上面发布的图像一样。每个新的一天,该DateCounter列将增加一个。

DateCounter公式:(=IFERROR(IF(ISBLANK(B3),"",TODAY()-B3),"")今天的日期 -B3创建行的日期 = 自创建行以来已经过去了多少天。)

在它自动增加一之后,我希望该Interest列自动更新并使其等于自身+该Per Diem行的。(例如:[I3利息=I3利息+H3每日津贴]。

我有一个 VBA 代码可以做到这一点,但它只在我DateCounter手动更改单元格时有效,而不是在自动触发公式时有效。

VBA代码:

'*If "day" range is changed, update Interest cell*'

Private Sub Worksheet_Change(ByVal target As Range)

    If Not Intersect(target, Range("N3:N400")) Is Nothing Then

        Range("I" & target.Row).Value = Range("I" & target.Row).Value + Range("H" & target.Row)

        'Change Interest cell to the accounting format
        Range("I" & target.Row).NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(@_)"
    End If
End Sub

我试图将代码更改为,Worksheet_Calculate() event但它会触发列中的每一行,并且由于无限循环,我的 excel 工作表崩溃。我试过这个例子[here]。我也尝试了其他示例,但我对 VBA 的了解有限,我似乎无法完成这项任务。

标签: excelvbaformula

解决方案


公式更改不会触发 Worksheet_Change。您需要 Worksheet_Calculate 和一个静态变量。

Option Explicit

Private Sub Worksheet_Calculate()
    Static tday As Long

    If Date <> tday Then
        tday = Date
        'suspend calculation so you don't run on top of yourself
         application.calculation = xlcalculationmanual

        'do all the update work here
        range(cells(2, "H"), cells(rows.count, "H").end(xlup)).copy
        cells(2, "I").pastespecial Paste:=xlPasteValues, Operation:=xlAdd


        'resume automatic calculation
         application.calculation = xlcalculationautomatic
    End If
End Sub

推荐阅读