在没有剪贴板的情况下复制到动态范围

时间:2017-10-12 17:42:10

标签: vba excel-vba excel

我正在尝试将值粘贴到不同工作表的动态范围而不使用剪贴板。当代码到达Range = Range部分时,它会出错,说明“应用程序定义的或对象定义的错误”。有什么想法吗?

Sub Test2()
Dim Start As Worksheet
Dim ED As Worksheet
Dim r As Integer, c As Integer, r1 As Integer, c1 As Integer

Set Start = Sheets("Start")
Set ED = Sheets("End")

r = 1
c = ActiveSheet.UsedRange.Columns.Count



With Start
    Do Until .Cells(r, c).Value = ""
        r = r + 1

    Loop
    r = r - 1

End With
 r1 = 1
 c1 = ActiveSheet.UsedRange.Columns.Count

With ED

    Do Until .Cells(r1, c1).Value = ""
        r1 = r1 + 1

    Loop
    r1 = r1

 Range(Cells(r1, 1), Cells(r1 + r - 1, c1)) = Start.Range(Cells(r, c), Cells(1, 1))

 Start.Activate

1 个答案:

答案 0 :(得分:3)

  1. 始终限定每个范围对象的每个父级。 Range()内的Cells()需要指向同一个父级:
  2.   

    Start.Range(Start.Cells(r, c), Start.Cells(1, 1))

    1. 我们不需要循环,但可以使用END()查找最后的列和行。
    2. 替换:

      Do Until .Cells(r, c).Value = ""
          r = r + 1
      
      Loop
      r = r - 1
      

      使用:

      c = .Cells(1, .Columns.Count).End(xlToLeft).Column
      r = .Cells(.Rows.Count, c).End(xlUp).Row
      
      1. 使用Resize,它更短更容易维护:
      2.   

        .Cells(r1+1, 1).Resize(r, c).Value = Start.Cells(1, 1).Resize(r, c).Value

        所以:

        Sub Test2()
        Dim Start As Worksheet
        Dim ED As Worksheet
        Dim r As Long, c As Long, r1 As Long, c1 As Long
        
        Set Start = Sheets("Start")
        Set ED = Sheets("End")
        
        With Start
            c = .Cells(1, .Columns.Count).End(xlToLeft).Column
            r = .Cells(.Rows.Count, c).End(xlUp).Row
        End With
        With ED
            c1 = .Cells(1, .Columns.Count).End(xlToLeft).Column
            r1 = .Cells(.Rows.Count, c1).End(xlUp).Row
            .Cells(r1+1, 1).Resize(r, c).Value = Start.Cells(1, 1).Resize(r, c).Value
        End With