【问题标题】:copy and paste as values to another sheet, excel macro将值复制并粘贴到另一个工作表,excel宏
【发布时间】:2019-01-05 08:54:53
【问题描述】:

我是 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

【问题讨论】:

标签: excel-formula


【解决方案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

【讨论】:

  • 太好了,它确实奏效了。你救了我的命。这太棒了。希望你能帮助我未来在 Macro 的旅程。上帝保佑你!
  • 嗨,:)。我不确定我是否理解您想要实现的目标......如果您还想使用“If Sheets("attendance").Cells(i, 3) = "time" Then”,您可以添加ElseIf 语句。参考使用方法可以找到here。否则,我建议您创建一个新问题,其中包含一些您想要实现的示例/图片,人们肯定会帮助您,包括我 =)!!
  • 期待我知道您可以回答的下一个问题。干杯! :)
  • 您好,先生,我能够回答我自己的问题 :) 嗯。还是谢谢
  • 太棒了!!我印象深刻:)。随时欢迎您提问:)。祝你的项目好运!。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多