如何在 Excel 中取消更改单元格之前创建事件。对于活动单元格

问题描述 投票:0回答:1

vba-excel

针对我描述的这个事件,有更好的解决方案吗?

Dim bitExit As Boolean

Private Sub Worksheet_Change(ByVal Target As Range)
    If bitExit Then
        Application.Undo
        bitExit = False
        Exit Sub
    End If
    Dim Cancel As Boolean
    Cancel = BeforeCellChange(Target)
    If Cancel Then
        bitExit = True
        Target = ""
    End If
End Sub

Private Function BeforeCellChange(ByVal Target As Range) As Boolean
    BeforeCellChange = True
End Function
excel vba events
1个回答
0
投票

这个怎么样:

方法:

偏移用于恢复活动单元格的位置

EnableEvents用于重置目标单元格的值

Dim bitExit As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim c As Range
    Set c = ActiveCell
    If bitExit Then
        'ActiveCell.Offset(-1).Select
        c.Offset(Target.Row - c.Row, Target.Column - c.Column).Select
        bitExit = False
        Exit Sub
    End If
    Dim Cancel As Boolean
    Cancel = BeforeCellChange(Target)
    If Cancel Then
        bitExit = True
        Application.EnableEvents = False
        Target = ""
        c.Offset(Target.Row - c.Row, Target.Column - c.Column).Select
        Application.EnableEvents = True
    End If
End Sub
Private Function BeforeCellChange(ByVal Target As Range) As Boolean
    rem set your rule
    If Target.Value <> "w" Then BeforeCellChange = True
End Function

© www.soinside.com 2019 - 2024. All rights reserved.