本文介绍了交换两个范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写用于交换两个范围的代码:

I am trying to write code for swapping two ranges:

Sub SwapRanges()
  Dim range1 As Range
  Dim range2 As Range
  Dim holder As Range

  range1 = Range("D7:D12")
  range2 = Range("E7:E12")
  holder = Range("F7:F12")

  Set holder = range1
  Set range1 = range2
  Set range2 = holder
End Sub

但收到运行时错误91 .

推荐答案

错误原因是分配范围时未使用 Set 命令.此外,请了解以下代码:

The cause of the error is that you are not using the Set command when assigning ranges. In addition, understand that this code:

Set holder = range1
Set range1 = range2
Set range2 = holder

仅更改变量 holder range1 range2 所引用的范围.它实际上并没有将这些引用中包含的数据从一个范围复制到另一个范围.

only changes the ranges referred to by the variables holder, range1, and range2. It doesn't actually copy the data contained in those references from one range to another.

下面的代码将执行实际的复制,同时还解决了运行时错误.

The code below will perform the actual copying while also addressing the run-time error.

Sub SwapRanges()
  Dim range1 As Range
  Dim range2 As Range
  Dim holder As Range

  Set range1 = Range("D7:D12")
  Set range2 = Range("E7:E12")
  Set holder = Range("F7:F12")

  range1.Copy holder
  range2.Copy range1
  holder.Copy range2
End Sub

这篇关于交换两个范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:51