首页 > 解决方案 > 如何根据其旁边的单元格中的值更改来修改单元格值

问题描述

我正在尝试将某个值放入单元格中,具体取决于它旁边的单元格的值是否已被编辑。例如,如果用户编辑了 E 列中任何单元格的值,则 F 列中它旁边的单元格中必须出现一个数字。在 VBA 中是否有简单的方法来做到这一点?

标签: excelvba

解决方案


这是一个非常小的示例,说明如何执行此操作。

首先进入您的 VBE 并双击将要发生此“更改”事件的工作表。我们想将此代码专门放在该表中。

接下来,您可以将其粘贴到:

Private Sub Worksheet_Change(ByVal Target As Range)
    'Test to see if the thing that changed was in range E:E
    'Target variable will hold the range that experienced the change
    If Not Intersect(Range("E:E"), Target) Is Nothing Then

        'Declare a variable to hold a single cell that was changed
        Dim changedCell As Range

        'Loop through all the cells that were changed in column E
        'generally just one is changed, but it could be multiple
        For Each changedCell In Intersect(Range("E:E"), Target).Cells
            'Now we will increment the number that is in column F next to the cell that changed
            changedCell.Offset(0, 1).Value = changedCell.Offset(0, 1).Value + 1
        Next changedCell
    End If
End Sub

这个子程序是一个特殊的子程序。它被调用Worksheet_Change()并且它有一个称为“目标”的参数。每次在此选项卡/工作表中发生任何更改时,都会自动触发。Target将保存经历变化的单元格范围。

此代码测试以查看更改的范围是否在 Column 中E,如果是,它会遍历每个更改的单元格(您可以通过复制/粘贴一次更改多个单元格),然后它只是在 F 列中增加一个计数器到每个单元格。


推荐阅读