2017-12-02 93 views
0

如果在单击“A2”之前ActiveCell为“A1”,我希望if子句为真。 它没有连接一个按钮或任何东西。它必须通过点击“A2”来工作。 这是我尝试我做:在Target.Address之前检查ActiveCell

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
If Target.Address(0, 0) = "A2" And ActiveCell.Cells(0, 0) = "A1" Then 
MsgBox ("test") 
End If 
End Sub 

是否有人有办法解决吗?

+0

你不能有细胞(0,0),因为这不存在 – QHarr

+2

看到这里回答:https://stackoverflow.com/questions/19179756/previous-active-cell – QHarr

+0

[Previously active cell](https://stackoverflow.com/questions/19179756/previously-active-cell) – YowE3K

回答

0

我想你在这里使用了错误的方法。

如果使用SelectionChange事件,则表示所选单元格已更改。每次调用事件时都必须存储最后一个单元格的地址。为了做到这一点,请在将ActiveCell作为lastCellAddress进行存储之前先将您的条件妥善保存。

这里是注释代码,以帮助您了解:

'Declare the variable out of the event 
Dim lastCellAddress As String 

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
    'Check if the last selected cell was A1 when selecting A2 
    If (ActiveCell.Address = "$A$2" And lastCellAddress = "$A$1") Then 
     'If the condition is true display your MsgBox 
     MsgBox ("test") 
    End If 

    'Set the current address as the last selected for next selection change 
    lastCellAddress = ActiveCell.Address 
End Sub 
+0

完美工作。谢谢。 – crat

+0

@crat很高兴帮助:) – Teasel