首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用动态范围用公式自动填充多个单元格

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

Stack Overflow用户
提问于 2016-11-23 13:46:05
回答 2查看 2.2K关注 0票数 0

我有一个动态表,它是基于细胞(4,"D")和细胞(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)

我的代码

代码语言:javascript
复制
 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

有人能帮我吗?

EN

回答 2

Stack Overflow用户

发布于 2016-11-23 14:46:54

这将将实际公式填充到范围中,然后用值替换它。我还将lastrow更改为long,以便它可以正确地在其他行中使用,并从您的范围中提取起始行。

代码语言:javascript
复制
 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的行,而不是硬编码。

代码语言:javascript
复制
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中,这样它将从正确的工作表中提取所有值。

票数 0
EN

Stack Overflow用户

发布于 2016-11-23 14:51:27

它用公式填充B栏:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40766203

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档