3

对于我正在编写的代码,我监视某些单元格范围内的更改以运行函数和私有子程序。为此,我在 sub.xml 中使用 Intersect 函数worksheet_change

但是,相交“测试”的触发器始终是我“移出”我正在测试的单元格是通过鼠标单击进入不同的单元格还是通过光标移动。

我需要的是一种方法来定义一个包含.address我之前选择的单元格的变量。

我尝试了下面的代码,但我得到的只是错误。

有谁知道如何做到这一点?

Public xfrLastCell As String
Public xfrActiveCell As String

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If xfrActiveCell = "" Then xfrActiveCell = ActiveCell.Address
xfrLastCell = xfrActiveCell
xfrActiveCell = ActiveCell
MsgBox xfrLastCell

End Sub
4

4 回答 4

3

下面的代码对我有用-您对 activecell 的分配缺少地址,这意味着 activecell 变量始终为空白

Option Explicit

Public xfrLastCell As String
Public xfrActiveCell As String

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If xfrActiveCell = "" Then xfrActiveCell = ActiveCell.Address
xfrLastCell = xfrActiveCell
xfrActiveCell = ActiveCell.Address
MsgBox xfrLastCell

End Sub
于 2013-10-04T11:19:32.947 回答
2

使用此代码,引用PreviousActiveCell将返回所需的结果:

Public PreviousActiveCell as Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Static pPrevious as Range
    Set PreviousActiveCell = pPrevious
    Set pPrevious = ActiveCell
End Sub

这适用于单个工作表。您是否需要跨其他工作表和工作簿的上一个单元格?

于 2013-10-04T12:29:20.707 回答
1

“记住”范围可能比范围的地址更容易:

Dim Oldcell As Range
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Oldcell Is Nothing Then
        Set Oldcell = Target
        Exit Sub
    End If
    MsgBox "New cell is " & Target.Address & vbCrLf & "Old cell was " & Oldcell.Address
    Set Oldcell = Target
End Sub
于 2013-10-04T11:29:02.653 回答
0

If是不必要的。我用过这个:

Public sPreviousTarget As String
Public sTarget As String

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  sPreviousTarget = sTarget
  sTarget = Target.Address
End Sub

此外,Target不同于ActiveCell(ActiveCellTarget) 中的单元格之一。

于 2018-01-16T13:18:16.643 回答