如何将数组粘贴到范围 – 错误1004

我一直在试图从1张表中复制一张简单的表格到第二张纸的最后一行。 最初我尝试与数组,因为这两个工作表有不同的结构(列不是在同一个顺序,所以我不能只是复制和粘贴),但我总是得到错误1004.现在我放弃了,并改变了表所以他们有相同的结构,现在我只能简单地复制和粘贴,但我仍然得到同样的错误。 这是我迄今为止。 我知道这是一个非常简单的事情,但我不知道我错在哪里。

Sub testy() Dim rowsIn, rowsOut As Long With Worksheets("Sheet1") rowsIn = .Cells.SpecialCells(xlLastCell).Row .Range(.Cells(4, 1), .Cells(rowsIn, 3)).Copy End With With Worksheets("Sheet2") rowsOut = .Cells.SpecialCells(xlLastCell).Row .Range(.Cells(rowsOut + 1, 3)).PasteSpecial xlPasteValues End With End Sub 

编辑:根据蒂姆·威廉姆斯的build议解决。 不过,我仍然很好奇,如何用数组来完成这个工作,就像我原本打算的那样。 假设Sheet1中的数据具有不同于Sheet2的顺序的列,我尝试使用临时数组来订购这些列,以便我可以将其粘贴。 我设法填充数组很好,但无法弄清楚如何获取数组的内容到Sheet2中。 添加了我用来填充(非常无效的方式)数组的代码。

 Sub testy2ElectricBoogaloo() Dim arr() As Variant Dim rowsIn, rowsOut, i As Long With Worksheets("Sheet1") rowsIn = .Cells.SpecialCells(xlLastCell).Row ReDim arr(1 To rowsIn - 3, 1 To 5) 'Array populated with a loop because columns are not in the same order, don't know if this is the most efficient method For i = 1 To UBound(arr) arr(i, 1) = "Constant1" 'data collected from other source arr(i, 2) = "Constant2" 'data collected from other source arr(i, 3) = .Cells(i + 3, 2).Value arr(i, 4) = .Cells(i + 3, 1).Value arr(i, 5) = .Cells(i + 3, 3).Value Next i End With End Sub 

这是无效的:

 .Range(.Cells(rowsOut + 1, 3)).PasteSpecial xlPasteValues 

你可以使用:

 .Cells(rowsOut + 1, 3).PasteSpecial xlPasteValues 

您可以在不使用复制/粘贴的情况下执行此操作:

 Sub testy() Dim rowsIn, rowsOut As Long, rng As Range With Worksheets("Sheet1") rowsIn = .Cells.SpecialCells(xlLastCell).Row Set rng = .Range(.Cells(4, 1), .Cells(rowsIn, 3)) End With With Worksheets("Sheet2") rowsOut = .Cells.SpecialCells(xlLastCell).Row .Cells(rowsOut + 1, 3)).Resize(rng.Rows.Count, _ rng.Columns.Count).Value = rng.Value End With End Sub 

编辑:使用你的arr例子是相当相似的:

  With Worksheets("Sheet2") rowsOut = .Cells.SpecialCells(xlLastCell).Row .Cells(rowsOut + 1, 3)).Resize(UBound(arr, 1), _ UBound(arr, 2)).Value = arr End With