VBA Excel:如何在编辑激活的单元格之前检测它?

时间:2017-09-20 17:07:52

标签: vba excel-vba excel

我是VBA的新手所以请耐心等待。我正在努力创造一个“待办事项”'列表,用于为输入任务时创建时间戳。如果用户尝试编辑现有条目,时间戳或任务,则应提示他们询问他们是否确定要更改它。我有这个工作(大多数)。到目前为止,这是代码的截图,其中包含它的工作原理(见下文)。

正确地提示用户是否编辑了单元格。到目前为止,用户编辑单元格,然后提示他们是否确定编辑,如果没有,则将先前的值插回到代码中。问题是这会再次触发更改,因为它只是将文本输入到单元格中。

我一直试图想出一个优雅的解决方案,但没有想到一个。如果我知道如何在实际编辑之前提示用户,我就不必做任何此操作。从逻辑上看,它可能看起来像:单元格变为活动状态(从它们开始输入它),但随后立即提示有关向前移动的更改,而不是等到更改完成。

有没有人有任何想法如何做到这一点?

To-Do list

Private lastVal As Variant

Private Sub Worksheet_Change(ByVal Target As Range)
Dim timeCol, taskCol As Integer
Dim sRow, sCol As Integer
Dim currentCell As Range

timeCol = 1
taskCol = 2

sRow = Target.row
sCol = Target.Column

Set currentCell = Cells(sRow, sCol)

'Checks for timestamp or task column. If Cell wasn't empty, 
'prompt user to confirm the change
If sCol = timeCol Or sCol = taskCol Then
    If lastVal <> "" Then
        response = MsgBox("Old Value:  " & lastVal & Chr(10) & Chr(10) _
              & "New Value:  " & currentCell & Chr(10) & Chr(10) _
              & "Are you sure you want to make this change?", _
              vbYesNo + vbQuestion, "Change Confirmation")
        If response = vbYes Then
            'Do nothing
        Else
            'Reject the change
            currentCell = lastVal
        End If
    End If
End If

'Checks for task column. If timestamp cell at current row is empty
'and something was entered into task column, fills timestamp cell
If sCol = taskCol Then
    If Cells(sRow, timeCol) = "" = True Then
        If currentCell <> "" Then
            Cells(sRow, timeCol) = Now()
        End If
    End If
End If

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim sRow, sCol
    Dim currentCell As Range

    sRow = Target.row
    sCol = Target.Column


    Set currentCell = Cells(sRow, sCol)
    lastVal = currentCell

End Sub

0 个答案:

没有答案