我遇到了一点麻烦,我想将另一工作簿中的一列复制到一个新工作簿中并转置它,但出现如下错误: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/