如何从ActiveCell分配范围以供将来参考(VBA)

我正在尝试将ActiveCell分配给一个variables,以便稍后使用它。 它给我一个超时错误。

代码如下,但通常我还没有想出如何dynamic地给variables分配一个范围。

Sub findCells() Dim topCell As Integer Dim left_Cell As Integer Set refCell = Range(ActiveCell) refCell.End(xlUp).Select topCell = ActiveCell.Value MsgBox topCell refCell.End(xlToLeft).Select leftCell = ActiveCell.Value MsgBox leftCell End Sub 

也许你可以使用类似下面的代码。 最好是远离SelectActiveCell ,尽量使用合格的Range

 Option Explicit Sub findCells() Dim topCell As Long Dim leftCell As Long Dim refCell As Range Set refCell = ActiveCell topCell = refCell.End(xlUp).Value ' <-- gets the value of the top cell topCell = refCell.End(xlUp).Row ' <-- gets the row number of the top cell MsgBox topCell leftCell = refCell.End(xlToLeft).Value ' <-- gets the value of the column to the left leftCell = refCell.End(xlToLeft).Column ' <-- gets the column number of the column to the left MsgBox leftCell End Sub