excel - 当自动触发公式时,如何更改我的 Worksheet_Change 代码以更改单元格的值

标签 excel vba formula

My Excel Sheet Example

我的工作表的目的是将客户信息输入到所需的单元格中,就像我在上面发布的图像一样。每一个新的一天,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 的了解有限,我似乎无法完成这项任务。

最佳答案

公式更改不会触发 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

关于excel - 当自动触发公式时,如何更改我的 Worksheet_Change 代码以更改单元格的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51313015/

相关文章:

VBA复制按钮从文本框中复制文本

vba - Excel VBA,转换数据导致Excel崩溃

尝试访问工作表范围时出现 VBA 运行时错误 1004

java - 如何将JTextArea行数的值转换为Dimension height_JAVA

excel - 如何以编程方式从 Excel 中的 VBA 宏中删除数字签名?

c# - 在 C# 中将 Excel 转换为 XML

java - 如何将 as400 假脱机文件转换为 Excel (XLS) 文件

VBA 通过用户选择数组大小来调整数组大小

java - 验证点是否在 3D 空间中的圆锥体内

javascript - LaTeX 公式嵌套