交换两个范围

时间:2015-11-25 19:27:45

标签: excel vba excel-vba

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

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

3 个答案:

答案 0 :(得分:3)

错误的原因是您在分配范围时未使用Set命令。另外,要了解这段代码:

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

仅更改变量holderrange1range2引用的范围。它实际上并不会将这些引用中包含的数据从一个范围复制到另一个范围。

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

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

答案 1 :(得分:0)

我会尝试这种方式(对不起,未经测试 - 从Chrombook写作:)

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

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

  holder = range1    
  range1 = range2
  range2 = holder
End Sub

答案 2 :(得分:0)

而不是应对你可以说:        支架=范围1        范围2 =范围1        支架=范围2

pnuts没有真正回答这个问题,但我认为这对你的申请有帮助。