【发布时间】:2019-07-19 21:32:13
【问题描述】:
最初选择的单元格存储在rngStart 中,以便在最后重新选择,因此用户不会被宏带走。但是,rngStart 中存储的范围会发生变化。貌似是自己。它最终成为粘贴操作发生的范围。
Sub Macro2()
Application.ScreenUpdating = False
Dim rngStart 'The variable I'm struggling with
Dim ws As Worksheet
Set rngStart = Selection 'Store original selection
Set ws = ActiveSheet
Selection.Cut
'Find an empty cell in column B
For Each cell In ws.Columns(2).Cells
If IsEmpty(cell) = True Then cell.Select: Exit For
Next cell
ActiveSheet.Paste 'Upon executing this line, rngStart changes to the cell being pasted to
rngStart.Select 'Supposed to return to the originally selected range
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
不要使用
.Select,这是一个非常糟糕的做法:How to avoid using Select in Excel VBA。还有比循环更好的方法来查找下一个空单元格。 -
我确实想选择,所以用户自己的选择似乎没有移动。
-
啊,这是因为您将原始范围(通过剪切/粘贴)移动到了新位置。所以由于
rngStart对象引用了范围,并且范围移动了,它实际上是新的位置。 -
@Pᴇʜ 正是我要说的,所以不要在最后使用
rngStart,为什么不只选择一个您希望用户结束的单元格。