【问题标题】:Why would a range variable change when selected? [duplicate]为什么选择范围变量时会发生变化? [复制]
【发布时间】: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,为什么不只选择一个您希望用户结束的单元格。

标签: excel vba


【解决方案1】:

将其保存为字符串。

Sub Macro2()

    Application.ScreenUpdating = False

    Dim rngStart As String 'The variable I'm struggling with
    Dim ws As Worksheet

    rngStart = Selection.Address 'Store original selection
    Set ws = ActiveSheet

    Selection.Cut
    'Find an empty cell in row 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
    Range(rngStart).Select  'Supposed to return to the originally selected range

    Application.ScreenUpdating = True

End Sub

【讨论】:

    【解决方案2】:

    记住您的起始范围地址以返回那里。另请注意,有一种更快的方法可以找到列中的下一个空行:

    Sub Macro2()
        Application.ScreenUpdating = False
    
        Dim ws As Worksheet
        Set ws = ActiveSheet
    
        Dim rngStart As Range
        Set rngStart = Selection
    
        Dim OriginalAddress As String
        OriginalAddress = rngStart.Address
    
        rngStart.Cut
    
        ws.Cells(ws.Rows.Count, "B").End(xlUp).Offset(RowOffset:=1).Select
        ws.Paste
    
        ws.Range(OriginalAddress).Select
    
        Application.ScreenUpdating = True
    End Sub
    

    【讨论】:

    • much faster way - 这样会找到 在最后一个填充单元格之后的第一个空单元格(错误地,顺便说一句:如果 B 列中没有数据,或者如果B)的最后一个单元格中有数据。 OP 的代码在数据中查找第一个空单元格(可用于填补空白),因此这不等效。
    • @GSerg 虽然您在技术上是正确的,但我假设该列在粘贴时没有间隙(如果有以下数据,这很容易覆盖数据)。但是从技术上讲,你是对的,它会找到最后使用的单元格 +1。
    • @Pᴇʜ 感谢您的解决方案。将地址存储为字符串有效。
    猜你喜欢
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2021-10-07
    • 2014-03-25
    • 1970-01-01
    相关资源
    最近更新 更多