简体   繁体   English

使用参考单元格通过VBA在一系列单元格中插入公式

[英]Insert a formula in a range of cells via VBA using reference cells

I have a code that loops through and calculates a formula for a column of inputs for a row of dates. 我有一个循环遍历并为一行日期的输入列计算公式的代码。 It is rather slow looping and writing in VBA so I was hoping to instead paste the formula in the cells instead of the computed value. 用VBA循环和编写相当慢,所以我希望将公式粘贴到单元格中,而不是将计算值粘贴到单元格中。 My plan is to create a range for the results and set the range equal to the formula. 我的计划是为结果创建一个范围,并将范围设置为等于公式。

However I am stuck with the formula. 但是,我坚持使用公式。 The formula uses the previous answer plus other data and I am stuck trying to create the formula for the range so the reference cells move for each cell in the range. 该公式使用了先前的答案以及其他数据,我被困于尝试为范围创建公式,以便参考单元格为该范围内的每个单元格移动。

The formula will look like this for cell N7 N7单元格的公式如下所示

   =IF(M7<>0,(M7-$D7)^(1/30.4),$B7*(1-$C7)^(1/$E7))

The formula will look like this when copied to cell O7 复制到单元格O7时,公式将如下所示

  =IF(N7<>0,(N7-$D7)^(1/30.4),$B7*(1-$C7)^(1/$E7))

For O8 it would look like this 对于O8,它看起来像这样

  =IF(N8<>0,(N8-$D8)^(1/30.4),$B8*(1-$C8)^(1/$E8))

I understand how to loop through each cell and write the formula, but I don't think it would be much faster than calculating it and then writing the answer. 我知道如何遍历每个单元格并编写公式,但是我认为这不会比计算公式然后编写答案快得多。 I was hoping there is a way to set the range equal to a formula that would populate the correct cell references. 我希望有一种方法可以将范围设置为等于可填充正确单元格引用的公式。

Would ActiveCell.Offset be a solution? ActiveCell.Offset是解决方案吗?

Use relative references: 使用相对参考:

.FormulaR1C1 = "=IF(RC[-1]<>0,(RC[-1]-RC4)^(1/30.4),RC2*(1-RC3)^(1/RC5))"

You can use this on a range to populate in one go if you need rather than looping through with something like this: 如果需要,可以在一定范围内一次使用它来填充,而不是像这样循环遍历:

Range("N7:P20").FormulaR1C1 = "=IF(RC[-1]<>0,(RC[-1]-RC4)^(1/30.4),RC2*(1-RC3)^(1/RC5))"

R is row and C is column relative to self negatives have to be in [] R为行,C为列,相对于自身负数必须位于[]中

You can also do this by using A1 Notation . 您也可以使用A1 Notation来执行此操作。

Range("N7:O8").Formula = "=IF(M7<>0,(M7-$D7)^(1/30.4),$B7*(1-$C7)^(1/$E7))"

There are advantages using R1C1 Notation but for this one, you better off using this, easier to read. 使用R1C1 Notation有很多优点,但是对于这一点,您最好使用这种R1C1 Notation而且更易于阅读。 HTH. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM