简体   繁体   中英

How to assign range from ActiveCell for future reference (VBA)

I am trying to assign the ActiveCell to a variable in order to use it later. It gives me a timeout error.

Code is below, but generally I haven't figured out how to assign a range to a variable dynamically.

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

Maybe you can use something like the code below. It's better if you stay away from Select , ActiveCell , and try to use qualified Range s as much as possible.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM