错误1004:范围类的PasteSpecial方法失败

时间:2016-11-11 06:31:18

标签: excel

我遇到了一点麻烦,我想将另一个工作簿中的一列复制到一个新的工作簿中并进行转置,但我有一个错误:Error 1004: PasteSpecial method of range class failed

Private Sub CommandButton1_Click()

    ActiveSheet.Range("C2:C30").Copy
    Workbooks.Open Filename:="E:\PENDIDIKAN_BJN\SUM.xlsx"
    eColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
    If eColumn >= 1 Then eColumn = eColumn + 1
    ActiveSheet.Cells(1, eColumn).Select
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, Skipblanks:=False, Transpose:=True
    ActiveWorkbook.Save
    ActiveWorkbook.Close
    Application.CutCopyMode = False

End Sub

1 个答案:

答案 0 :(得分:1)

问题原因

您正在尝试将单元格C2复制到C30,通过转置它们将29个单元格(30-2 + 1)复制到另一个工作簿。换句话说,您将这些单元格粘贴为包含29列的单行。

在您的其他工作簿中,您可以使用If eColumn >= 1 Then eColumn = eColumn + 1“动态”选择列,因此您无需选择29列进行粘贴。

最后的结果是错误消息Error 1004: PasteSpecial method of range class failed

<强>解决方案

其中一个解决方案是直接选择正确数量的列来粘贴数据,并按照以下方式执行:

Private Sub CommandButton1_Click()

    ActiveSheet.Range("C2:C30").Copy
    ' Store the number of rows selected in the eColumn associated before opening the other file
    ' Since this is a transposition the number of rows is the same as the target number of columns
    eColumn = Selection.Rows.Count

    Workbooks.Open Filename:="E:\PENDIDIKAN_BJN\SUM.xlsx"
    ActiveSheet.Cells(1, eColumn).Select
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, Skipblanks:=False, Transpose:=True
    ActiveWorkbook.Save
    ActiveWorkbook.Close
    Application.CutCopyMode = False

End Sub