如何使用动态范围使用公式自动填充多个单元格

时间:2016-11-23 13:46:05

标签: vba excel-vba autofill excel

我有一个基于Cell(4," D")和Cells(6," D")的乘法创建的动态表,它给出了总行数。列号是固定的,并从B到G定义。带数据的第一行是第13行。

我想写一个公式deltaMassFormula,在B列中引入以下内容:deltaMassFormula = D13 *(G13 - F13)并自动填充,直到countRows等于总行数(乘法变量)

例如,如果乘法= 4则

E13 = D13 *(G13-F13)

E14 = D14 *(G14-F14)

E15 = D15 *(G15 - F15)

E16 = D16 *(G16 - F16)

我的代码

 Dim StartCellM As Range    
 Dim lastRow As Long    
 Dim deltaMassFormula As Integer    
 Dim multiplication As Integer

 multiplication = Cells(4, "D").Value * Cells(6, "D").Value    
 countRows = multiplication - 1

 Set StartCellM = Cells(13, "E")    
 Set lastRow = Cells(13, "E") + countRows

 deltaMassFormula = Cells(13, "D") * (Cells(13, "G") - Cells(13, "F"))

 With ThisWorkbook.Sheets(1)     
    .Range("E13").Formula = deltaMassFormula    
    .Range("E13:E" & lastRow).FillDown    
 End With

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

这会将实际公式填入范围,然后将其替换为值。我还将lastrow更改为long,以便可以正确使用其他行并从您的范围中拉出起始行。

 Dim StartCellM As Range
 Dim lastRow As Long
 Dim multiplication As Integer

 With ThisWorkbook.Sheets(1) 
     multiplication = .Range("D4").Value * .Range("D6").Value
     countRows = multiplication - 1

     Set StartCellM = .Range("E13")
     lastRow = StartCellM.Row + countRows

    .Range("E13:E" & lastRow).Formula = "=D13*(G13-F13)"
    .Range("E13:E" & lastRow).Value = .Range("E13:E" & lastRow).Value 'Remove this line to keep formula
 End With

如果更改开始单元格所在的行并且不更改公式中的行以匹配,则公式将中断,因此此代码将使用公式中StartCellM的行而不是硬编码。

Dim StartCellM As Range
Dim lastRow As Long, startRow As Long
Dim multiplication As Integer

With ThisWorkbook.Sheets(1)
    multiplication = .Range("D4").Value * .Range("D6").Value
    countRows = multiplication - 1

    Set StartCellM = .Range("E13")

    startRow = StartCellM.Row
    lastRow = startRow + countRows

    .Range("E" & startRow & ":E" & lastRow).Formula = "=D" & startRow & "*(G" & startRow & "-F" & startRow & ")"
    .Range("E" & startRow & ":E" & lastRow).Value = .Range("E" & startRow & ":E" & lastRow).Value 'Remove this line to keep formula
End With

我还移动了With内的所有内容,以便从正确的工作表中提取所有值。

答案 1 :(得分:0)

它用以下公式填充B列:

Sub filler()

    Dim i As Long
    Dim startRow As Long
    Dim lastRow As Long
    Dim multiplication As Integer

    multiplication = Cells(4, 4).Value * Cells(6, 4).Value

    startRow = 13
    lastRow = startRow + multiplication - 1

    For i = startRow To lastRow
        Cells(i, 2).Formula = "=D" & i & "*(G" & i & "-F" & i & ")"
    Next i

End Sub
相关问题