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

我正在尝试创build一个确认,以便在单元格为空时提示启动。 如果用户单击确认,单元格保持空白,否则单元格返回到原始值。 我有以下但它不工作,我希望有人可以解决这个问题:

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的脚本不工作: 在这里输入图像说明

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

 ' 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 

我相信你希望这是一个事件程序。 下面检查单元格D11是否每次更改工作表“发票”更改。 请注意,这必须存储在VBE工作表“发票”中。

 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