Excel宏复制公式&复制/粘贴值

时间:2017-10-11 19:48:38

标签: excel vba excel-vba

我正在尝试创建一个Excel宏来复制已使用范围内的公式,然后复制表单并粘贴值。

我在想我将需要复制的公式存放在第1行的模板文件中。然后,用户可以将数据输入到任意数量的行中,宏将所有公式复制到所有使用的行,然后复制/粘贴整个工作表的值。

任何人都可以帮忙写这个吗?我曾试图自己写这篇文章,但是还没有能够走得很远。

谢谢!

编辑 - 我相信我的副本部分已经失效了。现在我只需要从第4行开始,在大部分工作表上复制/粘贴值。

    Sub Forecast()

Application.ScreenUpdating = False


  ' Get the last row on the sheet - store as variable
  Dim LastRow As Integer
  LastRow = Range("A1").End(xlDown).Row

  ' Copy cells K3:AY3  to  cells K4:AY[LastRow]
  Range(Cells(3, 11), Cells(3, 51)).AutoFill _
         Destination:=Range(Cells(3, 11), Cells(LastRow, 51))

Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:0)

要复制两个位置之间的可变行数的值,请执行以下操作:

Dim r_src as Range, r_dst as Range
' Set to the top cell of the source
Set r_src = Sheet1.Range("A2")

Dim n as Long
' Count the non-empty cells
n = Sheet1.Range(r_src, r_src.End(xlDown)).Rows.Count

' Set the range to include all 'n' cells using the `.Resize()` command
Set r_src = r_src.Resize(n,1)
' Set 'n' values in the destination sheet also
Set r_dst = Sheet2.Range("A2").Resize(n,1)

'This actually copies the range as values in one swoop
r_dst.Value = r_src.Value

要复制公式,您可以使用

r_dst.FormulaR1C1 = r_src.FormulaR1C1