获取对象_worksheet的运行时错误1004方法粘贴失败

时间:2019-08-31 14:36:00

标签: excel vba

以下代码无法获取对象_worksheet的运行时错误1004方法粘贴 请帮忙,谢谢您。

Sub Move()
    Dim lastrow As Long, erow As Long

    lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
    For i = 1 To lastrow
        Sheet1.Cells(i, 1).Copy
        erow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

        Sheet1.Paste Destination = Worksheets("Sheet2").Cells(erow, 1)

        Sheet1.Cells(i, 2).Copy
        Sheet1.Paste Destination = Worksheets("Sheet2").Cells(erow, 2)

        Sheet1.Cells(i, 3).Copy
        Sheet1.Paste Destination = Worksheets("Sheet2").Cells(erow, 3)
    Next i

    Application.CutCopyMode = False
    Sheet2.Columns().AutoFit`
    Range("A1").Select
End Sub

2 个答案:

答案 0 :(得分:0)

四处走动,并在一行中完成整个操作:

Sub Move()
    Dim lastrow As Long, erow As Long

    lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
    erow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    Sheet1.Range(Sheet1.Cells(1, 1),Sheet1.Cells(lastrow , 3)).Copy Sheet2.Cells(erow, 1)

    Application.CutCopyMode = False
    Sheet2.Columns().AutoFit
    Range("A1").Select
End Sub

现在,如果这不起作用,则可能是代码名称不正确,应该分别用Sheet1Sheet2替换所有Worksheets("Sheet1")Worksheets("Sheet2")

答案 1 :(得分:0)

通过@ScottCraner解决方案,您可以使用With ...End With块管理工作表引用,并避免重复:

Sub Move()    
    With Sheet1 ' reference Sheet1 once and for all...
        .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)).Resize(, 3).Copy Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) ' all Range objects beginning with dots are referencing the object after `With` keyword (i.e. Sheet1)
    End With
    Sheet2.Columns.AutoFit
End Sub

顺便说一句,使用Destination方法的Copy参数,您无需“激活” CutCopyMode,因此无需将其设置为False


,如果您仅对复制/粘贴值感兴趣,则嵌套另一个With ...End With块以引用“源”范围:

Sub Move()    
    With Sheet1 ' reference Sheet1 once and for all...
        With .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)).Resize(, 3) ' reference Sheet1 columns A:C range from row 1 down to column A last not empty cell
            Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Resize(.Rows.Count, .Columns.Count).Value = .Value ' get Sheet2 range as its column A last not empty cell, resize it as last referenced range and fill it with its values
        End With
    End With
    Sheet2.Columns.AutoFit
End Sub