【问题标题】:VBA dynamic range for formulas公式的 VBA 动态范围
【发布时间】:2017-08-23 18:01:24
【问题描述】:

我在下面发布了我的代码的 sn-p。我的实际工作簿有更多的公式,但它们的结构都类似于下面的公式。我正在使用的数据量可能会逐月变化,所以我永远不知道我需要公式来执行多少行。我的小技巧是为所有公式 "XX2:XX500" 设置目标范围,因为永远不会超过 500 行。

'November Remaining Spending Plan
 Range("BF2").Select
 ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""","""",RC[-43]+RC[-40]+RC[-37]+RC[-34]+RC[-31]+RC[-28]+RC[-25]+RC[-22])"
 Selection.AutoFill Destination:=Range("BF2:BF500")

'December Remaining Spending Plan
 Range("BG2").Select
 ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""","""",RC[-41]+RC[-38]+RC[-35]+RC[-32]+RC[-29]+RC[-26]+RC[-23])"
 Selection.AutoFill Destination:=Range("BG2:BG500")

我想使范围动态化,以便删除

"IF(RC[-1]="""","""","

部分公式和在工作簿中包含额外公式并不适合数据透视表和其他用户。

我尝试过使用 LastRow、FillDown、CurrentRegion 的组合来处理范围,但我没有任何运气。

每个公式应具有与所有其他公式相同的行数,并且公式的数量应始终等于 A 列中的行数减 1(减 1 用于标题)。

有办法清理吗?

谢谢!

【问题讨论】:

    标签: excel vba


    【解决方案1】:
    Dim lastRow As Long
    Dim ws As Worksheet
    'Always set the parent of all Range Objects
    Set ws = ActiveSheet 'This should be called by name: Worksheets("Sheet1")
    
    ' this assumes column "A" is the column which sets the lastrow.
    'If a different column sets the end of the dataset change "A" to that column
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    'do not use .Select or .Activate it slows the code
    'You do not need autofill just put it in all the cells at once
    
    
    'November Remaining Spending Plan
     ws.Range("BF2:BF" & lastRow).FormulaR1C1 = "=RC[-43]+RC[-40]+RC[-37]+RC[-34]+RC[-31]+RC[-28]+RC[-25]+RC[-22]"
    
    'December Remaining Spending Plan
     ws.Range("BG2:BG" & lastRow).FormulaR1C1 = "RC[-41]+RC[-38]+RC[-35]+RC[-32]+RC[-29]+RC[-26]+RC[-23]"
    

    【讨论】:

    • 这太好了 - 谢谢!再问你一个问题,我怎么做才能使用“Dim lastRow As Long Dim ws As WorksheetSet ws = ActiveSheet Worksheets("Sheet1") lastRow = ws.Cells(ws.Rows.Count, "A")。 End(xlUp).Row" 跨其他模块?有没有办法将其设置为公开?如果不能在其他模块中使用,我可以将公式全部移动到一个模块中。现在我的范围为 X2:XX500 的公式位于多个模块中。
    • 只需创建一个公共变量。在一个模块的顶部放置Public lastrow as Long 然后在子模块中删除Dim lastrow as Long。然后你设置它一次,当 Excel 打开并且你不在任何代码中单独使用 End 时。它将保持该值,并且可以被其他模块调用和使用。
    • 这是我现在拥有的,在其他模块中没有。 'On Top of Module 1 Public LastRow As Long 'In Module 1 where variable is defined Sub VariableTest() Dim ws As Worksheet Set ws = Worksheets("Test") LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row 然后我在第二个模块中进行了计算。 'Calculation in Module 2 Sub Test() 'New Nov Rem Est ws.Range("D2:D" & LastRow).FormulaR1C1 = "=RC[-2]-RC[1]" End Sub
    • 此时由于难以在 cmets 中格式化代码,请根据您的尝试提出一个新问题。
    【解决方案2】:

    听起来您每月都在刷新数据,并且需要在数据右侧的列中包含公式。问题是如何确定将公式放入哪些行。简短的答案是将代码放入 ThisWorkBook!Workbook_Open() 子中以删除从行 BF2 到 BG500 的范围(因为这是最大范围),然后从第 2 行复制公式到您拥有数据的行数。您提到了 LastRow,所以我假设您知道如何执行此操作。您需要示例代码还是足以让您入门?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      相关资源
      最近更新 更多