2017-02-13 50 views
2

我正在嘗試將ActiveCell分配給變量以便稍後使用它。它給我一個超時錯誤。如何從ActiveCell中分配範圍以供將來參考(VBA)

代碼在下面,但通常我還沒有想出如何動態地給變量指定一個範圍。

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 
+3

使用'設置refCell = ActiveCell',並作爲Range' –

+0

你們是不是要救ActiveCell位置ASLO定義'昏暗refCell或者你試圖挽救該單元格中包含的價值? – amdopt

回答

3

也許你可以使用類似下面的代碼。 如果您遠離Select,ActiveCell,並嘗試儘可能使用合格的Range s更好。

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 
+0

完美。完成我想要做的,但更乾淨。謝謝! – VBAnking

+3

嘿,歡迎來到10K!恭喜! –

+0

@ Mat'sMug謝謝,現在我可以退休了:)或者拿起它 –