如何在excel中,在任意位置插入一行后,该行能自动复制上一行的所有公式及格式(用vba)?

如题所述

第1个回答  2012-01-17
输入一行会触发:Change事件
可以在这个该事件中写入代码就可以了。
(北京 黄吕娜)追问

能帮助我写个完整的代码吗?

追答

Private Sub Worksheet_Change(ByVal Target As Range)
a = Target.Row()
b = Target.Column()
If a 1 Then
If Cells(a, b) = "" And Cells(a - 1, b) "" Then
Rows(a - 1 & ":" & a - 1).Copy
Cells(a, b).Select
ActiveSheet.Paste
c = Cells(a, b)
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = c
Cells(a, b).Select
End If
End If
End Sub

追问

您好!我运行代码发现,连同上一行的数据也复制了,我想只复制公式即可,不用复制没有公式的数据,应该如何修改代码?非常感谢您!

追答

用下面的代码吧,我重写过了!
Private Sub Worksheet_Change(ByVal Target As Range)
a = Target.Row()
b = Target.Column()
Application.ScreenUpdating = False
If a 1 Then
If Cells(a, b) = "" And Cells(a - 1, b) "" Then
For x = 1 To 256
If Cells(a - 1, x).HasFormula = True Then
Cells(a - 1, x).Copy
Cells(a, x).Select
ActiveSheet.Paste
Application.CutCopyMode = False
End If
Next x
Cells(a, b).Select
End If
End If
Application.ScreenUpdating = True
End Sub

本回答被提问者采纳
第2个回答  2012-01-16
按选性粘贴,——公式,再录制宏会录出一条词句,写例程时再加上设定格式的语句。追问

能给出完整的代码吗

第3个回答  2012-01-16
选中插入的那行,按Ctrl+d
第4个回答  2012-01-16
复制a列—b列插入复制单元格
第5个回答  2012-01-16
把上面的复制下来呀
相似回答