如何在Excel中使用cancel创建单元格更改前的事件,对于活动单元格

lf5gs5x2  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(186)

vba -excel
对于我所描述的事件,是否有更好的解决方案?enter image description here

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
2wnc66cl

2wnc66cl1#

不如这样:
方法:

**Offset**用于恢复活动单元的位置
**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

相关问题