将值复制并粘贴到另一个工作表excel宏

时间:2019-01-05 08:54:53

标签: excel-formula

我是Macro的新手,我想创建一个简单的副本并将excel公式从一张纸粘贴到另一张纸。但事实是,主要数据在单元格内部有一个公式,它不允许我将其作为值复制并粘贴到另一个单元格中。

Sub selectpasting()
Dim Lastrow As Long, erow As Long


Lastrow = Sheets("attendance").Cells(Rows.Count, 1).End(xlUp).Row
For i = 3 To Lastrow


   If Sheets("attendance").Cells(i, 3) = "absent" Then

    Sheets("attendance").Cells(i, 1).copy
    erow = Sheets("forpasting").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

    Sheets("attendance").Paste Destination:=Sheets("forpasting").Cells(erow, 1)


    Sheets("attendance").Cells(i, 3).copy
    Sheets("attendance").Paste Destination:=Sheets("forpasting").Cells(erow, 2)

End If

Next i


Application.CutCopyMode = False
Sheets("forpasting").Columns.AutoFit
Range("A1").Select

End Sub

1 个答案:

答案 0 :(得分:1)

更改此行:

Sheets("attendance").Paste Destination:=Sheets("forpasting").Cells(erow, 1)

收件人:

Sheets("forpasting").Cells(erow, 1).PasteSpecial xlValues

完整的代码为:

Sub selectpasting()
Dim Lastrow As Long, erow As Long
Dim i As Long

Lastrow = Sheets("attendance").Cells(Rows.Count, 1).End(xlUp).Row
For i = 3 To Lastrow


   If Sheets("attendance").Cells(i, 3) = "absent" Then

    Sheets("attendance").Cells(i, 1).Copy
    erow = Sheets("forpasting").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

    Sheets("forpasting").Cells(erow, 1).PasteSpecial xlValues


    Sheets("attendance").Cells(i, 3).Copy
    Sheets("forpasting").Cells(erow, 2).PasteSpecial xlValues
End If

Next i


Application.CutCopyMode = False
Sheets("forpasting").Columns.AutoFit
Range("A1").Select

End Sub

上面的代码很慢(尝试使用这两个代码,您会发现下面的代码更快)。原因是在上面的excel中需要确定/评估是否需要粘贴单元格属性或并非由于“ .copy”。当您需要复制/粘贴单元格格式等时,这是一种方法。

在您的情况下,您只对单元格显示的值感兴趣。因此,您只需选择值并复制即可。

因此,我建议您将其更改为:

Sub selectpasting_2()
Dim Lastrow As Long, erow As Long
Dim i As Long

Lastrow = Sheets("attendance").Cells(Rows.Count, 1).End(xlUp).Row
For i = 3 To Lastrow


   If Sheets("attendance").Cells(i, 3) = "absent" Then


    erow = Sheets("forpasting").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

    Sheets("forpasting").Cells(erow, 1) = Sheets("attendance").Cells(i, 1)

    Sheets("forpasting").Cells(erow, 2) = Sheets("attendance").Cells(i, 3)
End If

Next i


Application.CutCopyMode = False
Sheets("forpasting").Columns.AutoFit
Range("A1").Select

End Sub