gpt4 book ai didi

vba - 如何将数组粘贴到范围 [VBA] - 错误 1004

转载 作者:行者123 更新时间:2023-12-04 21:55:02 24 4
gpt4 key购买 nike

我一直在尝试将一张简单的表格从一张纸复制到第二张纸的最后一行。
最初我尝试使用数组,因为两张表具有不同的结构(列的顺序不同,所以我不能只是复制和粘贴),但我总是收到错误 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

编辑:按照 Tim Williams 的建议解决。但是,我仍然很好奇如何按照我最初的意图使用数组完成此操作。
假设 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

关于vba - 如何将数组粘贴到范围 [VBA] - 错误 1004,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46698207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com