Excel VBA: 编辑单元格时创建确认提示

Excel VBA: Creating a confirmation prompt when a cell is edited

我正在尝试创建确认信息,以便在单元格为空时启动提示。如果用户点击确认,单元格保持空白,否则单元格 returns 为原始值。我有以下但它不起作用,我希望有人能解决这个问题:

Private Sub MYtest()
Dim vatcell As Range
Set vatcell = Worksheets("Invoice").Range("D11:D11")
If vatcell = "" Then

 response = MsgBox("Are you sure you want to change the VAT ammount?" & Chr(10) & Chr(10) _
                        & "Value = " & vatcell & Chr(10) & Chr(10) _
                        & "Do you really want to change it?", vbYesNo + vbQuestion, "Value Already Entered")
            If response = vbYes Then
                vatcell = ""
            Else
                vatcell = vatcell
                End If
                End If
End Sub

提前致谢。

Daryll 的脚本无效:

我相信您希望这是一个事件过程。每次更改工作表 "Invoice" 时,下面都会检查单元格 D11 是否已更改。请注意,这必须存储在 VBE 中的工作表 "Invoice" 中。

Private Sub Worksheet_Change(ByVal Target as Range)
Dim vatcell As Range
Set vatcell = Worksheets("Invoice").Range("D11:D11")

If Not Intersect(Target,vatcell) is Nothing Then

 response = MsgBox("Are you sure you want to change the VAT ammount?" & Chr(10) & Chr(10) _
                        & "Value = " & vatcell & Chr(10) & Chr(10) _
                        & "Do you really want to change it?", vbYesNo + vbQuestion, "Value Already Entered")
End If

If response = vbYes Then
vatcell = ""
Else
vatcell = vatcell
End If
End Sub

您的解决方案缺少两个部分。首先,您需要在更改之前存储单元格的值。其次,您需要连接到一个事件,该事件会告诉您单元格内容何时更改。

' This is where you store the value before it was changed
Private last_vat As Variant

' this is where you capture the value when the worksheet is first loaded
Private Sub Worksheet_Activate()
    Dim vatcell As Range
    Set vatcell = Range("D11")
    last_vat = vatcell.Value
End Sub

' This is where you respond to a change
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim vatcell As Range
    Set vatcell = Range("D11")
    ' Make sure the cell that changed is the one you are interested in
    If Target = vatcell Then
        ' If it changed from something to nothing
        If vatcell.Value = "" And last_vat <> "" Then
            response = MsgBox("Are you sure you want to clear the VAT ammount?" & Chr(10) & Chr(10) _
                        & "Previous Value = " & last_vat & Chr(10) & Chr(10) _
                        & "Do you really want to change it?", vbYesNo + vbQuestion, "Value Already Entered")
            If response = vbYes Then
                ' Allow the change (by doing nothing)
            Else
                ' Reject the change
                vatcell = last_vat
            End If
        End If
        ' Save changes from non-blank to different non-blank value
        last_vat = vatcell.Value
    End If
End Sub