excel - 错误 1004 : PasteSpecial method of range class failed

标签 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

最佳答案

问题原因

您正在尝试将单元格 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

关于excel - 错误 1004 : PasteSpecial method of range class failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40542355/

相关文章:

excel - 当单元格发生更改但数据尚未输入时,如何运行 Excel 宏?

vba - 将excel另存为pdf,将其方向更改为水平

excel - 如何删除小数但保留数字的值

python - 使用 Python 打印某个范围的总和值

excel - 检查合并的单元格是否为空白

excel - 如何在Excel中将第一个字母小写

python - 如何在 python 中将 .txt 转换为 .xls?

Excel 公式 - 使用单元格本身提供的条件

VBA 编辑器放入空间

excel - 将工作表保持在工作簿的首位