在Excel VBA中更新目标单元格的值

时间:2017-07-09 21:08:17

标签: excel vba excel-vba

我正在尝试使用VBA宏更新Target单元格的值,当它存在于特定范围内时。我想通过将字符串连接到其值来更新其值。例如,如果有些人在Target单元格中写入250,我想要回写" XYZ-250"进入目标细胞。以下是代码:

Dim oldCellAddress As String
Dim oldCellValue As String
Private Sub Worksheet_Change(ByVal Target As Range)
oldCellValue = 0
If Not Intersect(Target, Range("E10:E500")) Is Nothing Then
oldCellValue = Target.Value
Sheet1.Cells(Target.Row, Target.Column).Value = "AST-" & oldCellValue
End If
End Sub

有趣的是,当我更改范围内任何单元格的值(E10到E500)时,消息框会无限次显示并暂停excel,我必须重新启动它。

提前致谢

1 个答案:

答案 0 :(得分:1)

在进行任何会触发Change事件的更改之前禁用事件:

Dim oldCellAddress As String
Dim oldCellValue As String
Private Sub Worksheet_Change(ByVal Target As Range)
    oldCellValue = 0
    If Not Intersect(Target, Range("E10:E500")) Is Nothing Then
        Application.EnableEvents = False
        oldCellValue = Target.Value
        Target.Value = "AST-" & oldCellValue
        Application.EnableEvents = True
    End If
End Sub

如果事件未被禁用,您对单元格的更改将触发Worksheet_Change事件,这将更改单元格,这将触发Worksheet_Change事件,这将更改单元格,这将触发Worksheet_Change事件,这将更改单元格,这将触发Worksheet_Change事件,这将更改单元格,这将触发...

假设您不需要oldCellValueoldCellAddress模块范围变量,但确实想要处理多个单元格的更改,请改用:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("E10:E500")) Is Nothing Then
        Dim c As Range
        Application.EnableEvents = False
        For Each c In Intersect(Target, Range("E10:E500")).Cells
            c.Value = "AST-" & c.Value
        Next
        Application.EnableEvents = True
    End If
End Sub