如何让excel运行VBA代码以响应用户按ESCAPE键?
下面是我正在使用的代码。当用户双击没有值的单元格时,代码输入今天的日期,单元格保持焦点,光标位于单元格内,允许用户编辑值。但是,如果用户按ESCAPE键,单元格将保留今天的日期。我希望它恢复用户双击单元格之前单元格中的值。这就是用户在空白单元格中输入数据时通常的行为 我知道当VBA运行时,撤销堆栈被清除,编程可以用来存储和恢复更改的值,例如 但是,如何让excel对用户按ESCAPE键作出响应如何让excel运行VBA代码以响应用户按ESCAPE键?,excel,Excel,下面是我正在使用的代码。当用户双击没有值的单元格时,代码输入今天的日期,单元格保持焦点,光标位于单元格内,允许用户编辑值。但是,如果用户按ESCAPE键,单元格将保留今天的日期。我希望它恢复用户双击单元格之前单元格中的值。这就是用户在空白单元格中输入数据时通常的行为 我知道当VBA运行时,撤销堆栈被清除,编程可以用来存储和恢复更改的值,例如 但是,如何让excel对用户按ESCAPE键作出响应 Private Sub Worksheet_BeforeDoubleClick(ByVal Targe
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not (Intersect(Target, Me.Range("shtJobList2_Columns_EnterDateOnCellDoubleClick")) Is Nothing) Then
' User double clicked in a column of interest
If Not (Intersect(Target, Me.Range("TableOfJobs2")) Is Nothing) Then
' User double click in the table as well!
If IsEmpty(Target.Value) Then
Target.Value = Date
Beep
Else
If vbOK = MsgBox("Do you want to enter todays date over the value that is already in the cell? (" & Target.Value & ")", vbOKCancel) Then
Target.Value = Date
End If
End If
End If
End If
End Sub
您可以使用Application.OnKey来检测ESCAPE键的按下情况,但前提是您的设备未处于编辑模式。要澄清几点:
Application.Undo
,存储以前的值,然后使用Application.Redo
并请求确认。(例如,单击)工作表_
,请不要因为不重要而放弃Cancel As Boolean参数。将“取消”设置为True将停止单元格内编辑过程。每次双击(插入日期)都要进入编辑模式,而不是编辑当前日期不合适的少数项,这似乎很尴尬。我之所以说是少数,是因为如果当前日期不是大多数时间所期望的日期,那么整个过程都是毫无用处的Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Intersect can have more than two paramteters
If Not (Intersect(Target, _
Me.Range("shtJobList2_Columns_EnterDateOnCellDoubleClick"), _
Me.Range("TableOfJobs2")) Is Nothing) Then
' User double clicked in a column of interest and the table
If IsEmpty(Target) Then
Cancel = True
Target.Value = Date
Beep
Else
If vbOK = MsgBox("Do you want to enter todays date over the value that is already in the cell? (" & Target.Value & ")", vbYesNo) Then
Cancel = True
Target.Value = Date
End If
End If
End If
End Sub
这会通过在几个地方设置Cancel=True来改变最初演示的流程。也许你可以用它来得到你想要的结果