excel - 从上面复制公式

标签 excel vba

我们有一个宏,通过 Excel 2013 中的按钮来插入包含上面公式的新行。问题是当它运行时,我说例如从第 10 行复制新第 11 行中的公式仍然读回第 10 行而不是第 11 行?

Sub Loop_InsertRowsandFormulas()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Risk Input Sheet")
Dim vRows As Long
Dim lastCol As Long
Dim firstRow As Long

firstRow = InputBox("Enter Row To Start Insert From.")
vRows = InputBox("Enter Number Of Rows Required")

If firstRow = 0 Or vRows = 0 Then Exit Sub
Debug.Print firstRow
IngA = ws.Cells(5, ws.Columns.Count).End(xlToLeft).Column
For myLoop = 1 To vRows
    ws.Range("A" & (firstRow + myLoop)).EntireRow.Insert
    ws.Range("A" & (firstRow + myLoop) & ":BB" & (firstRow + myLoop)).Formula = ws.Range("A" & firstRow & ":BB" & firstRow).Formula
Next

End Sub

最佳答案

您需要进行复制/粘贴。例如,如果 A1 包含:

=B1+C1

运行:

Sub qwerty()
    Range("A2").Formula = Range("A1").Formula
End Sub

也会将 A2 保留为 =B1+C1

如果您希望“调整”复制的公式,则:

Sub ytrewq()
    Range("A1").Copy Range("A2")
End Sub

编辑#1:

而不是:

ws.Range("A" & (firstRow + myLoop) & ":BB" & (firstRow + myLoop)).Formula = ws.Range("A" & firstRow & ":BB" & firstRow).Formula

使用类似的东西:

ws.Range("A" & firstRow & ":BB" & firstRow).Copy ws.Range("A" & (firstRow + myLoop) & ":BB" & (firstRow + myLoop))

关于excel - 从上面复制公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37965078/

相关文章:

php - 使用 PhpSpreadsheet 获取列范围

mysql - Excel VBA & MYSQL 的 Select LAST_INSERT_ID();

vba - 运行时错误 1004

macos - Excel VBA : Run time error 7: Out of Memory

Excel重置 "UsedRange"

excel - VB Excel 删除单元格中指定值的行

php - 通过 php 将 csv 导入 mysql

c# - 在 C# 中创建自定义 ODBC/OLE 驱动程序

arrays - 在 Excel 中打印特定工作表,具有不同的打印区域和使用 VBA 的打印设置

sql-server - 按时 Access 过滤器